Workshop 2
Workshop 2
2024-III
WorkShop No. 2 — Compilers
1. For each one of next cases definr a regular expression as used in a compiler based on
the Python re library:
(i) Identifier: A regular expression to match valid identifiers (variable names, func-
tion names, etc.).
(ii) Integer Literal: A regular expression to match integer literals.
(iii) Floating Point Literal: A regular expression to match floating-point literals.
(iv) String Literal: A regular expression to match string literals enclosed in double
quotes.
(v) Single-line Comment: A regular expression to match single-line comments
starting with ‘//‘.
(vi) Multi-line Comment: A regular expression to match multi-line comments
enclosed in ‘/* */‘.
(vii) Whitespace: A regular expression to match whitespace characters (spaces, tabs,
newlines).
(viii) Operators: A regular expression to match common operators (e.g., ‘+‘, ‘-‘, ‘*‘,
‘/‘, ‘==‘, ‘!=‘).
(ix) Keywords: A regular expression to match reserved keywords (e.g., ‘if‘, ‘else‘,
‘while‘, ‘return‘).
(x) Hexadecimal Literal: A regular expression to match hexadecimal literals.
Carlos Andrés Sierra, Computer Engineer, M.Sc. on Computer Engineering, Titular Professor at Uni-
versidad Distrital Francisco José de Caldas.
Any comment or concern related to this document could be send to Carlos A. Sierra at e-mail: cavir-
[email protected]
COMPUTER SCIENCE III — WORKSHOP NO. 2 2
S −> Program
Program −> S t a t e m e n t L i s t
S t a t e m e n t L i s t −> Statement S t a t e m e n t L i s t | <lambda>
Statement −> Assignment | I f S t a t e m e n t | WhileStatement | ReturnStatement
Assignment −> I d e n t i f i e r "=" E x p r e s s i o n " ; "
I f S t a t e m e n t −> " i f " " ( " E x p r e s s i o n " ) " " { " S t a t e m e n t L i s t " } " E l s e P a r t
E l s e P a r t −> " e l s e " " { " S t a t e m e n t L i s t " } " | <lambda>
WhileStatement −> " w h i l e " " ( " E x p r e s s i o n " ) " " { " S t a t e m e n t L i s t " } "
ReturnStatement −> " r e t u r n " E x p r e s s i o n " ; "
E x p r e s s i o n −> Term E x p r e s s i o n ’
E x p r e s s i o n ’ −> "+" Term E x p r e s s i o n ’ | " −" Term E x p r e s s i o n ’ |
<lambda>
Term −> F a c t o r Term ’
Term ’ −> " ∗ " F a c t o r Term ’ | " / " F a c t o r Term ’ | <lambda>
F a c t o r −> " ( " E x p r e s s i o n " ) " | I d e n t i f i e r | Number
I d e n t i f i e r −> [ a−zA−Z_ ] [ a−zA−Z0−9_] ∗
Number −> [0 −9]+
Explanation:
Based on the provided context-free grammar, create derivation trees for the following
statements:
(a) Exercise 1:
x = 5 + 3 ∗ 2;
(b) Exercise 2:
COMPUTER SCIENCE III — WORKSHOP NO. 2 3
i f ( x > 0) {
y = x − 1;
} else {
y = 0;
}
(c) Exercise 3:
while ( x < 10) {
x = x + 1;
}
(d) Exercise 4:
return (a + b) ∗ c ;