Why my rules of bison don't work - syntax-error

Every time I run my parser, it will appear "syntax error in line 1 near <>" (Because there is a subroutine yyerror(char *s)). I think that's because there is something wrong with my rules in bison.
The file (c17.isc) I want to parse.
*c17 iscas example (to test conversion program only)
*---------------------------------------------------
*
*
* total number of lines in the netlist .............. 17
* simplistically reduced equivalent fault set size = 22
* lines from primary input gates ....... 5
* lines from primary output gates ....... 2
* lines from interior gate outputs ...... 4
* lines from ** 3 ** fanout stems ... 6
*
* avg_fanin = 2.00, max_fanin = 2
* avg_fanout = 2.00, max_fanout = 2
*
*
*
*
*
1 1gat inpt 1 0 >sa1
2 2gat inpt 1 0 >sa1
3 3gat inpt 2 0 >sa0 >sa1
8 8fan from 3gat >sa1
9 9fan from 3gat >sa1
6 6gat inpt 1 0 >sa1
7 7gat inpt 1 0 >sa1
10 10gat nand 1 2 >sa1
1 8
11 11gat nand 2 2 >sa0 >sa1
9 6
14 14fan from 11gat >sa1
15 15fan from 11gat >sa1
16 16gat nand 2 2 >sa0 >sa1
2 14
20 20fan from 16gat >sa1
21 21fan from 16gat >sa1
19 19gat nand 1 2 >sa1
15 7
22 22gat nand 0 2 >sa0 >sa1
10 20
23 23gat nand 0 2 >sa0 >sa1
21 19
My flex file is as follows and it is right. You can find some information about how my scanner work here.
Error in the output of my flex file
declare.h
# include <stdio.h>
# include <string.h>
# include <stdlib.h>
# define INPT 1
# define NOR 2
# define NAND 3
# define NOT 4
# define XOR 5
# define AND 6
# define BUFF 7
# define FROM 8
flex file is
%{
# include "declare.h"
# include "parse.tab.h"
/*gi=1,it's input;gi=8,it's fanout;otherwise,it's gate*/
static int gi=-1;
static int inum=0;
struct{
char *symbol;
int val;
} symtab[]={
{"inpt", INPT},
{"nor", NOR},
{"nand", NAND},
{"not", NOT},
{"xor", XOR},
{"and", AND},
{"buff", BUFF},
{"from",FROM},
{"0",0}
};
extern FILE *yyin;
extern int yylval;
%}
%start A B C D E
DIGITS [0-9]+
BLANK [ \t\n\r\f\v\b]+
ALPHA [a-z]+
%%
"*".*\n {BEGIN A; return(COMMENT);}
<A>{DIGITS} {yylval=atoi(yytext); BEGIN B; return(NUM);}
<B>{DIGITS}{ALPHA} {yylval=atoi(yytext); BEGIN C; return(GNAME);}
<C>{DIGITS} {yylval=atoi(yytext); BEGIN D; return(OPNUM);}
<C>{DIGITS}{ALPHA} {yylval=atoi(yytext); BEGIN A; return(FR);}
<D>{DIGITS} {inum=atoi(yytext);
yylval=inum;
if(gi==1)
{BEGIN A;}
if(gi!=1)
{BEGIN E;}
return(IPNUM);
}
<E>{DIGITS} {inum--;
yylval=atoi(yytext);
if(inum<0)
{BEGIN B; return(NUM);}
else
{BEGIN E; return(ILIST);}
}
{ALPHA} {yylval=lookup(yytext);
return(GTYPE);
}
">sa"[0-1] {yylval=atoi(&yytext[yyleng-1]);return(FAULT);}
{BLANK} ;
. ;
%%
int lookup(const char *s)
{
int i;
for (i = 0; symtab[i].val != 0; i++)
{
if (strcmp(symtab[i].symbol, s) == 0)
break;
}
return(symtab[i].val);
}
The right rules in bison file are as follows
parto:
| parto COMMENT
| parto parti
;
parti: NUM
{...}
GNAME
{...}
GTYPE
{...}
| parti partii
| parti partiii
;
partii:OPNUM
{...}
IPNUM
{...}
partiv
partv
;
partiii: FR
{...}
partiv
;
partiv:
| partiv FAULT
{...}
;
partv:
| partv ILIST
{...}
;

Transferring the key comments into an answer.
The first edition of the code had a couple of problems. In the scanner code, there were lines like this:
<A>{DIGITS} { yylval=atoi(yytext); return(NUM); BEGIN B; }
You should be getting warnings about unreachable code from the BEGIN operations appearing after return. The BEGIN operations have to be executed. They aren't being executed, so you're not switching into your start states.
Michael commented:
There is no warning. I've modified it as you say and edit my codes in the question. Now I put return after BEGIN. Still, "syntax error in line 1 near <�>".
This probably means you aren't compiling the C code with enough warnings. Assuming you're using GCC, add -Wall to the compilation options for starters. There's a chance the warning requires optimization too.
Have you printed the tokens as they're returned (in the Flex scanner)? Have you compiled the Bison grammar with -DYYDEBUG? You also need to turn the debug on: yydebug = 1; in the main() program. You're probably not getting the tokens you expect when you expect them. I've not tried compiling this code yet. Tracking the tokens is key (in my experience) to getting grammars to work. Otherwise, you're running blind.
The other problem (closely related) is that you need to generate the symbolic names for FAULT etc from the grammar (bison -d grammar.y generates grammar.tab.h). You'll find that COMMENT is assigned the value 258, for example. Your scanner, though, is returning other numbers altogether because they're in declare.h. You'll have to fix this mismatch. One option is to #include "grammar.tab.h" in your scanner; this is more or less normal.
In retrospect, I think this is probably the most important observation; things seemed to revert to normal C debugging after this was resolved.
(People often include 'grammar.h' and only update 'grammar.h' if the content of 'grammar.tab.h' changes, so you don't recompile the scanner all the time).
The significance of this is that the set of tokens used by a grammar tends to be fairly stable while the actions associated with the rules change all the time as the implementation of the grammar evolves. So, if it takes enough time to be worth worrying about, you can create file grammar.h that is a copy of grammar.tab.h, but only update grammar.h when the content of grammar.tab.h changes.
cmp -s grammar.tab.h grammar.h || cp grammar.tab.h grammar.h
You'd include this in the makefile rule that converts that grammar into a C file (or an object file).
If the scanner is small enough and your machine fast enough, it may be simpler not to bother with this refinement; it mattered more in the days of 50 MHz machines with a few MiB of RAM than it does in these days of multiple cores running at 2+ GHz with a few GiB of RAM.

Related

gcov - how to reset the coverage statistics in the C/C++ code

This question is related to googletest - command line option to execute "the first, the second, etc"
I want to be able to attribute given coverage results to each googletest test case.
QUESTION
In my C++ code, is it possible to reset the statistics?
Every time a test-case is done executing, I would save the accumulated gcov statistics and reset them.
From within your C++ code you could try it with __gcov_dump and __gcov_reset. They are mentioned in the GNU documentation although there is surprisingly limited info on them.
Below is a C++ program main.cpp that calls both.
1 #include <iostream>
2 #include <signal.h>
3
4 extern "C" void __gcov_dump(void);
5 extern "C" void __gcov_reset(void);
6
7
8 static void handler(int signum)
9 {
10 std::cout<<std::endl<<"Signal "<<signum<<" received!"<<std::endl;
11 __gcov_dump(); // Dump coverage upon interupt
12 std::cout<<"Coverage data dumped!"<<std::endl;
13 exit(0);
14 }
15
16
17 int main()
18 {
19 // Initialize signal handling
20 struct sigaction sa;
21
22 sa.sa_handler = handler;
23 sigemptyset(&sa.sa_mask);
24 sa.sa_flags = SA_RESTART;
25
26 if (sigaction(SIGINT, &sa, NULL) == -1)
27 std::cerr<<"ERROR: Could not register handler"<<std::endl;
28
29 // Main loop
30 while(true) {
31 int n;
32 std::cout<<"Type a number: ";
33 std::cin>>n;
34
35 if (n % 2 == 0) {
36 std::cout<<"Your number is even!"<<std::endl;
37 }
38 else {
39 std::cout<<"Your number is odd!"<<std::endl;
40 }
41 __gcov_reset(); // Reset coverage at the end of every iteration
42 }
43 }
If I compile it with g++ main.cpp --coverage -O0 and then run it as follows:
gomfy:gcov$ ./a.out
Type a number: 1
Your number is odd!
Type a number: 2
Your number is even!
Type a number: 3
Your number is odd!
Type a number: 4
Your number is even!
Type a number: ^C
Signal 2 received!
Coverage data dumped!
And then call gcovr in the build directory, I get:
gomfy:gcov$ gcovr
------------------------------------------------------------------------------
GCC Code Coverage Report
Directory: .
------------------------------------------------------------------------------
File Lines Exec Cover Missing
------------------------------------------------------------------------------
main.cpp 18 6 33% 12-13,17,22-24,26-27,35-36,39,41
------------------------------------------------------------------------------
TOTAL 18 6 33%
------------------------------------------------------------------------------
This shows that the coverage has been successfully reset at the end of the while loop.

Binding a scalar to a sigilless variable (Perl 6)

Let me start by saying that I understand that what I'm asking about in the title is dubious practice (as explained here), but my lack of understanding concerns the syntax involved.
When I first tried to bind a scalar to a sigilless symbol, I did this:
my \a = $(3);
thinking that $(...) would package the Int 3 in a Scalar (as seemingly suggested in the documentation), which would then be bound to symbol a. This doesn't seem to work though: the Scalar is nowhere to be found (a.VAR.WHAT returns (Int), not (Scalar)).
In the above-referenced post, raiph mentions that the desired binding can be performed using a different syntax:
my \a = $ = 3;
which works. Given the result, I suspect that the statement can be phrased equivalently, though less concisely, as: my \a = (my $ = 3), which I could then understand.
That leaves the question: why does the attempt with $(...) not work, and what does it do instead?
What $(…) does is turn a value into an item.
(A value in a scalar variable ($a) also gets marked as being an item)
say flat (1,2, (3,4) );
# (1 2 3 4)
say flat (1,2, $((3,4)) );
# (1 2 (3 4))
say flat (1,2, item((3,4)) );
# (1 2 (3 4))
Basically it is there to prevent a value from flattening. The reason for its existence is that Perl 6 does not flatten lists as much as most other languages, and sometimes you need a little more control over flattening.
The following only sort-of does what you want it to do
my \a = $ = 3;
A bare $ is an anonymous state variable.
my \a = (state $) = 3;
The problem shows up when you run that same bit of code more than once.
sub foo ( $init ) {
my \a = $ = $init; # my \a = (state $) = $init;
(^10).map: {
sleep 0.1;
++a
}
}
.say for await (start foo(0)), (start foo(42));
# (43 44 45 46 47 48 49 50 51 52)
# (53 54 55 56 57 58 59 60 61 62)
# If foo(42) beat out foo(0) instead it would result in:
# (1 2 3 4 5 6 7 8 9 10)
# (11 12 13 14 15 16 17 18 19 20)
Note that variable is shared between calls.
The first Promise halts at the sleep call, and then the second sets the state variable before the first runs ++a.
If you use my $ instead, it now works properly.
sub foo ( $init ) {
my \a = my $ = $init;
(^10).map: {
sleep 0.1;
++a
}
}
.say for await (start foo(0)), (start foo(42));
# (1 2 3 4 5 6 7 8 9 10)
# (43 44 45 46 47 48 49 50 51 52)
The thing is that sigiless “variables” aren't really variables (they don't vary), they are more akin to lexically scoped (non)constants.
constant \foo = (1..10).pick; # only pick one value and never change it
say foo;
for ^5 {
my \foo = (1..10).pick; # pick a new one each time through
say foo;
}
Basically the whole point of them is to be as close as possible to referring to the value you assign to it. (Static Single Assignment)
# these work basically the same
-> \a {…}
-> \a is raw {…}
-> $a is raw {…}
# as do these
my \a = $i;
my \a := $i;
my $a := $i;
Note that above I wrote the following:
my \a = (state $) = 3;
Normally in the declaration of a state var, the assignment only happens the first time the code gets run. Bare $ doesn't have a declaration as such, so I had to prevent that behaviour by putting the declaration in parens.
# bare $
for (5 ... 1) {
my \a = $ = $_; # set each time through the loop
say a *= 2; # 15 12 9 6 3
}
# state in parens
for (5 ... 1) {
my \a = (state $) = $_; # set each time through the loop
say a *= 2; # 15 12 9 6 3
}
# normal state declaration
for (5 ... 1) {
my \a = state $ = $_; # set it only on the first time through the loop
say a *= 2; # 15 45 135 405 1215
}
Sigilless variables are not actually variables, they are more of an alias, that is, they are not containers but bind to the values they get on the right hand side.
my \a = $(3);
say a.WHAT; # OUTPUT: «(Int)␤»
say a.VAR.WHAT; # OUTPUT: «(Int)␤»
Here, by doing $(3) you are actually putting in scalar context what is already in scalar context:
my \a = 3; say a.WHAT; say a.VAR.WHAT; # OUTPUT: «(Int)␤(Int)␤»
However, the second form in your question does something different. You're binding to an anonymous variable, which is a container:
my \a = $ = 3;
say a.WHAT; # OUTPUT: «(Int)␤»
say a.VAR.WHAT;# OUTPUT: «(Scalar)␤»
In the first case, a was an alias for 3 (or $(3), which is the same); in the second, a is an alias for $, which is a container, whose value is 3. This last case is equivalent to:
my $anon = 3; say $anon.WHAT; say $anon.VAR.WHAT; # OUTPUT: «(Int)␤(Scalar)␤»
(If you have some suggestion on how to improve the documentation, I'd be happy to follow up on it)

How to make function atomically?

I am now practicing lock,semaphore,mutual exclusive ..
I trying to implements simple code such that add 1 iteratively using mutex.
And here is my code.
[A.c]
for(int i=0; i<1000;i++){
acquire(&lock);
ADD1("count.txt"); // count.txt is shared memory
temp=Load("count.txt") // Load func get number
printf("\n %d",temp);
release(&lock);
}
also there is [B.c] all the same with A.
And I compiled A.c and B.c
gcc A.c -o A
gcc B.c -o B
and execute
./A & ./B
what I expected is ascending printing such as
1
2
3
4
..
1999
2000
But there is problem, it correctly count until 2000
but.. it was not ascending order..
4
5
6
7
1
...
234
235
...
223
...
1999
2000
Think this is weird because If I can see '2000' then It means mutex lock does work!
But why printing log is not ascending order..?
p.s/ sorry for if you can't understanding well...
Since I used google translation, my bad

CDT : IASTBinaryExpression calculating the value

I'm working on the development of the eclipse plugin based on CDT.
The plugin parses the C++ code and generates another C++ code based on the data from parsed code.
Suppose the original code is
enum SOMEENUM
{
ONE = 1 << 1 // Bit 2 2
,TWO = 1 << 2 // Bit 3 4
,THREE = 1 << 3 // Bit 4 8
,FOUR = 1 << 4 // Bit 5 16
}
CDT recognizes the 1 << 1, 1 << 2, etc as IASTBinaryExpression.
Question : Does anybody know how is it possible to evaluate the value of each binary expression by means of CDT ?
Otherwise the only option remain the calculation by manual parsing of all operands.

Hash function to iterate through a matrix

Given a NxN matrix and a (row,column) position, what is a method to select a different position in a random (or pseudo-random) order, trying to avoid collisions as much as possible?
For example: consider a 5x5 matrix and start from (1,2)
0 0 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
I'm looking for a method like
(x,y) hash (x,y);
to jump to a different position in the matrix, avoiding collisions as much as possible
(do not care how to return two different values, it doesn't matter, just think of an array).
Of course, I can simply use
row = rand()%N;
column = rand()%N;
but it's not that good to avoid collisions.
I thought I could apply twice a simple hash method for both row and column and use the results as new coordinates, but I'm not sure this is a good solution.
Any ideas?
Can you determine the order of the walk before you start iterating? If your matrices are large, this approach isn't space-efficient, but it is straightforward and collision-free. I would do something like:
Generate an array of all of the coordinates. Remove the starting position from the list.
Shuffle the list (there's sample code for a Fisher-Yates shuffle here)
Use the shuffled list for your walk order.
Edit 2 & 3: A modular approach: Given s array elements, choose a prime p of form 2+3*n, p>s. For i=1 to p, use cells (iii)%p when that value is in range 1...s-1. (For row-length r, cell #c subscripts are c%r, c/r.)
Effectively, this method uses H(i) = (iii) mod p as a hash function. The reference shows that as i ranges from 1 to p, H(i) takes on each of the values from 0 to p-1, exactly one time each.
For example, with s=25 and p=29 or 47, this uses cells in following order:
p=29: 1 8 6 9 13 24 19 4 14 17 22 18 11 7 12 3 15 10 5 16 20 23 2 21 0
p=47: 1 8 17 14 24 13 15 18 7 4 10 2 6 21 3 22 9 12 11 23 5 19 16 20 0
according to bc code like
s=25;p=29;for(i=1;i<=p;++i){t=(i^3)%p; if(t<s){print " ",t}}
The text above shows the suggestion I made in Edit 2 of my answer. The text below shows my first answer.
Edit 0: (This is the suggestion to which Seamus's comment applied): A simple method to go through a vector in a "random appearing" way is to repeatedly add d (d>1) to an index. This will access all elements if d and s are coprime (where s=vector length). Note, my example below is in terms of a vector; you could do the same thing independently on the other axis of your matrix, with a different delta for it, except a problem mentioned below would occur. Note, "coprime" means that gcd(d,s)=1. If s is variable, you'd need gcd() code.
Example: Say s is 10. gcd(s,x) is 1 for x in {1,3,7,9} and is not 1 for x in {2,4,5,6,8,10}. Suppose we choose d=7, and start with i=0. i will take on values 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, which modulo 10 is 0, 7, 4, 1, 8, 5, 2, 9, 6, 3, 0.
Edit 1 & 3: Unfortunately this will have a problem in the two-axis case; for example, if you use d=7 for x axis, and e=3 for y-axis, while the first 21 hits will be distinct, it will then continue repeating the same 21 hits. To address this, treat the whole matrix as a vector, use d with gcd(d,s)=1, and convert cell numbers to subscripts as above.
If you just want to iterate through the matrix, what is wrong with row++; if (row == N) {row = 0; column++}?
If you iterate through the row and the column independently, and each cycles back to the beginning after N steps, then the (row, column) pair will interate through only N of the N^2 cells of the matrix.
If you want to iterate through all of the cells of the matrix in pseudo-random order, you could look at questions here on random permutations.
This is a companion answer to address a question about my previous answer: How to find an appropriate prime p >= s (where s = the number of matrix elements) to use in the hash function H(i) = (i*i*i) mod p.
We need to find a prime of form 3n+2, where n is any odd integer such that 3*n+2 >= s. Note that n odd gives 3n+2 = 3(2k+1)+2 = 6k+5 where k need not be odd. In the example code below, p = 5+6*(s/6); initializes p to be a number of form 6k+5, and p += 6; maintains p in this form.
The code below shows that half-a-dozen lines of code are enough for the calculation. Timings are shown after the code, which is reasonably fast: 12 us at s=half a million, 200 us at s=half a billion, where us denotes microseconds.
// timing how long to find primes of form 2+3*n by division
// jiw 20 Sep 2011
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
double ttime(double base) {
struct timeval tod;
gettimeofday(&tod, NULL);
return tod.tv_sec + tod.tv_usec/1e6 - base;
}
int main(int argc, char *argv[]) {
int d, s, p, par=0;
double t0=ttime(0);
++par; s=5000; if (argc > par) s = atoi(argv[par]);
p = 5+6*(s/6);
while (1) {
for (d=3; d*d<p; d+=2)
if (p%d==0) break;
if (d*d >= p) break;
p += 6;
}
printf ("p = %d after %.6f seconds\n", p, ttime(t0));
return 0;
}
Timing results on 2.5GHz Athlon 5200+:
qili ~/px > for i in 0 00 000 0000 00000 000000; do ./divide-timing 500$i; done
p = 5003 after 0.000008 seconds
p = 50021 after 0.000010 seconds
p = 500009 after 0.000012 seconds
p = 5000081 after 0.000031 seconds
p = 50000021 after 0.000072 seconds
p = 500000003 after 0.000200 seconds
qili ~/px > factor 5003 50021 500009 5000081 50000021 500000003
5003: 5003
50021: 50021
500009: 500009
5000081: 5000081
50000021: 50000021
500000003: 500000003
Update 1 Of course, timing is not determinate (ie, can vary substantially depending on the value of s, other processes on machine, etc); for example:
qili ~/px > time for i in 000 004 010 058 070 094 100 118 184; do ./divide-timing 500000$i; done
p = 500000003 after 0.000201 seconds
p = 500000009 after 0.000201 seconds
p = 500000057 after 0.000235 seconds
p = 500000069 after 0.000394 seconds
p = 500000093 after 0.000200 seconds
p = 500000099 after 0.000201 seconds
p = 500000117 after 0.000201 seconds
p = 500000183 after 0.000211 seconds
p = 500000201 after 0.000223 seconds
real 0m0.011s
user 0m0.002s
sys 0m0.004s
Consider using a double hash function to get a better distribution inside the matrix,
but given that you cannot avoid colisions, what I suggest is to use an array of sentinels
and mark the positions you visit, this way you are sure you get to visit a cell once.