Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Grammar

This page describes the formal grammar of Felico.

Notation

The grammar is described using EBNF-like notation:

  • ? means optional (zero or one)
  • * means zero or more repetitions
  • + means one or more repetitions
  • | means alternation (or)
  • () groups items

Lexical Structure

Keywords

if else fn let return while break continue true false

Operators

+ - * / % == != < <= > >= && || !

Delimiters

( ) { } [ ] , ; :

Syntax Grammar

Program

program = statement*

Statements

statement = let_statement
          | expression_statement
          | block_statement

let_statement = "let" IDENTIFIER (":" type)? "=" expression

expression_statement = expression ";"?

block_statement = "{" statement* "}"

Expressions

expression = assignment_expr

assignment_expr = logical_or_expr
                | IDENTIFIER "=" assignment_expr

logical_or_expr = logical_and_expr ("||" logical_and_expr)*

logical_and_expr = equality_expr ("&&" equality_expr)*

equality_expr = comparison_expr (("==" | "!=") comparison_expr)*

comparison_expr = additive_expr (("<" | "<=" | ">" | ">=") additive_expr)*

additive_expr = multiplicative_expr (("+" | "-") multiplicative_expr)*

multiplicative_expr = unary_expr (("*" | "/" | "%") unary_expr)*

unary_expr = ("!" | "-") unary_expr
           | call_expr

call_expr = primary_expr ("(" argument_list? ")")*

primary_expr = IDENTIFIER
             | literal
             | "(" expression ")"
             | if_expr
             | block_expr
             | function_expr

if_expr = "if" expression block_expr ("else" (if_expr | block_expr))?

block_expr = "{" statement* expression? "}"

function_expr = "fn" "(" parameter_list? ")" ("->" type)? block_expr

Literals

literal = INTEGER
        | FLOAT
        | STRING
        | BOOLEAN

BOOLEAN = "true" | "false"
INTEGER = [0-9]+
FLOAT = [0-9]+ "." [0-9]+
STRING = '"' ([^"\\] | escape_sequence)* '"'

Types

type = "int" | "float" | "bool" | "string" | "()"

Tokens

Identifiers

IDENTIFIER = [a-zA-Z_][a-zA-Z0-9_]*

Comments

line_comment = "//" [^\n]*
block_comment = "/*" ([^*] | "*" [^/])* "*/"

Operator Precedence

From highest to lowest:

  1. Primary expressions, function calls
  2. Unary operators (!, -)
  3. Multiplicative (*, /, %)
  4. Additive (+, -)
  5. Comparison (<, <=, >, >=)
  6. Equality (==, !=)
  7. Logical AND (&&)
  8. Logical OR (||)
  9. Assignment (=)

Notes

  • Semicolons are optional after expressions
  • Whitespace is generally insignificant
  • Comments are treated as whitespace
  • The grammar is subject to change as Felico evolves