Monday, July 25, 2005

Signals-I

Signals are asynchronous notifications and there is no code that calls the signal handler directly.
When a signal is received the signal handler code gets executed.
"kill -l" lists all the available signals on a system.
Here is some sample code that sends a SIGSTOP to itself.

main()
{
pid_t my_pid = getpid();
kill(my_pid, SIGSTOP);

}

Catching Signals - Signal Handlers

signal(SIGINT, print_hello);

With signal fucntion we can define a signal handler for a given signal.In the example above
We have defined print_hello to be the handler for SIGINT(Ctrl-C).

Masking signals:
If we re-enter intoa signal while a signal is being processed ,things can get nasty.
sigprocmask allows us to mask signals in a global context.

This function lets us either block/unblock new signals or completely set a new mask.
To mask any signals while we are in a signal handler,following piece of code could be used.

sigset_t mask_set; /* used to set a signal masking set. */
sigset_t old_set; /* used to store the old mask set. */

/* re-set the signal handler again to catch_int, for next time */
signal(SIGINT, catch_int);
/* mask any further signals while we're inside the handler. */
sigfillset(&mask_set);
sigprocmask(SIG_SETMASK, &mask_set, &old_set);

There is no need to re-set the signal mask later on as the operating system will automatically reset the mask during the return from the signal handler.

Tuesday, July 19, 2005

setjmp

Setjmp saves the "state of the program" so that longjmp can later restore it.

What setjmp basically saves the state of the registers and longjmp restores it later on.
In other words longjmp restores the state of the program at the time setjmp was called.

#include 

main()
{
jmp_buf env;
int i;

i = setjmp(env);
printf("i = %d\n", i);

if (i != 0) exit(0);

longjmp(env, 2);
printf("This line is never printed?\n");

}
$./a.out
i = 0
i = 2



When we call setjmp first it saves the state and returns 0 but when we later call longjmp it returns from the same place where setjmp was called but with a return value 2.Longjmp returns from the most recent setjmp. is you add one more setjmp after the first printf,we get following output.


$./a.out
i = 0

Friday, July 15, 2005

Precedence and associativity

For operators this two terms are very important ..Let me just go into the details of how these are interpretted

Precedence
3+4*5=35 or 23.

Associativity
45 - 45 -5 = -5 or 5

We can specify the precedence and associativity using %left,%right or %nonassoc followed by list of tokens.



All of the tokens on the same line have the same precedence level and associativity; the lines occur in order of increasing precedence. The following lines describe the precedence and associativity of the four arithmetic operators:

%left  '+'  '-'
%left '*' '/'


So as you can see ,in the previous example we can make the grammar by specifying the following in the definitions section.

%left '-'

Now when i compileandrun , i get ....

$./compileandrun.sh rpcalc.y
45 - 45 - 5
-5

shift - reduce

Interesting stuff .
Consider the following rule..

exp: NUM { $$ = $1; }
| exp '-' exp { $$ = $1 - $3; }


Now when i compileandrun it..here is what i observe..

$./compileandrun.sh rpcalc.y
rpcalc.y: conflicts: 1 shift/reduce
45 - 45 - 5
5


So as you can see the answer is 5 so the parser computed this as..

45 - ( 45 -5 ) instead of (45 -45 ) - 5.
The earlier operation is right associative and called shift and the later one is left associative
and is called reduce .So the parser prefers shift to reduce.

Rules

When creating rules we have to make sure literal strings are characters..

For example..

expr : expr expr '+-'

doesnt work ,but


expr : expr expr '+' '-'

works

yylval

This global yacc variable has the value of the token.

yylval = value; /* Put value onto Bison stack. */
return INT; /* Return the type of the token. */

%union {
int intval;
double val;
symrec *tptr;
}

yylval.intval = value; /* Put value onto Bison stack. */
return INT; /* Return the type of the token. */

Thursday, July 14, 2005

Yacc actions

Yacc actions are specified in curly braces and can be given anywhere in the definition section but it is a good practice to specify them after the last symbol.

 A       :  '('  B  ')'
{
othello( 1, "abc" );
}
;


Value of symbols:
All symbols are aa grammar rule :-? with a value associated with it.For terminal symbols the value can be asigned by the lexical analyzer.Non terminals symbols can have values associated with them using parser actions,they can be text,numbers or any kind of data structure.
The dollar sign is used to access value of symbol. $$ is the value of symbol associated with the left of the rule.$1, $2, $3 and $n refer to 1st,2nd ,3rd and nth symbol to the right of the rule.


expr : '(' expr ')'
{
$$ = $2 ;
}

Some yacc basics

Yacc rules are of the format

lname : definition ;

If there are actions associated with the rule,they must come in between colon and semicolon.
lname is a non-terminal that is it has to be "decompposed" and definition could consist of
terminals and non-terminals.A word about terminals and non-terminals:tokens that are recognized by
lex and passed to parser(yacc generated) are called "terminal symbols" as they cant be "decomposed" futher.Any symbol "terminal" or "non-terminal" is called a name.A symbol cant start with a digit but can contain letters,underscores ,dots and digits.

If there are several grammar rules with the same left hand side they can be seperated by "|".


A : B C D ;
A : E F ;
A : G ;


A : B C D
| E F
| G
;

Lex subroutines

This is to let you write your own functions which you want to be executed as actions in the rules section.

article a|an|the
%%
{article} do_article(yytext);
%%
do_article(char *s)
{
printf("gotta an article %s",s);
}

Lex definitions

The important types of definitions are external definitions,#includes and abbreviations.

1.External definitions:Same as in C,they define variables that are globally defined elsewhere(like in another file).

2.#includes ,these are useful to include header files ,most importantly you can call yacc routines by including y.tab.h.

3.Abbreviations:You can make a shorform of patterns .

%{
#include "y.tab.h"
extern int tokval;
int lineno;
%}
dig [0-9]

As you can see variable declarations and #includes should be occur within '%{' and '}%',whereas abbreviation are declared outside that block.

ECHO

This macro has the is same as printf("%s",yytext);
Its a useful shorthand.

yytext and yyleng

In lex if you want to find out of what text the scanner matches for a given patten the variable yytext returns the string matched and yylength conatins the length of the match.


[0-9]+ { printf("Gotta a number:%s of %d digits\n",yytext,yyleng); }
$./compileandrun.sh
123213
Gotta a number:123213 of 6 digits


Lex actions

An action is a block of C code that gets executed whenever any pattern in the lex specification is matched.As i dont really understand any of this , a good question would be to ask
"What are the typical actions?".
Here is the list of them.

1)Transformation of the matched string
2)Returning a token to a parser
3)Compiling statistics on the input.

Lex rules section

This section is mandatory,this section is a mapping of patterns to be searched/scanned for in the input and an action associated with it.

If no action is given then no action will be taken.

A string with no operators matches a literal string.
dog

if you want to match spaces and tabs then enclose the string in double quotes..

"Big chasm"



An expression, followed by the ``*'' operator, matches 0 or more occurrences of that expression.
m*


An expression, followed by the ``+'' operator, matches 0 or more occurrences of that expression.
m+


An expression, followed by the ``?'' operator, matches 0 or 1 occurrence of that expression.
m?


The period character, (.), matches any single character.
.


Alternation in regular expressions is supported using the vertical bar, (|)
Me|Myself|Irene


Expressions may be grouped using parentheses, '(' and ')' .
(Me|Myself|Irene)+


The circumflex, (^), followed by a pattern, signifies that the pattern must match at the beginning of a line
^(Me|Myself|Irene)+

The dollar sign, ($) is appended to a pattern to indicate that it must match at the end of a line.
^(Me|Myself|Irene)+$


To indicate that a regular expression should be matched a specific number of times, follow that expression with a number enclosed in curly braces, '{' and '}'
(Me|Myself|Irene){3}

To specify a range,you can give two numbers sperated by comma in curly braces.
(Me|Myself|Irene){1,3}


A sequence of characters inside square brackets, '[' and ']', matches any one character in the sequence.
[UFOR]


If the circumflex, (^), is the first character inside the square brackets, then the pattern matches any character that does not appear inside the brackets.
[^abcd]



Ranges within a standard alphabetic or numeric order are indicated with a hyphen, (-).
[0-9]

Regular expressions can be concatenated.
(Me|Myself|Irene){1,3}[0-9]


To treat an otherwise special character as a literal character, rather than as a special character, enclose the character in quotation marks or precede it with a backslash (\).

Press\* or Press"*"


lex understands the standard C escape sequences, such as \n for the end-of-line.

Wednesday, July 13, 2005

Basic lex - lesson 1

$cat  test.y
%{
int count;
%}
%%
fly { count++; noise(); }
dog { printf("Woof!\n"); }
man { printf("Hello world!\n"); }

%%
noise()
{
printf("%d flies went Bzzzz!\n",count);
}


So as we can see in the first section:(This section starts with '%{' and ends with '}%' ) , there is an integer called count declared.
In the second section:(This section starts with '%%' and ends with '%%' ),we have a token and an associated action.So what we are telling is when you read fly then increase the count and call the function noise and so on..
The last section doesnt have a explicit start but in effect starts where the second section ends..and in this we have our function declaration called noise.

Hmpfff...

now to compile and run it..

$cat compileandrun.sh
flex test.y
cc lex.yy.c -l fl
./a.out
$./compileandrun.sh
fly
1 flies went Bzzzz!

man
Hello world!

dog
Woof!

fly
2 flies went Bzzzz!


Lex and yuck!

I started looking into bash source code after loading bash in gdb..
It has something called yyparse so i thought i might be a good idea to find out what the hell it is.

So i'll be blogging my learning or learning through blogging .
The url is http://osr5doc.ca.caldera.com:457/tools/CONTENTS.html

Good stuff ,i hope :)