The Wayback Machine - https://web.archive.org/web/20241118013246/https://www.geeksforgeeks.org/how-to-create-a-programming-language-using-python/
Open In App

How to Create a Programming Language using Python?

Last Updated : 10 Jul, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to learn how to create your own programming language using SLY(Sly Lex Yacc) and Python. Before we dig deeper into this topic, it is to be noted that this is not a beginner’s tutorial and you need to have some knowledge of the prerequisites given below.

Prerequisites

  • Rough knowledge about compiler design.
  • Basic understanding of lexical analysis, parsing and other compiler design aspects.
  • Understanding of regular expressions.
  • Familiarity with Python programming language.

Getting Started

Install SLY for Python. SLY is a lexing and parsing tool which makes our process much easier.

pip install sly

Building a Lexer

The first phase of a compiler is to convert all the character streams(the high level program that is written) to token streams. This is done by a process called lexical analysis. However, this process is simplified by using SLY

First let’s import all the necessary modules.

Python3




from sly import Lexer


Now let’s build a class BasicLexer which extends the Lexer class from SLY.  Let’s make a compiler that makes simple arithmetic operations. Thus we will need some basic tokens such as NAME, NUMBER, STRING. In any programming language, there will be space between two characters. Thus we create an ignore literal. Then we also create the basic literals like ‘=’, ‘+’ etc., NAME tokens are basically names of variables, which can be defined by the regular expression [a-zA-Z_][a-zA-Z0-9_]*. STRING tokens are string values and are bounded by quotation marks(” “). This can be defined by the regular expression \”.*?\”.

Whenever we find digit/s, we should allocate it to the token NUMBER and the number must be stored as an integer. We are doing a basic programmable script, so let’s just make it with integers, however, feel free to extend the same for decimals, long etc., We can also make comments. Whenever we find “//”, we ignore whatever that comes next in that line. We do the same thing with new line character. Thus, we have build a basic lexer that converts the character stream to token stream.

Python3




class BasicLexer(Lexer):
    tokens = { NAME, NUMBER, STRING }
    ignore = '\t '
    literals = { '=', '+', '-', '/', 
                '*', '(', ')', ',', ';'}
  
  
    # Define tokens as regular expressions
    # (stored as raw strings)
    NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
    STRING = r'\".*?\"'
  
    # Number token
    @_(r'\d+')
    def NUMBER(self, t):
        
        # convert it into a python integer
        t.value = int(t.value) 
        return t
  
    # Comment token
    @_(r'//.*')
    def COMMENT(self, t):
        pass
  
    # Newline token(used only for showing
    # errors in new line)
    @_(r'\n+')
    def newline(self, t):
        self.lineno = t.value.count('\n')


Building a Parser

 First let’s import all the necessary modules.

Python3




from sly import Parser


Now let’s build a class BasicParser which extends the Lexer class. The token stream from the BasicLexer is passed to a variable tokens. The precedence is defined, which is the same for most programming languages. Most of the parsing written in the program below is very simple. When there is nothing, the statement passes nothing. Essentially you can press enter on your keyboard(without typing in anything) and go to the next line. Next, your language should comprehend assignments using the “=”.  This is handled in line 18 of the program below. The same thing can be done when assigned to a string.

Python3




class BasicParser(Parser):
    #tokens are passed from lexer to parser
    tokens = BasicLexer.tokens
  
    precedence = (
        ('left', '+', '-'),
        ('left', '*', '/'),
        ('right', 'UMINUS'),
    )
  
    def __init__(self):
        self.env = { }
  
    @_('')
    def statement(self, p):
        pass
  
    @_('var_assign')
    def statement(self, p):
        return p.var_assign
  
    @_('NAME "=" expr')
    def var_assign(self, p):
        return ('var_assign', p.NAME, p.expr)
  
    @_('NAME "=" STRING')
    def var_assign(self, p):
        return ('var_assign', p.NAME, p.STRING)
  
    @_('expr')
    def statement(self, p):
        return (p.expr)
  
    @_('expr "+" expr')
    def expr(self, p):
        return ('add', p.expr0, p.expr1)
  
    @_('expr "-" expr')
    def expr(self, p):
        return ('sub', p.expr0, p.expr1)
  
    @_('expr "*" expr')
    def expr(self, p):
        return ('mul', p.expr0, p.expr1)
  
    @_('expr "/" expr')
    def expr(self, p):
        return ('div', p.expr0, p.expr1)
  
    @_('"-" expr %prec UMINUS')
    def expr(self, p):
        return p.expr
  
    @_('NAME')
    def expr(self, p):
        return ('var', p.NAME)
  
    @_('NUMBER')
    def expr(self, p):
        return ('num', p.NUMBER)


The parser should also parse in arithmetic operations, this can be done by expressions. Let’s say you want something like shown below. Here all of them are made into token stream line-by-line and parsed line-by-line. Therefore, according to the program above, a = 10 resembles line 22. Same for b =20. a + b resembles line 34, which returns a parse tree (‘add’, (‘var’, ‘a’), (‘var’, ‘b’)).

GFG Language > a = 10
GFG Language > b = 20
GFG Language > a + b
30

Now we have converted the token streams to a parse tree. Next step is to interpret it.

Execution

Interpreting is a simple procedure. The basic idea is to take the tree and walk through it to and evaluate arithmetic operations hierarchically. This process is recursively called over and over again till the entire tree is evaluated and the answer is retrieved. Let’s say, for example, 5 + 7 + 4. This character stream is first tokenized to token stream in a lexer. The token stream is then parsed to form a parse tree. The parse tree essentially returns (‘add’, (‘add’, (‘num’, 5), (‘num’, 7)), (‘num’, 4)). (see image below)

The interpreter is going to add 5 and 7 first and then recursively call walkTree and add 4 to the result of addition of 5 and 7. Thus, we are going to get 16. The below code does the same process. 

Python3




class BasicExecute:
    
    def __init__(self, tree, env):
        self.env = env
        result = self.walkTree(tree)
        if result is not None and isinstance(result, int):
            print(result)
        if isinstance(result, str) and result[0] == '"':
            print(result)
  
    def walkTree(self, node):
  
        if isinstance(node, int):
            return node
        if isinstance(node, str):
            return node
  
        if node is None:
            return None
  
        if node[0] == 'program':
            if node[1] == None:
                self.walkTree(node[2])
            else:
                self.walkTree(node[1])
                self.walkTree(node[2])
  
        if node[0] == 'num':
            return node[1]
  
        if node[0] == 'str':
            return node[1]
  
        if node[0] == 'add':
            return self.walkTree(node[1]) + self.walkTree(node[2])
        elif node[0] == 'sub':
            return self.walkTree(node[1]) - self.walkTree(node[2])
        elif node[0] == 'mul':
            return self.walkTree(node[1]) * self.walkTree(node[2])
        elif node[0] == 'div':
            return self.walkTree(node[1]) / self.walkTree(node[2])
  
        if node[0] == 'var_assign':
            self.env[node[1]] = self.walkTree(node[2])
            return node[1]
  
        if node[0] == 'var':
            try:
                return self.env[node[1]]
            except LookupError:
                print("Undefined variable '"+node[1]+"' found!")
                return 0


Displaying the Output

To display the output from the interpreter, we should write some codes. The code should first call the lexer, then the parser and then the interpreter and finally retrieves the output. The output in then displayed on to the shell.

Python3




if __name__ == '__main__':
    lexer = BasicLexer()
    parser = BasicParser()
    print('GFG Language')
    env = {}
      
    while True:
          
        try:
            text = input('GFG Language > ')
          
        except EOFError:
            break
          
        if text:
            tree = parser.parse(lexer.tokenize(text))
            BasicExecute(tree, env)


It is necessary to know that we haven’t handled any errors. So SLY is going to show it’s error messages whenever you do something that is not specified by the rules you have written.

Execute the program you have written using,

python you_program_name.py

Footnotes

The interpreter that we built is very basic. This, of course, can be extended to do a lot more. Loops and conditionals can be added. Modular or object oriented design features can be implemented. Module integration, method definitions, parameters to methods are some of the features that can be extended on to the same. 



Similar Reads

Natural Language Processing(NLP) VS Programming Language
In the world of computers, there are mainly two kinds of languages: Natural Language Processing (NLP) and Programming Languages. NLP is all about understanding human language while programming languages help us to tell computers what to do. But as technology grows, these two areas are starting to overlap in cool ways, changing how we interact with
4 min read
Difference Between Machine Language and Assembly Language
Machine language is the low level programming language. Machine language can only be represented by 0s and 1s. In earlier when we have to create a picture or show data on the screen of the computer then it is very difficult to draw using only binary digits(0s and 1s). For example: To write 120 in the computer system its representation is 1111000. S
2 min read
Difference Between Assembly Language And Machine Language
Assembly language and machine language are both low-level languages that are intended for direct manipulation of the hardware but assembly language is slightly more abstract and much easier to use than machine language. Machine language is a series of instructions written in binary that the CPU can understand and execute directly, making it the low
4 min read
Difference Between Hardware Description Language and Software Language
Hardware and software are fundamental components of modern computing systems. While software languages are widely known for programming applications, hardware description languages (HDLs) play a crucial role in designing and describing electronic circuits. Ever wondered how Hardware Systems are designed, planned, and expressed in what form or langu
6 min read
Python - Fastest Growing Programming Language
There was a time when the word "Python" meant a particularly large snake but now it is a programming language that is all the rage!!! According to the TIOBE Index, Python is the fourth most popular programming language in the world currently and this extraordinary growth is only set to increase as observed by Stack Overflow Trends. So the question
5 min read
Difference between Python and Lua Programming Language
Python Python is one of the most popular and powerful scripting languages that works nowadays. It is a high-level interpreted programming language. It is a very simple scripting language and very easy to learn as compared to other languages. Python programming language is best for both scripting applications and as standalone programs along with th
3 min read
Introduction of HIP parallel programming language
One must have header terms parallel computing, heterogeneous computing, high performance computing (HPC). If not you can explore HPC domain it is one of the fastest growing technology. It has touched almost all industries such as Medical, Security, Entertainment, Autonomous car, Finance, Oil industry etc. and list is growing every year. Companies l
2 min read
Facts about Cython Programming Language
Cython is a programming language. It can run on Windows, macOS, and Linux operating systems. It had a version ranging from 2.6 to 3.8. Cython 3.0.0 is under development. In Cython, the Code written in Python is converted to C language. High traffic websites such as Quora use Cython Programming language. History Cython is actually derived from the P
4 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
What is Fourth Generation Programming Language?
The language which is used to create programs is called a programming language. It comprises a set of instructions that are used to produce various kinds of output. A Fourth Generation Programming Language (4GL) is designed to make coding easier and faster for people by using more human-friendly commands, compared to older programming languages. In
4 min read
Detect an Unknown Language using Python
The idea behind language detection is based on the detection of the character among the expression and words in the text. The main principle is to detect commonly used words like to, of in English. Python provides various modules for language detection. In this article, the modules covered are: langdetecttextbloblangid Method 1: Using langdetect li
2 min read
Language Detection in Python using Tkinter
Prerequisite: Tkinter In this article, we will learn about language detection Using Python in Tkinter. In Simple Words, language identification is the problem of determining which natural language given content is in. Modules UsedTkinter module is used in Python to create GUI based interfaces.For Language detection, we will use the langdetect Modul
2 min read
Language Translator Using Google API in Python
API stands for Application Programming Interface. It acts as an intermediate between two applications or software. In simple terms, API acts as a messenger that takes your request to destinations and then brings back its response for you. Google API is developed by Google to allow communications with their servers and use their API keys to develop
3 min read
Difference between Functional Programming and Object Oriented Programming
What is Functional Programming?In functional programming, we have to build programs using functions. An example of functional programming is Haskell language. What is Object Oriented Programming?Object-oriented programming is built by using classes and objects. In this, we have concepts of encapsulation, inheritance, polymorphism, and Data abstract
3 min read
Natural Language Processing using Polyglot - Introduction
This article explains about a python NLP package known as Polyglot that supports various multilingual applications and offers a wide range of analysis and broad language coverage. It is developed by Rami Al-Rfou. It consists of lots of features such as Language detection (196 Languages)Tokenization (165 Languages)Named Entity Recognition (40 Langua
3 min read
Overview of Word Embedding using Embeddings from Language Models (ELMo)
What is word embeddings? It is the representation of words into vectors. These vectors capture important information about the words such that the words sharing the same neighborhood in the vector space represent similar meaning. There are various methods for creating word embeddings, for example, Word2Vec, Continuous Bag of Words(CBOW), Skip Gram,
2 min read
Language Learning App using Django
In this article, we will guide you through creating a language-learning application using Django in Python. Language Learning App Using DjangoBelow, is the step-by-step Implementation of a language learning app using Django in Python: Starting the Project FolderTo start the project use this command django-admin startproject language_appcd language_
15 min read
Python IMDbPY – Getting the language codes of the series
In this article we will see how we can get the language codes of series, language codes are basically codes for language in which series is available for example 'en' for English and 'hi' for Hindi. In order to get this we have to do the following - 1. Get the series details with the help of get_movie method 2. As this object will act as dictionary
2 min read
Python Tweepy – Getting the language of a tweet
In this article we will see how we can fetch the language of a tweet/status. The lang attribute of the Status object indicates the language of the status. The language is indicated in the language code example, English is en, Hindi is hi. In order to get the language of the status, we have to do the following : Identify the status ID of the status
2 min read
What makes Python a slow language ?
Python is a high-level language (than C or C++) thus Python itself manages details of a program like memory allocation, memory deallocation, pointers, etc. This makes writing codes in Python easier for programmers. Python code is first compiled into python Byte Code. The Byte Code interpreter conversion happens internally and most of it is hidden f
2 min read
Python Language advantages and applications
Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It generally has small programs when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and
4 min read
Python – The new generation Language
INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in recent years, making it one of the most in-demand pr
6 min read
Why Python is Called Interpreted Language
Python is frequently categorized as an interpreted language, but What does that suggest exactly? To apprehend why Python is called an interpreted language, it's essential to discover the concepts of interpretation and compilation, in addition to the execution model of Python code. Python is called an interpreted language because it executes code l
6 min read
Why Python is a High Level Language
Python is categorized as a high-level programming language because of several key characteristics and features that distinguish it from lower-level languages ​​such as assembly language or machine code. In this article, we will see why Python is a high-level language. What Does High-Level Language Mean?High-level languages ​​are programming languag
5 min read
Writing a Domain Specific Language (DSL) in Python
The Domain Specific Languages (DSLs) are specialized programming languages tailored to specific problem domains or application areas. They enable developers to express domain-specific concepts and operations in concise intuitive syntax enhancing productivity and readability. In this article, we'll explore the process of designing and implementing a
3 min read
Why Python is Called a Cross-Platform Language
Python, a high-level, interpreted programming language, is renowned for its cross-platform capabilities. This attribute signifies that Python code can run on various operating systems—such as Windows, macOS, Linux, and others—without requiring substantial modifications. Why Python is Called a Cross-Platform LanguageTable of Content Why Python is Ca
4 min read
wxPython - Create Radio Button using Create() function
Create() function is used for the two-step construction of Radio Button in wxPython. Create() function takes different attributes of radio button as an argument Syntax: wx.RadioButton.Create(parent, id=ID_ANY, label="", pos=DefaultPosition, size=DefaultSize, style=0, validator=DefaultValidator, name=RadioButtonNameStr ) Parameters: ParameterInput T
1 min read
wxPython - Create Static Box using Create() method
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items. In this article we will create Static Box using two step creation, in order to do that we will use Create() method. Syntax: wx.StaticBox.Create(parent, id=ID_ANY, label="", pos=DefaultPosi
2 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Draw house using Turtle programming in Python
Prerequisite: Turtle Programming in Python “Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! ”turtle” comes packed with the standard Python package and need not be installed externally. Step 1: Import turtle and math module in Python. import turtle import math Step 2: Choose a background color fo
2 min read
Practice Tags :
three90RightbarBannerImg