Access a Left or Right child in a Custom KlocWork Checker - klocwork

I'm trying to write a Custom KlocWork checker for c++ however im stuck with an issue:
When we have an expression like this one:
x = y + z;
I want to access the left node which is the variable 'x' but also both variables from the Right node(Left and Right from the RIGHT NODE) i don't know how to access every variable, so far i have this in my checker:
// BinaryExpr [ getOperationCode() = KTC_OPCODE_ASSIGN]
[$exprL:= Left]
[$size1:= $exprL.getTypeSize()]
[$exprR:= Right]
[$exprR.getOperationCode() = KTC_OPCODE_ADD]
Which detects every BinaryExpression with another expression on the Left Node(store in $exprR) but after that i don't know how to access Left and Right childs of $exprR.
Thanks in advance for any help!

There are two nested expressions here, and you want to store the Left node of the assignment and then continue to traverse the AST further using the full pattern to the second binary expression node to get the left and right nodes of the add. For example:
// BinaryExpr [getOperationCode() = KTC_OPCODE_ASSIGN] [$exprOL:= Left]
Here we find and store the left node of the assignment expression.
// BinaryExpr [getOperationCode() = KTC_OPCODE_ASSIGN] [$exprOL:= Left] / Right::BinaryExpr [getOperationCode() = KTC_OPCODE_ADD]
And then we continue on to get the addition expression. Finally, we can grab Left and Right of this expression:
// BinaryExpr [getOperationCode() = KTC_OPCODE_ASSIGN] [$exprOL:= Left] / Right::BinaryExpr [getOperationCode() = KTC_OPCODE_ADD]
[$exprL:= Left]
[$exprR:= Right]
You can use the println() function to test this. So the complete expression
// BinaryExpr [getOperationCode() = KTC_OPCODE_ASSIGN] [$exprOL:= Left] / Right::BinaryExpr [getOperationCode() = KTC_OPCODE_ADD]
[$exprL:= Left]
[$exprR:= Right]
[$exprOL.getName().println()]
[$exprL.getName().println()]
[$exprR.getName().println()]
for the following code:
int func (int x, int y)
{
int local;
local = x;
local = x + y;
local = y - x;
return local;
}
Would print out:
local
x
y

Related

How to generate arbitrary instances of a language given its concrete syntax in Rascal?

Given the concrete syntax of a language, I would like to define a function "instance" with signature str (type[&T]) that could be called with the reified type of the syntax and return a valid instance of the language.
For example, with this syntax:
lexical IntegerLiteral = [0-9]+;
start syntax Exp
= IntegerLiteral
| bracket "(" Exp ")"
> left Exp "*" Exp
> left Exp "+" Exp
;
A valid return of instance(#Exp) could be "1+(2*3)".
The reified type of a concrete syntax definition does contain information about the productions, but I am not sure if this approach is better than a dedicated data structure. Any pointers of how could I implement it?
The most natural thing is to use the Tree data-type from the ParseTree module in the standard library. It is the format that the parser produces, but you can also use it yourself. To get a string from the tree, simply print it in a string like so:
str s = "<myTree>";
A relatively complete random tree generator can be found here: https://github.com/cwi-swat/drambiguity/blob/master/src/GenerateTrees.rsc
The core of the implementation is this:
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
Tree randomTree(type[Tree] gr)
= randomTree(gr.symbol, 0, toMap({ <s, p> | s <- gr.definitions, /Production p:prod(_,_,_) <- gr.definitions[s]}));
Tree randomTree(\char-class(list[CharRange] ranges), int rec, map[Symbol, set[Production]] _)
= randomChar(ranges[arbInt(size(ranges))]);
default Tree randomTree(Symbol sort, int rec, map[Symbol, set[Production]] gr) {
p = randomAlt(sort, gr[sort], rec);
return appl(p, [randomTree(delabel(s), rec + 1, gr) | s <- p.symbols]);
}
default Production randomAlt(Symbol sort, set[Production] alts, int rec) {
int w(Production p) = rec > 100 ? p.weight * p.weight : p.weight;
int total(set[Production] ps) = (1 | it + w(p) | Production p <- ps);
r = arbInt(total(alts));
count = 0;
for (Production p <- alts) {
count += w(p);
if (count >= r) {
return p;
}
}
throw "could not select a production for <sort> from <alts>";
}
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
It is a simple recursive function which randomly selects productions from a reified grammar.
The trick towards termination lies in the weight of each rule. This is computed a priori, such that every rule has its own weight in the random selection. We take care to give the set of rules that lead to termination at least 50% chance of being selected (as opposed to the recursive rules) (code here: https://github.com/cwi-swat/drambiguity/blob/master/src/Termination.rsc)
Grammar terminationWeights(Grammar g) {
deps = dependencies(g.rules);
weights = ();
recProds = {p | /p:prod(s,[*_,t,*_],_) := g, <delabel(t), delabel(s)> in deps};
for (nt <- g.rules) {
prods = {p | /p:prod(_,_,_) := g.rules[nt]};
count = size(prods);
recCount = size(prods & recProds);
notRecCount = size(prods - recProds);
// at least 50% of the weight should go to non-recursive rules if they exist
notRecWeight = notRecCount != 0 ? (count * 10) / (2 * notRecCount) : 0;
recWeight = recCount != 0 ? (count * 10) / (2 * recCount) : 0;
weights += (p : p in recProds ? recWeight : notRecWeight | p <- prods);
}
return visit (g) {
case p:prod(_, _, _) => p[weight=weights[p]]
}
}
#memo
rel[Symbol,Symbol] dependencies(map[Symbol, Production] gr)
= {<delabel(from),delabel(to)> | /prod(Symbol from,[_*,Symbol to,_*],_) := gr}+;
Note that this randomTree algorithm will not terminate on grammars that are not "productive" (i.e. they have only a rule like syntax E = E;
Also it can generate trees that are filtered by disambiguation rules. So you can check this by running the parser on a generated string and check for parse errors. Also it can generated ambiguous strings.
By the way, this code was inspired by the PhD thesis of Naveneetha Vasudevan of King's College, London.

Copy and paste shape from one sheet to another

Can someone tell me why this excel VBA to copy and paste a shape from one sheet to another fails? The shape "StandingsPix" and sheet "Pictures" exist in my workbook and in fact when I record a macro to do this manually, it creates similar code.
It fails in the assignment of "p" with "Object Variable Not Set". Help greatly appreciated.
Sub CopyPictureToScorecard(TargetCells As Range)
Dim p As Shape
Dim p2 As Shape
Dim TargetWS As Worksheet
Set TargetWS = Sheets("Scorecards")
p = Sheets("Pictures").Shapes.Range(Array("StandingsPix")) <== Fails Here
p.Copy
TargetWS.Paste
'make sure the picture is properly centered on the scorecard
Set p2 = TargetWS.Shapes(TargetWS.Shapes.Count)
p2.Width = p.Width
p2.Height = p.Height
p2.Top = TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2)
p2.Left = TargetCells.Left + (TargetCells.Width / 2) - (p2.Width / 2)
p2.Line.Visible = False
End Sub
When I record a macro doing this manually (successfully!), here is the code that it generated:
Sheets("Pictures").Select
ActiveSheet.Shapes.Range(Array("StandingsPix")).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Scorecards").Select
Range("K24").Select
ActiveSheet.Paste
Selection.ShapeRange.IncrementLeft 621
Selection.ShapeRange.IncrementTop -369.75
Sub CopyPictureToScorecard(TargetCells As Range)
Dim p As Shape
Set p = Sheets("Pictures").Shapes("StandingsPix")
Sheets("ScoreCards").Shapes.AddShape _
Type:=p.AutoShapeType, _
Left:=TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2), _
Top:=TargetCells.Top + (TargetCells.Height / 2) - (p2.Height / 2), _
Width:=p.Width, _
Height:=p.Height
End Sub

Proper usage of lua tables/classes

I'm trying to use class behavior in lua where there is a ship that has two other classes pos and vector
But I cannot get it working like I assumed I would be able to
Point = {x=0, y=0}
function Point:new(p)
p = p or {}
return p
end
Ship =
{
pos = {Point:new{x=0,y=0}},
vector = {Point:new{x=0,y=0}} -- I thought this would be sufficient for access being available for vector
}
-- create new ship class
function Ship:new(pos)
p = p or {}
p.pos = pos
p.vector = Point:new{x=0,y=0} -- I need to do this or accessing vector will crash (The problem)
return p
end
-- Create new ship...
plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300
If anyone knows how to make the above code cleaner/better I would be thankful
You can use metatables to set default fields. (I've made some assumptions about what you're trying to do. If this doesn't work for you, please add some clarification to your question.)
local Point = {x=0, y=0}
Point.__index = Point
function Point:new(p)
p = p or {}
setmetatable(p, self)
return p
end
-- create new ship class
local Ship = {}
Ship.__index = Ship
function Ship:new(pos)
setmetatable(pos, Point)
local p = {pos = pos, vector = Point:new()}
setmetatable(p, self)
return p
end
-- Create new ship...
local plrShip = Ship:new{}
plrShip.pos.x = 300
plrShip.pos.y = 300
I found solution to do this, it still not perfect but only I got working was this modified code:
Ship =
{
pos = Point:new{x=0,y=0},
vector = Point:new{x=0,y=0}
}
function Ship:new()
p = p or {}
p.pos = self.pos
p.vector = self.vector
return p
end
plrShip = Ship:new()
plrShip.pos.x = 300
plrShip.pos.y = 300

Orientdb get last vertex from each path when Traversing by edge property

I need to traverse all vertices that are connected by edges where the property 'dependence' is 'true'
This is what I have so far:
SELECT
FROM (TRAVERSE *
FROM (SELECT outE() FROM 9:5)
WHILE (#class = 'E' AND dependence = 'yes') OR #class = 'V')
WHERE #class = 'V'
Although im not sure if is the best way to do it, this seems to work fine following only the paths where edges have 'dependence' = 'yes'.
Now, There could be more than one path generated, and I need to get the last vertex from each path/branch.
traverserdVertex(-1) should return the last one, but im guessing that is from the whole traversal so is no good. (and it looks like there's a bug because it retrieves more than one)
The outer SELECT returns the whole bag of vertices so I'm thinking that maybe finding the ones that doesn't have an outgoing edge with dependence='yes' might solve it, although I'm not sure how to do it nicely.
SOLUTION:
SELECT
FROM (TRAVERSE *
FROM (SELECT outE() FROM 9:5)
WHILE (#class = 'E' AND dependence = 'yes') OR #class = 'V')
WHERE #class = 'V' AND NOT (outE() contains (dependence='yes'))
This effectively returns the last vertex from each branch. I'm open to any other option, I'm wondering if it could be improved.
I tried with an example by building the following graph
The javascript function "myFunction" has three parameters which are ridVertex, property and value
var g=orient.getGraph();
var previous=[];
var currently=[];
var node=[];
var b=g.command("sql","select from v where #rid =" + ridVertex);
if(b.length>0){
previous.push(b[0]);
node.push(b[0]);
do{
for(i=0;i<previous.length;i++){
var edges=g.command("sql","select expand(outE()) from V where #rid = "+ previous[i].getId());
var myVertex=[];
for(j=0;j<edges.length;j++){
var edge=edges[j];
var dependence=edge.getProperty(property);
if(dependence==value){
var vIn=edge.getProperty("in");
myVertex.push(vIn);
}
}
if(myVertex.length>0){
setPaths();
}
}
change();
}while(previous.length>0);
}
return node;
function setPaths(){
for (m = 0; m < node.length; m++) {
var lastId=node[m].getId().toString();
var idOut=previous[i].getId().toString();
if (lastId==idOut) {
for(r=0;r<myVertex.length;r++){
var vertex=myVertex[r];
node.push(vertex);
currently.push(vertex);
}
node.splice(m,1);
break;
}
}
}
function change(){
previous=[];
for (indice=0;indice<currently.length;indice++)
previous.push(currently[indice]);
currently=[];
}
Using the following command
select expand(result) from (select myFunction("#9:0","dependence","yes") as result)
the paths are A -> D and A -> B -> C -> G and then will be returned the verteces D and G
The following is a slight simplification of #sebastian's solution, using Allesandro's graph (with dependentOn.value being 0 or 1):
select from
(TRAVERSE * FROM (select from Circle where name="A")
while (#CLASS="dependentOn" and value=1) OR #CLASS="Circle")
where #CLASS='Circle' AND NOT (outE().value contains 1)
----+-----+------+----+--------------
# |#RID |#CLASS|name|in_dependentOn
----+-----+------+----+--------------
0 |#11:6|Circle|G |[#12:4]
1 |#11:3|Circle|D |[#12:1]

how to compute ceiling of log2 in e hardware verification language

The 'e' language has a 'ilog2' function but I need a 'ceiling of log2' type function - what's the best way to do this?
I could invoke a Perl through the system command and use POSIX::ceil...
Invoking perl script might be computational expensive. Instead add 0.5 to log2 and typecast (not sure if e-language supports it) to integer.
Another try:
Let y = ilog2(x);
if ((x & x-1) == 0) //Check if x is power of 2
return y;
else
return y+1;
I would have done something like this:
ceil_log2(in : uint): uint is {
var bottom := ilog2(in);
result = (in == ipow(2,bottom)) ? bottom : bottom + 1;
};
If you don't mind doing it in real:
ceil_log2(in: uint): uint is {
result = ceil(log10(in)/log10(2)).as_a(uint);
};