cannot generate code for file - oop

Please have a look at the following code
Formula.ads
package Formula is
procedure CalculateFormula;
end Formula;
Formula.adb
with Ada.Text_IO; use Ada.Text_IO;
with Formula; use Formula;
package body Formula is
procedure CalculateFormula is
package fom_io is new Ada.Float_Text_IO(Float);
use fom_io;
u : Float;
t : Float;
a : Float;
answer : Float;
begin
put_line("Enter 'U'");
get(u);
put_line("Enter 'T'");
get(t);
put_line("Enter 'A'");
get(a);
answer = (u*t)+ 0.5(a(t*t));
put("Answer is: ");
put(answer,Fore => 1,Aft => 1,Exp => 1);
end CalclualeFormula;
end Formula;
When I run this code, I get the following error
gnatmake -d -PC:\Users\yohan\Documents\Ada\Formula\formula.gpr
gcc -c -I- -gnatA C:\Users\yohan\Documents\Ada\Formula\formula.ads
cannot generate code for file formula.ads (package spec)
gnatmake: "C:\Users\yohan\Documents\Ada\Formula\formula.ads" compilation error
[2013-04-06 03:18:22] process exited with status 4 (elapsed time: 00.22s)
I am very new to Ada. Started coding few hours back. Please help me to get rid of the above issue. Thank you.
EDIT
formula.gpr
project Formula is
for Main use ("formula.ads");
end Formula;

The GPR file shows that you are trying to use a package specification as a main program unit - that doesn't work.
Two ways to fix this: The simplest one is to make "CalculateFormula" a standalone main program in a file "calculateformula.adb" and set this in your project file:
for Main use ("calculateformula.adb");
But if you want to see how packages work, there is a "better" way (in that it gets you to understand what packages are for and how they are used...)
Packages are reusable components : the package spec is all you need to see in order to use them ... but you actually use them in another program. So in this case you would create a main program
with Formula; use Formula;
procedure MyMain is
begin
CalculateFormula;
end MyMain;
and in the .gpr file,
for Main use ("mymain.adb");
And then the compiler will automatically compile the correct packages and find the other issues that Shark has pointed out.
You really don't need a separate Main here, as the "hello world" example showed. However such trivial "main subprograms" (in the correct Ada lingo) are not so unusual, especially for purposes like unit testing packages to be used in more complex apps later.

This is puzzling because there are some big errors that the compiler should be flagging, like:
package fom_io is new Ada.Float_Text_IO(Float);
which isn't withed, and
answer = (u*t)+ 0.5(a(t*t));
because:
= is not the assignment operator; you need :=.
0.5(XXXX) isn't valid multiplication.
Also, there's exponentiation in Ada, so t**2 can replace t*t.
formula.adb
with
Ada.Float_Text_IO,
Ada.Text_IO;
use
Ada.Text_IO;
package body Formula is
procedure CalculateFormula is
use Ada.Float_Text_IO;
u, t, a, answer : Float;
Procedure Prompt( Item : out Float; Name : String ) is
begin
put_line("Enter '"& Name &"'");
get(Item);
end prompt;
begin
prompt( u, "U" );
prompt( t, "T" );
prompt( a, "A" );
answer:= (u*t) + 0.5*( a*t**2 );
put("Answer is: ");
put(answer,Fore => 1,Aft => 1,Exp => 1);
New_Line;
end CalculateFormula;
end Formula;
This corrects the syntax errors you had. The other answer seems right in that this ["cannot generate code for" error] seems to be a problem with the gpr-file rather than the source itself.

Related

plsql : New function inside an existing package compilation and syntax check

How do I compile a new function created inside a package in plsql, to see syntactical error and so on
You can't compile a single function - compile the whole package.
If your concern is about invalidating the whole package in case that function has errors, then
create a standalone function (i.e. outside of the package)
debug it
once it is OK (doesn't have syntax errors, returns result as expected), include it into the package
In addition to #Littefoot's advise I'd say: use a proper GUI. Oracle has a free tool called sql developer. It has a great interface for editing database objects (packages/functions/procedures/triggers). It highlights errors and is very well documented (https://www.thatjeffsmith.com/sql-developer/). Note that is does not point out syntax errors - but once you're a bit used to working with pl/sql they become obvious very quickly.
In Oracle, after compiling a procedure/function/package. If there is an error then the command will return with the message:
ORA-24344: success with compilation error
You can then use:
SHOW ERRORS
or
SELECT * FROM USER_ERRORS;
or, for example, for errors with packages in a specific schema:
SELECT *
FROM ALL_ERRORS
WHERE owner = 'SCHEMA_NAME'
AND type IN ( 'PACKAGE', 'PACKAGE BODY');
Which will list the errors (complete with line numbers and error messages) and you can then debug the procedure/function/package and recompile it.
fiddle

How to tell whether elaboration has completed at a breakpoint?

When I hit a breakpoint in a VLAB script, how can I find out if I have caused elaboration to finish or not, yet?
My script reaches a statement that raises an error:
Error: (E529) insert module failed: elaboration done
(The command that causes this is vlab.instantiate("stim", "stim"))
So obviously elaboration was unexpectedly (for me) already completed. I need to somehow go back in the process and find out where that happened - so I need some way of asking "is elaboration complete?" at the point where I set breakpoints earlier in the script.
SystemC provides the following function to query the current phase of elaboration or simulation.
sc_status sc_get_status();
It returns either SC_ELABORATION, SC_BEFORE_END_OF_ELABORATION, SC_END_OF_ELABORATION, SC_START_OF_SIMULATION, SC_RUNNING, SC_PAUSED, SC_STOPPED, or SC_END_OF_SIMULATION.
See section 4.5.8 in the SystemC Language Reference Manual for more details. Note that this function was only added in the most recent version of the standard, IEEE Standard 1666-2011.
In VLAB, the SystemC API is available from the sysc Python package, so the following script can be used to test if the current phase is at elaboration:
import sysc
print "Is elaboration phase:", sysc.sc_get_status() == sysc.SC_ELABORATION

Runtime error with no apparent cause

I'm working with files in free pascal and I'm trying to open a file, but if it doesn't exists then I create it.
This is my code:
program messages;
const PATH_ = 'data/messages/';
type messageFields =
record
date : String
; viewed : Boolean
; text : String
; sender : String [ 8 ]
end
; messagesFile = file of messageFields
;
procedure openMessagesFile ( var _file: messagesFile; _fileName: String; var error: Boolean );
begin
error := false;
assign ( _file, PATH_+_fileName );
{$I-}
reset ( _file );
{$I+}
if ( ioResult <> 0 ) then
error := true;
end;
var _file: messagesFile
; fileName: String
; error: boolean;
begin
readln(filename);
openMessageFile(_file, filename, error);
if ( error ) then
rewrite(_file);
end.
The first time that I execute the program, since the file doesn't exists, throw me an exception.
The second time, works fine!
This is the exception:
An unhandled exception occurred at $00401759 :
EInOutError : Access denied
Have you reproduced this error with the exact code you've posted and I really can't see it causing the error you're getting. I cannot reproduce it and since you haven't included uses SysUtils you should get Runtime error 5 instead of EInOutError.
One thing that's terribly wrong with your code is that you're not closing the file after opening/creating it (although OS usually cleans it up after program finishes). Given this and the fact that you're getting EInOutError instead of Runtime error 5 I believe that your (real, bigger) program keeps the file open after creating it and trying to open it later, but fails since the file is already opened. The second time you run the program the file is already created so it's only opened once (for reading).
The code is a bit atypical, but Windows is known to keep fleeting locks on files for a few seconds even after they are closed and Dos originating code like this might suffer from that.
Maybe using FPC's FileExist() directly works better (IIRC on windows it is findfirst based, and not createfile based)

Fortran Module Version Fatal Error

I have a very scary error on Fortran 95:
Fatal Error: While reading module 'list5.mod' found module version 0, expected 6
I have included the main structure of my module. I highly doubt it has anything to do with the substance inside my module since it has given me error messages on those and I have been able to fix them which means it is able to go through my module fine it is just something small related to the way I use the module. Perhaps?
MODULE list5
IMPLICIT NONE
CONTAINS
----
END MODULE
The main program is structured something like this:
PROGRAM mainlist
USE list5
IMPLICIT NONE
!Variable Declaration
INTEGER:: opt
INTEGER, PARAMETER:: maxitems=50
INTEGER:: size=0
CHARACTER(20):: itemarray(50)
INTEGER:: quantityarray(50)
INTEGER:: totalquantity, i=0
REAL:: totalprice=0, pricearray(50)=0
CHARACTER(20), DIMENSION(:)::Item
CHARACTER(20):: ItemSought
LOGICAL:: Found
INTEGER:: Location
INTEGER:: NumItems=0, SmallestItem=0
!Select statement for the menu
DO
opt=choices()
SELECT CASE (opt)
CASE(1)
size=size+1
CALL getItemData(itemarray,pricearray,quantityarray)
CASE(2)
CALL getFileItems(size,itemarray,pricearray,quantityarray)
CASE(3)
CALL pickItemRandomly (size)
CASE(4)
CALL calcListTotals
(pricearray,quantityarray,totalprice,totalquantity)
CALL printList(size,itemarray,pricearray,quantityarray,totalprice, totalquantity)
CASE(5)
CALL sortByItem(itemarray, pricearray, quantityarray)
CASE(6)
CALL sortByPrice(itemarray, pricearray, quantityarray)
CASE(7)
CALL writeListtoFile(size,itemarray, pricearray, quantityarray)
CASE(8)
CALL search(itemarray, ItemSought, Found, Location)
CASE(9)
STOP
END SELECT
END DO
END PROGRAM
Any suggestions at all?? I really need to solve this so any help would be appreciated. Thanks so much!!
As Rook says, the issue is with compiler versions; somehow the .mod file from by compiling list5 the first time around was generated by an older compiler. Clear out all your .o and .mod files, and try again, first compiling list5.f90 (or whatever the file containing module list5 is) and then compiling the main program.

Setting up diagnostic error messages in large Mathematica projects

Whenever I create a large Mathematica project I run into this problem: Preventing avalanche of runtime errors in Mathematica, i.e., Mathematica's error message are opaque, archaic, and legion.
The idea then is to disable all of Mathematica's own error messages and implement type checking and error messages of your own in every Function and Module. However I have not found a simple and efficient way of doing this and end up with, e.g., some function generating an error 20 function calls deep and then get a whole cascade of error messages all the way back up to the main routine.
How would you set up a simple mechanism for this that only generates one error message at the function that experiences the error and a simple list of the chain of function calls?
EDIT: Since it has come up in a couple of answers; I am specifically looking for something lightweight regarding the output it produces (otherwise I could just stick with Mathematica's error messages) and obviously also lightweight in computational overhead. So while Stack and Trace are definitely light on the overhead, their output in complex projects is not quick to parse and some work needs to be done simplifying it.
YAsI - Yet Another (silly?) Idea ...
Re-reading your question ...
The idea then is to disable all of Mathematica's own error messages and implement type checking and error messages of your own in every Function and Module.
Found this:
$MessagePrePrint = ( #; Print[Stack[_][[;; -5]]]; Abort[]) &
v[x_, y_] := w[x, y];
w[x_, y_] := x/y;
StackComplete#v[1, 0];
During evaluation of In[267]:= {StackComplete[v[1,0]];,
StackComplete[v[1,0]], v[1,0], w[1,0], 1/0, 1/0, Message[Power::infy,1/0]}
Out[267]= $Aborted
conclusion ... Aborts at first message and leaves a "reasonable" stack trace. "Reasonable" means "Should be improved".
But it is completely non-intrusive!
To get the ball rolling here is one idea that I've been toying with; the creation of a pseudo stack.
First make a global variable theStack={} and then in every Function or Module start with AppendTo[theStack,"thisFuncName"] and end with theStack=Most#theStack. Assuming moderate (~a few tens) depth of function calls, this should not add any significant overhead.
Then implement your own typing/error checking and use Print#theStack;Abort[]; on errors.
Refinements of this method could include:
Figuring out a way to dynamically get "thisFuncionName" so that the AppendTo[] can be made into an identical function call for all Functions and Module.
Using Message[] Instead of Print[].
Pushing other important variables / stateful information on theStack.
One attempt to implement #Timo's idea (theStack)
Incomplete and perhaps flawed, but just to keep thinking about it:
Clear["Global`*"];
funcDef = t_[args___] \[CircleMinus] a_ :>
{t["nude", args] := a,
ReleaseHold[Hold[t[args] :=
(If[! ValueQ[theStack], theStack = {}];
AppendTo[theStack, ToString[t]];
Check[ss = a, Print[{"-TheStack->", Evaluate#theStack}];
Print#Hold[a]; Abort[]];
theStack = Most#theStack;
Return[ss])
]]};
v[x_, y_]\[CircleMinus] (Sin# g[x, y]) /. funcDef;
g[x_, y_]\[CircleMinus] x/y /. funcDef;
v[2, 3]
v[2, 0]
Output:
Out[299]= Sin[2/3]
During evaluation of In[295]:= Power::infy: Infinite expression 1/0 encountered. >>
During evaluation of In[295]:= {-TheStack->,{v,g}}
During evaluation of In[295]:= Hold[2/0]
Out[300]= $Aborted
A suggestion for extracting stack, maybe something that relies on Trace?
An example of using Trace below, from Chris Chiasson. This code saves evaluation tree of 1 + Sin[x + y] + Tan[x + y] into ~/temp/msgStream.m
Developer`ClearCache[];
SetAttributes[recordSteps, HoldAll];
recordSteps[expr_] :=
Block[{$Output = List#OpenWrite["~/temp/msgStream.m"]},
TracePrint[Unevaluated[expr], _?(FreeQ[#, Off] &),
TraceInternal -> True];
Close /# $Output;
Thread[
Union#Cases[
ReadList["~/temp/msgStream.m", HoldComplete[Expression]],
symb_Symbol /;
AtomQ#Unevaluated#symb &&
Context#Unevaluated#symb === "System`" :>
HoldComplete#symb, {0, Infinity}, Heads -> True],
HoldComplete]
];
recordSteps[1 + Tan[x + y] + Sin[x + y]]
To answer Samsdram's question, the code below (also from Chris) gives evaluation tree of a Mathematica expression. Here is the post from MathGroup with source code and examples.
(Attributes## = {HoldAllComplete}) & /# {traceToTreeAux, toVertex,
HoldFormComplete, getAtoms, getAtomsAux}
MakeBoxes[HoldFormComplete[args___], form_] :=
MakeBoxes[HoldForm[args], form]
edge[{head1_, pos1_, xpr1_}, {head2_, pos2_, xpr2_}] :=
Quiet[Rule[{head1, vertexNumberFunction#pos1, xpr1}, {head2,
vertexNumberFunction#pos2, xpr2}], {Rule::"rhs"}]
getAtomsAux[atom_ /; AtomQ#Unevaluated#atom] :=
Sow[HoldFormComplete#atom, getAtomsAux]
getAtomsAux[xpr_] := Map[getAtomsAux, Unevaluated#xpr, Heads -> True]
getAtoms[xpr_] := Flatten#Reap[getAtomsAux#xpr][[2]]
toVertex[traceToTreeAux[HoldForm[heldXpr_], pos_]] := toVertex[heldXpr]
toVertex[traceToTreeAux[HoldForm[heldXprs___], pos_]] :=
toVertex#traceToTreeAux[Sequence[], pos]
(*this code is strong enough to not need the ToString commands,but \
some of the resulting graph vertices give trouble to the graphing \
routines*)
toVertex[
traceToTreeAux[xpr_, pos_]] := {ToString[
Short#Extract[Unevaluated#xpr, 0, HoldFormComplete], StandardForm],
pos, ToString[Short#First#originalTraceExtract#{pos}, StandardForm]}
traceToTreeAux[xpr_ /; AtomQ#Unevaluated#xpr, ___] := Sequence[]
traceToTreeAux[_HoldForm, ___] := Sequence[]
traceToTreeAux[xpr_, pos_] :=
With[{lhs = toVertex#traceToTreeAux[xpr, pos],
args = HoldComplete ## Unevaluated#xpr},
Identity[Sequence][
ReleaseHold[
Function[Null, edge[lhs, toVertex##], HoldAllComplete] /# args],
ReleaseHold#args]]
traceToTree[xpr_] :=
Block[{vertexNumber = -1, vertexNumberFunction,
originalTraceExtract},
vertexNumberFunction[arg_] :=
vertexNumberFunction[arg] = ++vertexNumber;
originalTraceExtract[pos_] :=
Extract[Unevaluated#xpr, pos, HoldFormComplete]; {MapIndexed[
traceToTreeAux, Unevaluated#xpr, {0, Infinity}]}]
TraceTreeFormPlot[trace_, opts___] :=
Block[{$traceExpressionToTree = True},
Through#{Unprotect, Update}#SparseArray`ExpressionToTree;
SparseArray`ExpressionToTree[trace, Infinity] = traceToTree#trace;
With[{result = ToExpression#ToBoxes#TreeForm[trace, opts]},
Through#{Unprotect, Update}#SparseArray`ExpressionToTree;
SparseArray`ExpressionToTree[trace, Infinity] =.;
Through#{Update, Protect, Update}#SparseArray`ExpressionToTree;
result]];
TraceTreeFormPlot[Trace[Tan[x] + Sin[x] - 2*3 - 55]]
Perhaps we have been over thinking this. What if we just tweaked the pattern matching on the arguments a little. For instance, if we modified the function to check for a numeric quantity and added some code to print an error if it fails. For instance,
TypeNumeric[x_] := If[! NumericQ[Evaluate[x]],
Print["error at "]; Print[Stack[]]; Print["Expression "]; Print[x]; Print["Did
not return a numeric value"];Return[False],
(*Else*)
Return[True];]
SetAttributes[TypeNumeric, HoldAll];
Step 2: If you have a function, f[x_] that requires a numeric quantity, just write it with the standard pattern test and all should be well
Input:
f[x_?TypeNumeric] := Sqrt[x]
f[Log[y]]
f[Log[5]]
Output:
error at
{f}
Expression
Log[y]
Did not return a numeric value
f[Log[y]]
Sqrt[Log[5]]
I believe this will work and, it makes robust type checking as simple as a writing a function or two. The problem is that this could be hugely inefficient because this code evaluates the expression x twice, once for the type checking and once for real. This could be bad if an expensive function call is involved.
I haven't figured out the way around this second problem and would welcome suggestions on that front. Are continuations the way out of this problem?
Hope this helps.