You are on page 1of 20

COMPILER DESIGN

--- group2
K.MohananjaliAP19110010182
J.ManognaAP19110010153
N.RajyalakshmiAP19110010301
V.AnirudhAP19110010175
T.DharmeshAP19110010183

Report

Selected language: PHP

DATATYPES IN PHP:
PHP supports the following data types:

String:

A string is a sequence of characters. A string can be any text inside quotes.


You can use single or double quotes:
Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
Output: Hello world!
Hello world!

Integer:
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base
8), or binary (base 2) notation

Example:

<?php
$x = 5985;
var_dump($x);
?>
Output:
int(5985)

Float:
A float (floating-point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The PHP var_dump() function returns the data type and value:

Example:
<?php
$x = 10.365;
var_dump($x);
?>
output:float(10.365)

Boolean:
A Boolean represents two possible states: TRUE or FALSE.

Example:
$x = true;
$y = false;

Array:

An array stores multiple values in one single variable. In the following example
$cars is an array.

Example:

<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

Object:

Classes and objects are the two main aspects of object-oriented programming. A
class is a template for objects, and an object is an instance of a class.

Example:

<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

NULL:

Null is a special data type that can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Example:

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?
Resource:

The special resource type is not an actual data type. It is the storing of a reference
to functions and resources external to PHP. A common example of using the
resource data type is a database call.

Variable Declaration in PHP:


Variable is nothing, it is just the name of the memory location. A Variable is simply
a container i.e used to store both numeric and non-numeric information. Variables
are case sensitive.No need to declare variable type before using in PHP.

Rules for Variable declaration


● Variables in PHP start with a dollar($) sign, followed by the name of the
variable.
● The variable name must begin with a letter or the underscore character.
● A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
● A variable name should not contain space

Decision-Making Statements:
PHP conditional statements
allow you to make a decision, based upon the result of a condition. These
statements are called Decision Making Statements.
Conditional Statements in PHP are:
● If statements
● If else statements
● If elseif else statement
● Switch statement

if Statement: This statement allows us to set a condition. On being TRUE, the


following block of code enclosed within the if clause will be executed.

SYNTAX:

if (condition){
// if TRUE then execute this code

}
Example:

<?php

$x = 12;

if ($x > 0) {

echo "The number is positive";

?>

Output:

The number is positive

If…elseif…else Statement: This allows us to use multiple if…else statements.


We use this when there are multiple conditions of TRUE cases.

SYNTAX:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:

<?php

$x = "August";

if ($x == "January") {

echo "Happy Republic Day";

elseif ($x == "August") {

echo "Happy Independence Day!!!";

Else{

echo "Nothing to show";

}
?>

OUTPUT:

Happy Independence Day!!!

SWITCH STATEMENT: The “switch” performs in various cases i.e., it has various
cases to which it matches the condition and appropriately executes a particular case
block. It first evaluates an expression and then compares it with the values of each case.
If a case matches then the same case is executed. To use the switch, we need to get
familiar with two different keywords namely, break and default.

● The break statement is used to stop the automatic control flow into the next cases
and exit from the switch case.
● The default statement contains the code that would execute if none of the cases
match.

SYNTAX:

switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;

EXAMPLE:
<?php
$n = "February";

switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>

OUTPUT:

Its February
if…else Statement: We understood that if a condition will hold i.e., TRUE, then the
block of code within if will be executed. But what if the condition is not TRUE and we
want to perform an action? This is where else comes into play. If a condition is TRUE
then if block gets executed, otherwise else block gets executed.
SYNTAX:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
EXAMPLE:
else{<?php
$x = -12;

if ($x > 0) {
echo "The number is positive";
}
?>
echo "The number is negative";
}
OUTPUT:
The number is negative

AtLeast two Iterative statements in PHP:


Iteration is the process where a set of instructions or statements is executed
repeatedly for a specified number of times or until a condition is met. Such a
statement is known as an iterative statement.
While Loop:
The statement(s) will be executed as long as the condition evaluates to
true. statement(s) may be a single statement or a block of statements.
The value of the variable involved in the condition should be changing during
every pass of the while loop. If it is not changed, then the while loop enters into an
infinite loop.
Syntax:
while(condition)
{
statement(s);
}
Example:
<?php
$i=0;
while($i<=2)
{ //output value 0 from 2
echo "The Number is ".$i."<br>";
$i++;
}
?>
Output:
The Number is 0
The Number is 1
The Number is 2

For Loop:
The for loop is used when you know in advance how many times the script
should run.
for statement has the following properties:
● The two semicolons are required and create three sections: an initialization
statement, a boolean expression, and an update statement.
● The initialization step occurs once at the beginning of the loop.
● The boolean_expression must evaluate to true or false.
● The initialization and update_statement sections can contain multiple
statements, separated by commas.
● Any variables declared in the initialization step are local variables in for
loop and go out of scope when the loop finishes.
Syntax:
for (initialization; boolean_expression; update_statement)
{
//body of the loop;
}
Example:
<?php
for($i=0;$i<=2;$i++)
{
echo "The Number is ".$i."<br/>";
}
?>
Output:
The Number is 0
The Number is 1
The Number is 2

CFG(context free grammar):


CFG stands for context-free grammar. It is a formal grammar that is used to
generate all possible patterns of strings in a given formal language. Context-free
grammar G can be defined by four tuples:
G = (V, T, P, S)
G is the grammar, which consists of a set of production rules. It is used to generate
the string of a language.
T is the final set of a terminal symbol. It is denoted by lower case letters.
V is the final set of a non-terminal symbol. It is denoted by capital letters.
P is a set of production rules, which is used for replacing non-terminals
symbols(on the left side of the production) in a string with other terminal or
nonterminal symbols(on the right side of the production).
S is the start symbol which is used to derive the string. We can derive the string by
repeatedly replacing a non-terminal by the right-hand side of the production until
all non-terminal has been replaced by terminal symbols.

CFG for operator:


<s>→<id><operator><id>
<id>→<var><dig>
<operator>→= = | > | <
<dig>→0|1|2|3|.......|9
<var>→a|b|c

Parse Tree:
CFG for Variable declaration:

<var-decl>→ <type><list>
<type>→ int|float
<list>→ id|id,<list>
id={a,b,...A,B,...}

Parse tree:

Semantic Actions: Variable declaration tells the compiler two things: The name
of the variable and the type of data the variable will hold
CFG for Arithmetic expression:

<exp>→ <term><operator><term>
<term>→ <factor><operator><factor>
<operator>→ +|-|*|=
<factor>→ a-z|A-Z
Parse tree:
CFG for IF-ELSE:

<statement>→ <if><exp><statement><else><statement>|<statement><statement>
<exp>→ < < >, < > >, <= = >,...
Parse tree:

Semantic analysis:
The if-else statement is used to carry out two operations in response to a single
condition. The if-else statement is an extension to the if statement that allows us to
perform two different operations, one for the correctness of the condition and the
other for its incorrectness. It is important to note that the if and else blocks cannot
be executed concurrently. It is always preferable to use an if-else statement because
it always invokes an otherwise case with every if condition..

For loop:
Structure of For Loop:
for(initialization; condition; increment/decrement)
for($n=1;$n<=10;$n++)
Keywords : for
Terminals : (, ), =, <, >, ++, --, variable i.e. i
CFG:
S → XY
X → for
Y → ( A; B; C ) (Rest of loop will be Y)
A → V = N (Initialization)” (Increment / Decrement)
N → 0-9N / [0-9]
V→ _W/ a-zW / A-ZW
W → _W/ a-zW/ 0-9W/ lambda
Parse tree:
Semantic actions:
The PHP for loop is similar to the java/C/C++ for a loop.
initialization - Initialize the loop counter value. The initial value of the for loop is
done only once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise, the execution
of the loop ends.
Increment/decrement - It increments or decrements the value of the variable.
flow chart of for loop:
Target language: Python
Syntax Of Target Language:
Python statement ends with the token NEWLINE character (carriage return). It means
each line in a Python script is a statement. The following Python script contains three
statements in three separate lines.

EXAMPLE:

print('id: ', 1)

print('First Name: ', 'Steve')

print('Last Name: ', 'Jobs')

Use backslash character / to join a statement span over multiple lines, as shown below.

EXAMPLE:

if 100 > 99 and \


200 <= 300 and \
True != False:
print('Hello World!')
the backslash character spans a single statement in one logical line and multiple physical
lines, but not the two different statements in one logical line.

EXAMPLE:

>>> print('Hello \
World!') # a multi-line statement
Hello World!
>>> print('Hello') \
print(' World!') # two statement in one logical line
SyntaxError: invalid syntax

Use the semicolon; to separate multiple statements in a single line.


EXAMPLE:

print('id: ', 1);print('First Name: ', 'Steve');print('Last Name: ', 'Jobs')

Expressions in parentheses (), square brackets [ ], or curly braces { } can be spread over
multiple lines without using backslashes.

EXAMPLE:
list = [1, 2, 3, 4
5, 6, 7, 8,
9, 10, 11, 12]

Indentation in Python:
The leading space or tab at the beginning of the line is considered as the indentation level
of the line, which is used to determine the group of statements. Statements with the same
level of indentation are considered as a group or block.

Indentation Rules:
● Use the colon: to start a block and press Enter.
● All the lines in a block must use the same indentation, either space or a tab.
● Python recommends four spaces as indentation to make the code more readable. Do not
mix space and tab in the same block.
● A block can have inner blocks with next-level indentation.

The following example demonstrates if elif blocks:


EXAMPLE IF BLOCK:

if 10 > 5: # 1st block starts


print("10 is greater than 5") # 1st block
print("Now checking 20 > 10") # 1st block
if 20 > 10: # 1st block
print("20 is greater than 10") # inner block
elif: # 2nd block starts
print("10 is less than 5") # 2nd block
print("This will never print") # 2nd block
The following function contains a block with two statements.

Python function block:

def SayHello(name):
print("Hello ", name)
print("Welcome to Python Tutorials")

You might also like