Simple yacc grammars give an error - yacc

I have a question for yacc compiler. I do not compile simple yacc grammar. Here is the code section :
/*anbn_0.y */
%token A B
%%
start: anbn '\n' {printf(" is in anbn_0\n");
return 0;}
anbn: empty
| A anbn B
;
empty: ;
%%
#include "lex.yy.c"
yyerror(s)
char *s;
{ printf("%s, it is not in anbn_0\n", s);
I use mac os x and, i try yo command;
$ yacc anbn_0.y and then
$ gcc -o anbn_0 y.tab.c -ll and give me error. Here is the error ;
warning: implicit declaration of function 'yylex' is invalid in C99 [-Wimplicit-function-declaration]
yychar = YYLEX;
Why do I get an error ?

Its a warning, not an error, so you should be fine if you ignore it. But if you really want to get rid of the warning, you could add
%{
int yylex();
%}
to the top of your .y file

Here is an answer to a more sophisticated version of this problem which isn't easily solved just by adding a declaration.
GNU Bison supports the generation of re-entrant parsers which work together with Flex (using Flex's %option bison-bridge re-entrant). Berkeley Yacc provides a compatible implementation.
Here is a guide on how to solve this undeclared yylex for both parser generators.
With a re-entrant, "Bison bridged" lexer, the declaration of yylex turns into this:
int yylex(YYSTYPE *yylval, void *scanner);
If you place this prototype in the %{ ... %} initial header section of your Yacc parser, and generate the parser with either Bison or Berkeley Yacc, the compiler will complain that YYSTYPE is not declared.
You cannot simply create a forward declaration for YYSTYPE, because in Berkeley Yacc, it does not have a union tag. In Bison, it is typedef union YYSTYPE { ... } YYSTYPE, but in Berkeley Yacc it is typedef { ... } YYSTYPE: no tag.
But, in Berkeley Yacc, if you put a declaration in the third section of the parser, it is in scope of the yylex call! So the following works for Berkeley yacc:
%{
/* includes, C defs */
%}
/* Yacc defs */
%%
/* Yacc grammar */
%%
int yylex(YYSTYPE *, void *);
/* code */
If this is generated with Bison, the problem persists: there is no prototype in scope of the yylex call.
This little fix makes it work for GNU Bison:
%{
/* includes, C defs */
#if YYBISON
union YYSTYPE;
int yylex(union YYSTYPE *, void *);
#endif
%}
/* Yacc defs */
%%
/* Yacc grammar */
%%
int yylex(YYSTYPE *, void *);
/* code */
There you go.

Related

Redefinition of z_stream_s, gz_header_s, gzfile_s in zlib.h for objective c after upgrade to xcode13

After upgrade to xcode13.4, redefinition of struct z_stream_s, gz_header_s, gzfile_s in zlib.h.
I added to guard to avoid the redefinition in the starting and ending
#ifndef ZLIB_H
#define ZLIB_H
------ coding
#endif
Code where the error occurring
typedef struct z_stream_s {
z_const Bytef *next_in; /* next input byte */
uInt avail_in; /* number of bytes available at next_in */
uLong total_in; /* total number of input bytes read so far */
Bytef *next_out; /* next output byte will go here */
uInt avail_out; /* remaining free space at next_out */
uLong total_out; /* total number of bytes output so far */
z_const char *msg; /* last error message, NULL if no error */
struct internal_state FAR *state; /* not visible by applications */
alloc_func zalloc; /* used to allocate the internal state */
free_func zfree; /* used to free the internal state */
voidpf opaque; /* private data object passed to zalloc and zfree */
int data_type; /* best guess about the data type: binary or text
for deflate, or the decoding state for inflate */
uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */
uLong reserved; /* reserved for future use */
} z_stream;
typedef struct z_stream_s FAR *z_streamp;
typedef struct gz_header_s {
int text; /* true if compressed data believed to be text */
uLong time; /* modification time */
int xflags; /* extra flags (not used when writing a gzip file) */
int os; /* operating system */
Bytef *extra; /* pointer to extra field or Z_NULL if none */
uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
uInt extra_max; /* space at extra (only when reading header) */
Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
uInt name_max; /* space at name (only when reading header) */
Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
uInt comm_max; /* space at comment (only when reading header) */
int hcrc; /* true if there was or will be a header crc */
int done; /* true when done reading gzip header (not used
when writing a gzip file) */
} gz_header;
struct gzFile_s {
unsigned have;
unsigned char *next;
z_off64_t pos;
};
I replaced the latest zlib.h also but the same redefinition error occurring again.
These files are used to generate the qrcode
redefintion issue occurring in all these files
When i click the error occur it goes to the line where struct z_stream_s is defined
typedef struct z_stream_s {
In that error shows that it has been already defined in the file unzip.c
in the unzip.c when i look into that zlib.h has been include in the both unzip.h and unzip.c
in unzip.h
#ifndef _unz_H
#define _unz_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
in unzip.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"
#include "unzip.h"
#ifdef STDC
# include <stddef.h>
# include <string.h>
# include <stdlib.h>
#endif
#ifdef NO_ERRNO_H
extern int errno;
#else
# include <errno.h>
#endif
These files are used to generate the QRCODE
and the redefinition error continues on file by file zip.c, zip.h, pngpriv.h, pngstruct.h like that it goes on
Note:The same project is working fine in Xcode 12.4, but in latest Xcode 13 Its shows the redefinition error
Please help me to resolve this issue.
Thanks in advance.

failed to parse number by yacc and lex

i have finished my lex file and start to learn about yacc
but i have some question about part of my code of lex:
%{
#include "y.tab.h"
int num_lines = 1;
int comment_mode=0;
int stack =0;
%}
digit ([0-9])
integer ({digit}+)
float_num ({digit}+\.{digit}+)
%%
{integer} { //deal with integer
printf("#%d: NUM:",num_lines); ECHO;printf("\n");
yylval.Integer = atoi(yytext);
return INT;
}
{float_num} {// deal with float
printf("#%d: NUM:",num_lines);ECHO;printf("\n");
yylval.Float = atof(yytext);
return FLOAT;
}
\n { ++num_lines; }
. if(strcmp(yytext," "))ECHO;
%%
int yywrap() {
return 1;
}
every time i got an integer or a float i return the token and save it into yylval
and here is my code in parser.y:
%{
#include <stdio.h>
#define YYDEBUG 1
void yyerror (char const *s) {
fprintf (stderr, "%s\n", s);
}
%}
%union{
int Integer;
float Float;
}
%token <int>INT;
%token <float>FLOAT;
%%
statement :
INT {printf("int yacc\n");}
| FLOAT {printf("float yacc\n");}
|
;
%%
int main(int argc, char** argv)
{
yyparse();
return 0;
}
which compiled by
byacc –d parser.y
lex lex.l
gcc lex.yy.c y.tab.c –ll
since i just want to try something easy to get started, i want to see if i can parse
only int and float number first, i print them in both .l and .y file after i input an
integer or a float.int the begining i input fisrt random number, for example 123
, then my program print :
1: NUM: 123
in yylex() and
"int yacc\n"
in parser.y
but if i input the second else number, it shows syntax error and the program shutdown
i dont know where is the problem.
is there any solution?
Your grammar only accepts a single token, either an INT or a FLOAT. So it will only accept a single number, which is why it produces a syntax error when it reads the second number; it is expecting an end-of-file.
The solution is to change the grammar so that it accepts any number of "statements":
program: /* EMPTY */
| program statement
;
Two notes:
1) You don't need an (expensive) strcmp in your lexer. Just do this:
" " /* Do nothing */;
. { return yytext[0]; }
It's better to return the unknown character to the parser, which will produce a syntax error if the character doesn't correspond to any token type (as in your simple grammar) than to just echo the character to stdout, which will prove confusing. Some people would prefer to produce an error message in the lexer for invalid input, but while you are developing a grammar I think it is easier to just pass through the characters, because that lets you add operators to your parser without regenerating the lexer.
2) When you specify %types in bison, you use the tagname from the union, not the C type. Some (but not all) versions of bison let you get away with using the C type if it is a simple type, but you can't count on it; it's not posix standard and it may well break if you use an older or newer version of bison. (For example, it won't work with bison 3.0.) So you should write, for example:
%union{
int Integer;
float Float;
}
%token <Integer>INT;
%token <Float>FLOAT;

API for handling wait queues are not working

I have to make tasks as processes in Linux but I don't want the process to execute until all the processes are created. So I thought of moving the processes to wait queue soon after creation and wait until all processes are created.
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <sched.h>
#include <linux/kernel.h>
#include <time.h>
#include <sys/resource.h>
#include <stddef.h>
#include <linux/sched.h>
#include <linux/wait.h> /* for wait_event_interruptible() & wake_up_interruptible() */
int done = 0;
static DECLARE_WAIT_QUEUE_HEAD(queue);
int main()
{
int pid1, pid2;
if ((pid1 = fork()) < 0) //create a child process
exit(1);
if ((pid2 = fork()) < 0) //create a child process
exit(1);
if (pid1 == 0) //child process
{
wait_event_interruptible(queue, done == 2);
printf("child 1\n");
}
else //parent process
{
done = done+1;
wake_up_interruptible(&queue);
}
if (pid2 == 0) //child process
{
wait_event_interruptible(queue, done == 2);
printf("child 2\n");
}
else //parent process
{
done = done+1;
wake_up_interruptible(&queue);
}
return 0;
}
But when I tried this sample code it shows these errors.
$ gcc -Wall try.c
try.c:18:8: warning: type defaults to ‘int’ in declaration of ‘DECLARE_WAIT_QUEUE_HEAD’ [-Wimplicit-int]
try.c:18:1: warning: parameter names (without types) in function declaration [enabled by default]
try.c: In function ‘main’:
try.c:33:6: warning: implicit declaration of function ‘wait_event_interruptible’ [-Wimplicit-function-declaration]
try.c:33:31: error: ‘queue’ undeclared (first use in this function)
try.c:33:31: note: each undeclared identifier is reported only once for each function it appears in
try.c:39:2: warning: implicit declaration of function ‘wake_up_interruptible’ [-Wimplicit-function-declaration]
try.c: At top level:
try.c:18:8: warning: ‘DECLARE_WAIT_QUEUE_HEAD’ declared ‘static’ but never defined [-Wunused-function]
When I checked $ man wait_event_interruptible, it says "No manual entry for wait_event_interruptible". So the API is missing in the library. How can I add it to the library? Thanks in advance.
wait_event_interruptible(), wake_up_interruptible() are some of the Kernel's API to create and use wait queues. You cannot use those from the user-land!
If I understand your purpose correctly, what you need to do is to create N processes barrier. If you know the number of the processes (N), you can easily use semaphores: initialize the semaphore with zero, all processes call down() and the last process calls up() N times. You can also use message queues.
You can also use the Linux API for barriers: pthread_barrier_wait and pthread_barrier_init, but I have not used this before.

How would I declare a grammar rule for a number of tags in any order?

I am trying to write a compiler for a formating language.This language has a start and an end property and a set of document and text properties.
The first is just info for the document itself where as the second is the actual document (titles, paragraphs, lists... the usual). The first set must always follow the start property and must contain all properties BUT in any order the user might like.
Assuming that my tokens for the properites are PROP1, PROP2, PROP3 and PROP4 I can use recursion and an OR for all the properties so that the user can define any document property he wants.
doc_properties
: /* empty */
: doc_properties property
;
property
: PROP1
: PROP2
: PROP3
: PROP4
;
BUT how do I make him to define them all and only once. One way that I thought (the easy and crude way I would like to avoid) is because I only have 4 document properties I can just make an or of all possible combinations. I am pretty sure there is another way. Any help?
My grammar so far is pretty simple and small
%{ /* C Stuff */ %}
/* union and error stuff and tokens */
%%
source
: /* empty */
| entry_point doc_properties txt_properties exit_point
;
entry_point
: SLASH BLOCK_S LBRACE DOC RBRACE
;
doc_properties
: /* This is where my question goes */
;
txt_properties
: /* empty */
;
exit_point
: SLASH BLOCK_E LBRACE DOC RBRACE
;
%%
int main (int argc, char* argv[])
{
/* various checks for the arguments and the input output files */
yyin = fopen(argv[1], "r");
yyout = fopen(fn, "w");
//do{
yyparse();
//}while(!feof(yyin));
fclose(yyin);
fclose(yyout);
return 0;
}
void yyerror(const char* str) {
fprintf(stderr,"syntax error[%d]: %s\n",yylineno, str);
}
Also on an unrelated note does using yyparse() inside a do-while loop or just once by itself has any difference? Because I see it both ways and while the do-while loop makes more sense to me (because it requests a token parses and then again) I am not sure if the function repeats itself or something...
There is a number of syntax rules that are best enforced by semantic checks rather than by the grammar itself. For instance, in C like languages, the break construct can only appear inside loops (and switch), yet it is far simpler to accept it like any regular statement, and later, in the semantic analysis pass, reject invalid uses to break.
You could use a similar pattern: accept any combination of PROP, and later reject those that do not respect your constraints. Of course, you can also do this while parsing, using YYERROR to raise an error when appropriate.
Wrt to your second question, yyparse is to be called only once, but then of course it is in charge of calling the scanner (yylex) repeatedly. Note that Bison offers "push-parsers", where you are in charge of calling yylex repeatedly, and pass its results to yyparse (repeatedly too). See http://www.gnu.org/software/bison/manual/bison.html#Push-Decl for more details.

Mingw32 std::isnan with -ffast-math

I am compiling the following code with the -ffast-math option:
#include <limits>
#include <cmath>
#include <iostream>
int main() {
std::cout << std::isnan(std::numeric_limits<double>::quiet_NaN() ) << std::endl;
}
I am getting 0 as output. How can my code tell whether a floating point number is NaN when it is compiled with -ffast-math?
Note: On linux, std::isnan works even with -ffast-math.
Since -ffast-math instructs GCC not to handle NaNs, it is expected that isnan() has an undefined behaviour. Returning 0 is therefore valid.
You can use the following fast replacement for isnan():
#if defined __FAST_MATH__
# undef isnan
#endif
#if !defined isnan
# define isnan isnan
# include <stdint.h>
static inline int isnan(float f)
{
union { float f; uint32_t x; } u = { f };
return (u.x << 1) > 0xff000000u;
}
#endif
On linux, the gcc flag -ffast-math breaks isnan(), isinf() and isfinite() - there may be other related functions that are also broken that I have not tested.
The trick of wrapping the function/macro in parentheses also did not work (ie. (isnan)(x))
Removing -ffast-math works ;-)