It is highly recommended to go through the following links first

In this grammar file we do our semantic analysis, by walking and evaluating the nodes, of the AST tree, generated in our grammar file.


Figure 1. A Snapshot of the tree of a statement.

tree grammar StatementWalker1;

options {

language = Java;

tokenVocab = XL1;

ASTLabelType = CommonTree;

}

@header{

package com.fawad.policywritingtool;

}

policy

: (mode ‘(””‘ appname ‘”‘ ‘as’ app ‘,’ ‘”‘ permname'”‘ ‘as’ perm ‘)’ ‘:’

statement+ ‘->’ policyeffect ‘(‘app ‘,’ perm ‘)’ ‘;’ )+

;

mode

: RES

;

appname

: IDENT(‘.’ IDENT | ‘_’ IDENT)+

;

app

: IDENT+

;

method

: IDENT+'()’

;

permname

: IDENT(‘.’ IDENT | ‘_’ IDENT)+

;

perm

: IDENT+

;


An integer ‘result’ is returned when the statement is evaluated

statement returns [int result] :    e=expression  { result = e; }

;


Following are the operators and their respective implementation in the walker

expression returns [int result]

: ^(‘AND’ op1=expression op2=expression ) { if(op1==1 && op2 == 1) result =1; else result =0;}

|^(‘OR’ op1=expression op2=expression ) { if(op1==1 || op2 == 1) result =1; else result =0;}

|^(‘>’ op1=expression op2=expression) { result= op1 > op2?1:0; }

| ^(‘<‘ op1=expression op2=expression) { result= op1 < op2?1:0;}

| ^(‘>=’ op1=expression op2=expression) { result= op1 >= op2?1:0;}

| ^(‘<=’ op1=expression op2=expression) { result= op1 <= op2?1:0;}

| ^(‘=’ op1=expression op2=expression) { result= op1 != op2?1:0;}

| ^(‘!=’ op1=expression op2=expression) { result= op1 != op2?1:0;}

| ^(‘+’ op1=expression op2=expression) { result = op1 + op2; }

| ^(‘-‘ op1=expression op2=expression) { result = op1 – op2; }

| ^(‘*’ op1=expression op2=expression) { result = op1 * op2; }

| ^(‘/’ op1=expression op2=expression) { result = op1 / op2; }

| ^(‘%’ op1=expression op2=expression) { result = op1 \% op2; }

| ^(NEGATION e=expression) { result = -e;}

| TRUE{ result = 1;}

| FALSE{ result = 0;}

| INTEGER { result= Integer.parseInt($INTEGER.text); }

;

Policy effect returns an integer ‘res’ with the value ‘1’ for allow and  ‘0’ for deny

policyeffect returns [int res ]

: ALLOW {res= 1 ;}

| DENY {res= 0 ;}

;

Advertisements