flint package

Subpackages

Submodules

flint.environment module

class flint.environment.Environment(enclosing=None)

Bases: object

assign(name, value)

Assigns a value to an existing variable in the environment.

Parameters:
  • name (str) – The name of the variable.

  • value (any) – The value to assign to the variable.

Raises:

RuntimeError – If the variable is not defined in the environment.

define(name, value)

Defines a new variable in the environment.

Prevents redefinition of variables in the same scope.

Parameters:
  • name (str) – The name of the variable.

  • value (any) – The value associated with the variable.

Raises:

RuntimeError – If the variable is already defined in the current scope.

get(name)

Retrieve the value of a variable from the environment. :param name: The token representing the variable name. :type name: Token

Returns:

The value of the variable if it exists in the environment.

Return type:

Any

Raises:

CustomRunTimeError – If the variable is not found in the environment.

log_environment(filepath)

flint.flint module

class flint.flint.Flint

Bases: object

global_environment = <flint.environment.Environment object>
had_error = False
had_runtime_error = False
static main() None

The main entry point for the Flint application.

This function handles the command-line arguments and determines whether to run a script file or enter REPL (Read-Eval-Print Loop) mode.

Usage:

Flint [script]

If a script file is provided as an argument, it runs the script. If no arguments are provided, it starts the REPL mode.

Exits with status code 64 if more than one argument is provided.

static run(source, environment, is_repl_mode=False)

Compiles and executes the given source code.

static run_file(path)
static run_prompt()

Starts a Read-Eval-Print Loop (REPL) for the Flint programming language.

This function continuously prompts the user for input, evaluates the input using the Flint interpreter, and prints the result. The loop terminates when the user inputs an empty string or ‘exit’.

Usage:

run_prompt()

Note

This function sets Flint.had_error to False after each command execution.

flint.flint_callable module

class flint.flint_callable.ClockCallable

Bases: FlintCallable

arity()

Returns the number of arguments the callable expects

call(interpreter, arguments)

Excutes the callable with the given interpreter and arguments

to_string()

Returns the string representation of the callable

class flint.flint_callable.FlintCallable

Bases: ABC

abstract arity() int

Returns the number of arguments the callable expects

abstract call(interpreter, arguments) object

Excutes the callable with the given interpreter and arguments

abstract to_string() str

Returns the string representation of the callable

flint.flint_function module

class flint.flint_function.FlintFunction(declaration)

Bases: FlintCallable

arity()

Returns the number of parameters the function takes.

call(interpreter, arguments)

Calls the function with the given arguments.

to_string()

Returns the string representation of the function.

flint.interpreter module

class flint.interpreter.Interpreter(environment)

Bases: object

check_number_operand(operator, operand)

Ensure the operand is a number else raise an error

check_number_operands(operator, left, right)

Ensures that both operands are numbers

evaluate(expr)

Evaluates the given expression by accepting the visitor

execute(stmt)

Executes a statement by delegating to its accept method.

Parameters:

stmt (Stmt) – The statement to be executed.

execute_block(statements, environment)

Executes a block of statements in a given environment.

Parameters:
  • statements (list) – The statements to execute.

  • environment (Environment) – The environment for the block’s scope.

interpret(statements)

Executes a list of statements sequentially.

Parameters:

statements (List[Stmt]) – A list of statements to be executed.

Handles runtime errors gracefully by reporting them using the runtime_error method.

is_equal(left, right)
is_truthy(object)

Determines the truthiness of an object based on Flints’s semantics

stringify(obj)

Converts the given object to its string representation. :param obj: The object to be converted to a string. It can be of any type.

Returns:

The string representation of the object. If the object is None,

it returns “nil”. If the object is a float and ends with “.0”, the “.0” part is removed from the string representation.

Return type:

str

visit_assign(expr)

Visit an assignment expression, evaluate its value, and assign it to the corresponding variable in the environment.

Parameters:

expr – The assignment expression to be visited. It should have ‘value’ and ‘name’ attributes.

Returns:

The evaluated value of the assignment expression.

visit_binary(expr)

Evaluates binary expressions for supported operators

visit_block(stmt)

Visits a block statement, creating a new environment for the block and executing the statements within it.

Parameters:

stmt – The block statement to be visited, which contains a list of statements.

Returns:

None

visit_call(expr)

Handles a call expression by evaluating the callee and arguments, and then calling the function.

visit_expression(stmt)

Executes an expression statement.

Parameters:

stmt – The expression statement to execute.

visit_function(stmt)

Evaluates and executes a function declaration statement.

This method creates a new FlintFunction object with the given function statement and stores it in the environment with the function’s name.

Parameters:

stmt (FunctionStmt) – The function declaration statement to execute

visit_grouping(expr)

Evaluates a grouping expression

visit_if_stmt(stmt)
visit_literal(expr)

Evaluates literal expression

visit_logical(expr)
visit_print(stmt)

Evaluates and executes a print statement.

This method evaluates the given expression in the print statement and outputs the result to the console using Python’s built-in print function. A custom print library may replace this in the future for enhanced functionality.

Parameters:

stmt (PrintStmt) – The print statement to evaluate.

visit_unary(expr)

Visit unary expression

visit_var(stmt)

Evaluates and executes a variable declaration statement.

This method evaluates the initializer expression in the variable declaration statement and stores the result in the environment with the variable’s name.

Parameters:

stmt (VarStmt) – The variable declaration statement to execute

visit_variable(expr)

Evaluates a variable expression by retrieving its value from the environment.

Parameters:

expr (VariableExpr) – The variable expression to evaluate.

visit_while_stmt(stmt)

flint.parser module

class flint.parser.Parser(tokens, is_repl_mode)

Bases: object

Parser class for parsing a list of tokens into an Abstract Syntax Tree (AST). .. attribute:: _tokens

A list of Token objects to be parsed.

type:

list

current

Tracks the current position in the token list.

Type:

int

Inner Classes:

ParseError: Custom exception for parsing errors.

exception ParseError

Bases: Exception

Custom exception for error class

advance()

Advance the parser to the next token and return the current token.

Returns:

The token that was advanced past.

Return type:

Token

and_logic()
assignment()
binary_expr(sub_expr_method, *operators)

Parse a binary expression.

Parameters:
  • sub_expr_method (callable) – The method to parse the sub-expressions (e.g., self.unary).

  • operators (TokenType) – The binary operators to handle at this level.

  • Returns

  • Expr – The parsed binary expression or a single sub-expression.

block()

Parses a block of code enclosed in braces and returns a list of statements. This method continues to parse declarations and add them to the statements list until it encounters a right brace or reaches the end of the input. :returns: A list of parsed statements within the block. :rtype: list

Raises:

ParseError – If the right brace ‘}’ is not found after the block.

call()

Parse a call expression.

check(type)

Check if the current token matches a specific type.

Parameters:

token_type (str) – The type of token to check.

Returns:

True if the current token matches the type, False otherwise.

Return type:

bool

comparision()

Parses and returns a comparison expression. This method handles comparison operators such as greater than, greater than or equal to, less than, and less than or equal to. It maintains left associativity by constructing a binary expression tree. :returns: The parsed comparison expression. :rtype: expr

consume(type: TokenType, message: str)

Consume the current token if it matches the expected type.

Parameters:
  • token_type (str) – The expected type of the token.

  • error_message (str) – The error message to raise if the token doesn’t match.

Returns:

The consumed token.

Return type:

Token

Raises:

RuntimeError – If the current token does not match the expected type.

declaration()

Parse a declaration statement.

If the current token matches a variable declaration (VAR), parse it as a variable declaration. Otherwise, parse it as a general statement.

Returns:

The parsed statement object, or None if a parse error occurs.

Return type:

Stmt

equality()

Parses an equality expression, handling binary operations with ‘!=’ and ‘==’.

error(token, message)

Handles parsing errors by raising a custom ParseError.

Parameters:
  • token – The token where the error occurred.

  • message – A description of the error.

Raises:

self.ParseError – Custom exception indicating a parsing error.

expression()

Parses and returns an expression.

expression_statement()

Parses an expression statement in the source code.

This method expects an expression followed by a semicolon. It consumes the semicolon token and returns an Expression statement.

Returns:

An expression statement object.

Return type:

Stmt.Expression

Raises:

ParseError – If the semicolon is not found after the expression.

factor()
finish_call(callee)

Parse the arguments for a function call expression.

for_statement()
function(kind)

Parse a funtion declaration.

if_statement()
is_at_end() bool

Check if the parser has reached the end of the tokens.

Returns:

True if at the end of the token stream, False otherwise.

Return type:

bool

match(*types: str) bool

Checks if the current token matches any of the given types. If a match is found, advances the token pointer.

Parameters:

types (str) – The token types to check against.

Returns:

True if a match is found, False otherwise.

Return type:

bool

or_logic()
parse()

Parses the input and returns a list of statements. This method repeatedly calls the declaration method to parse declarations until the end of the input is reached. The parsed declarations are collected into a list and returned. :returns: A list of parsed statements. :rtype: list

peek()

Get the current token without advancing the parser.

Returns:

The current token.

Return type:

Token

previous()

Get the most recently consumed token.

Returns:

The previous token.

Return type:

Token

primary()

Parse a primary expression.

Handles literals, variables, and grouped expressions enclosed in parentheses.

Returns:

The parsed primary expression.

Return type:

Expr

print_statement()

Parse a print statement.

This method consumes the current token as an expression to be printed, and ensures the statement ends with a semicolon.

Returns:

A Print statement AST node containing the parsed expression.

Return type:

Print

statement()

Parse a single statement.

Returns:

The parsed statement as an AST node.

Return type:

Stmt

synchronize()

Synchronizes the parser by advancing through tokens until it finds a statement boundary. This is typically used to recover from a parsing error and continue parsing subsequent statements. The method advances the parser until it finds a semicolon or a token that indicates the start of a new statement, such as a class, function, variable declaration, or control flow keyword (for, if, while, print, return). :returns: None

term()
property tokens

Provides read-only access to the tokens.

unary()
var_declaration()

Parse a variable declaration statement.

Expects a variable name, followed optionally by an initializer (if an ‘=’ token is present), and ends with a semicolon.

Returns:

A variable declaration statement containing the variable’s name and initializer expression (or None if no initializer is provided).

Return type:

Stmt.Var

while_statement()

flint.runtime_error module

exception flint.runtime_error.CustomRunTimeError(tokens, message)

Bases: Exception

Custom exception for runtime errors with a token context

flint.scanner module

class flint.scanner.Scanner(source)

Bases: object

KEYWORDS = {'and': TokenType.KEYWORD_AND, 'class': TokenType.KEYWORD_CLASS, 'else': TokenType.KEYWORD_ELSE, 'false': TokenType.KEYWORD_FALSE, 'fn': TokenType.KEYWORD_FUNCTION, 'for': TokenType.KEYWORD_FOR, 'if': TokenType.KEYWORD_IF, 'nil': TokenType.KEYWORD_NIL, 'or': TokenType.KEYWORD_OR, 'print': TokenType.KEYWORD_PRINT, 'return': TokenType.KEYWORD_RETURN, 'super': TokenType.KEYWORD_SUPER, 'this': TokenType.KEYWORD_THIS, 'true': TokenType.KEYWORD_TRUE, 'var': TokenType.KEYWORD_VARIABLE, 'while': TokenType.KEYWORD_WHILE}
add_token(type_, literal=None)
advance() str
indentifier()
is_alpha(char)

Check if the character is an alphabet or an underscore.

is_alphanumeric(char)

Check if the char is a letter, digit or underscore

is_at_end()
is_digit(c)
match(expected) bool
number()
peek()
peek_next()
scan_multiline_comment()
scan_token()
scan_tokens()
string()

flint.token module

class flint.token.Token(type_: TokenType, lexeme: str, literal: object, line: int)

Bases: object

Represents a single token in the Tachyon programming language.

params:

type_ (TokenType): The type of the token (e.g., identifier, keyword, operator). lexeme (str): The actual string representation of the token from the source code. literal (object): The literal value of the token, if applicable (e.g., number or string values). line (int): The line number in the source code where the token appears.

__str__()

Returns a formatted string representation of the token for debugging and logging purposes.

flint.token_types module

class flint.token_types.TokenType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

This class categorizes tokens into: - Single-character tokens (e.g., parentheses, operators). - One or two-character tokens (e.g., comparison operators). - Literals (e.g., identifiers, strings, numbers). - Keywords (reserved words in the language). - Special tokens (e.g., end-of-file).

ASSIGN = 15
ASTERISK = 11
COMMA = 5
DOT = 6
EOF = 40
EQUAL = 12
EQUAL_EQUAL = 16
EXCLAMATION = 13
EXCLAMATION_EQUAL = 14
FORWARD_SLASH = 10
GREATER_THAN = 17
GREATER_THAN_EQUAL = 18
IDENTIFIER = 21
KEYWORD_AND = 24
KEYWORD_CLASS = 25
KEYWORD_ELSE = 26
KEYWORD_FALSE = 27
KEYWORD_FOR = 29
KEYWORD_FUNCTION = 28
KEYWORD_IF = 30
KEYWORD_NIL = 31
KEYWORD_OR = 32
KEYWORD_PRINT = 33
KEYWORD_RETURN = 34
KEYWORD_SUPER = 35
KEYWORD_THIS = 36
KEYWORD_TRUE = 37
KEYWORD_VARIABLE = 38
KEYWORD_WHILE = 39
LEFT_BRACE = 3
LEFT_PAREN = 1
LESS_THAN = 19
LESS_THAN_EQUAL = 20
MINUS = 7
NUMBER_LITERAL = 23
PLUS = 8
RIGHT_BRACE = 4
RIGHT_PAREN = 2
SEMICOLON = 9
STRING_LITERAL = 22

Module contents