Search code examples
programming-languageslanguage-design

Language Definition Question


Can someone please help me understand exactly what this means?

<stmt> := var <ident> = <expr>
    | <ident> = <expr>
    | for <ident> = <expr> to <expr> do <stmt> end
    | read_int <ident>
    | print <expr>
    | <stmt> ; <stmt>

<expr> := <string>
    | <int>
    | <arith_expr>
    | <ident>

<bin_expr> := <expr> <bin_op> <expr>
<bin_op> := + | - | * | /

<ident> := <char> <ident_rest>*
<ident_rest> := <char> | <digit>

<int> := <digit>+
<digit> := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

<string> := " <string_elem>* "
<string_elem> := <any char other than ">

In the first part, I'm assuming <ident> means "Identifier", and <expr> means "Expression" and <arith_expr> means "Arithmatic Expression". But the rest is a little confusing to me.

Thank you


Solution

  • <stmt> := var <ident> = <expr>
        | <ident> = <expr>
        | for <ident> = <expr> to <expr> do <stmt> end
        | read_int <ident>
        | print <expr>
        | <stmt> ; <stmt>
    

    Translation: A statement can be either

    • a variable declaration (with an expression)
    • a variable assignment (with an expression)
    • a for() loop (with two expressions and a statement)
    • read_int (with an identifier)
    • print (with an expression)
    • two statements separated by a semicolon

    <expr> := <string>
        | <int>
        | <arith_expr>
        | <ident>
    

    Translation: An expression can be either

    • a string literal
    • and integer
    • an arithmetic expression
    • an identifier

    <bin_expr> := <expr> <bin_op> <expr>
    <bin_op> := + | - | * | /
    

    A binary expression consists of two expressions and a binary operator inbetween. Binary operators are:

    + - * /
    

    <ident> := <char> <ident_rest>*
    <ident_rest> := <char> | <digit>
    

    An identifier always starts with a character, but the rest of the identifier can consist of characters and digits


    <int> := <digit>+
    <digit> := 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
    

    definition of a digit


    <string> := " <string_elem>* "
    <string_elem> := <any char other than ">
    

    definition of a string literal