Syntax Analysis

Parser

Ahmad Yoosofan

Compiler course

University of Kashan

Checking Syntax

  1. I am student
  2. ⊠ I are student
  3. ⊠ You am student
  4. ⊠ They am student
  5. 342 + 261 * 5
  6. 45 * (23 + 332)
  7. ⊠ 23 * + 54
  8. ⊠ 2323 +
  9. ⊠ * 232
  10. ⊠ 2323 + 23 * (23 (23))
  11. ⊠ 234 * (45 * (23+3)
  12. We need more theory to simplify the task

Grammar

https://www.nltk.org/book/ch08.html

Simple Grammars

  1. Writing grammar is harder than finding sentences of a grammar
    • 87
    • 78968 + (3334+43)
    • 78968 * (3334+43)
    • 78968 * (334+43)
    • 78968 * ((334+43) * 4)
    • 78968 * ((334+43)* 4)
    • (23 + 45) + 45
    • (23 + 45) + (45 * 443)
    • 2 * ((23 + 45) + (45 * 443))

Grammar of simpler calculator

  1. It has just +, *, (, )
  2. There is no priority
  3. No unary operator (+)
  4. Use paranthesis for more that one operator
    1. (2+3)+4
    2. 2+(4+3)
    3. (2+(4+3))+5
    4. (2*(4*3))*5
  5. Terminals
  6. INT (for simplicity we use token.type: i)
    1. (i+i)+i
    2. i+(i+i)
    3. (i+(i+i))+i
    4. (i*(i*i))*i
  7. {'+', '*'}
  8. {'(', ')'}
  9. No need for naming operators, just using the symbol
  10. Use recursion
  1. Start Symbol (S)
  2. S → A + A
  3. S → A * A
  4. S → A
  5. A → (S)
  6. A → i
  7. Derivation Tree

Derivation Tree(I)

  1. S → A + A
  2. S → A * A
  3. S → A
  4. A → (S)
  5. A → i
  • 43 + 87

Left Most Derivation

  1. S ⇒ A + A ⇒
  2. i[43] + A ⇒
  3. i[43] + i[87]

Right Most Derivation

  1. S ⇒ A + A ⇒
  2. A + i[87] ⇒
  3. i[43] + i[87]

Derivation Tree(II)

  1. S → A + A
  2. S → A * A
  3. S → A
  4. A → (S)
  5. A → i
  • (32 * 5)

Left Most Derivation

  1. S ⇒ A ⇒
  2. (S)
  3. (A * A) ⇒
  4. (i[32] * A) ⇒
  5. (i[32] * i[5])

Right Most Derivation

  1. S ⇒ A ⇒
  2. (S)
  3. ( A * A ) ⇒
  4. ( A * i[5] ) ⇒
  5. ( i[32] * i[5] )

Derivation Tree(III)

  • S → A + A | A * A | A
  • A → (S) | i
  • 3 * (32 + 5)

Left Most Derivation

  1. S ⇒ A * A ⇒
  2. i[3] * A ⇒
  3. i[3] * (S) ⇒
  4. i[3] * ( A + A ) ⇒
  5. i[3] * ( i[32] + A ) ⇒
  6. i[3] * ( i[32] + i[5] )

Right Most Derivation

  1. S ⇒ A * A ⇒
  2. A * ( S ) ⇒
  3. A * ( A + A ) ⇒
  4. A * ( A + i[5] ) ⇒
  5. A * ( i[32] + i[5] ) ⇒
  6. i[3] * ( i[32] + i[5] )

More Languages

  1. Adding Priority
  2. Adding Minus and Divide
  3. Adding Variables (Assignment)
  4. A simple Programming Language (if and while)

Next Topic: Recursive Descendant Parser

End

1