Lark Basics (Python, Lark to make a shell-like guy)

First

Since I am a beginner in programming and a fairly ignorant man, I do not know various names and ambiguous expressions such as "*** na guy" are used, but please forgive me.

Things to do

I want to make a guy (I don't know what to say) that works in a bash-like way of writing! So I made it.

The created program analyzes and executes the following script, for example, and returns the result.

rand -s3 a b c + say def | replace e E

(The result will be, for example, b a cd Ef)

In this article, I will omit the specific processing and briefly explain how to use Lark.


Library you are using Lark - a modern parsing library for Python


Creating a grammar rule file

First, create a text file that describes the grammar rules to be passed to the parser generator. In this case, A script is one or more chunks connected by a join. chunk is one or more sentences connected by pipe ... I will describe it like this.

Grammar.lark


script : [chunk join] chunk

chunk : [(sentence pipe)+] sentence

sentence : command [space option] [(space arg)+] [/\n+/]

command : chars
        | ([chars] subshell [chars])+
option : "-" (chars|subshell)+
arg : chars
    | "'" allchars "'"
    | ([chars] subshell [chars])+

subshell : "(" script ")" [/\n+/]

chars : /[^\+\|\s\(\)']+/[/\n+/]
allchars : /[^']+/[/\n+/]
space : " "
join : [space] "+" [space]
pipe : [space] "|" [space]

Creating a parser

How to create a parser. Just load the text file you just created and pass it to Lark.

Parser creation part


from lark import Lark

with open("Grammar.lark",encoding="utf-8") as grammar:
    LP = Lark(grammar.read(),start="script")

In the second argument start = of Lark (), write the outermost component (probably).

Let's try parsing rand -s3 a b c + say def | replace e E with this parser. You can display it with high readability by using the pretty () method of the analysis result tree, so let's use it.

Parser test


tree = LP.parse("rand -s3 a b c + say def | replace e E")
print(tree.pretty())

result


script
  chunk
    sentence
      command
        chars   ra
      space
      option
        chars   s3
      space
      arg
        chars   a
      space
      arg
        chars   b
      space
      arg
        chars   c
  join
    space
    space
  chunk
    sentence
      command
        chars   sa
      space
      arg
        chars   de
    pipe
      space
      space
    sentence
      command
        chars   re
      space
      arg
        chars   e
      space
      arg
        chars   E

(That? Space is strange? I don't use it for processing ...)

Creating a transformer

Now, let's create a part that executes processing according to the state of the analyzed tree.

Transformer creation part


from lark import Transformer

class mytransformer(Transformer):
    def __init__(self): #Initialize variables to be used as appropriate
        self.var1 = None
        self.var2 = []

    def sentence(self,tree): #If you take the second argument, you can use a tree deeper than sentence!
        print("sentence") # example

    def command(self,tree):
        print("command")

    def option(self,tree):
        print("option")

Processing such as ʻargandchunkis omitted. Sentence, command, ʻoption, etc. defined in mytransformer are called ** with depth-first priority. So in this example The processing is performed in the order of command-> ʻoption-> sentence`.

How to use the transformer

How to use the transformer


tree = LP.parse("rand -s3 a b c + say def | replace e E")
mytransformer().transform(tree)

Use it like this.

Finally

So far, I have briefly explained about Lark.

Since the beginners managed to do their best, I think there are some mistakes. If you find any mistakes, please leave a comment.

Recommended Posts

Lark Basics (Python, Lark to make a shell-like guy)
[Python] How to make a class iterable
I want to make a game with Python
Try to make a "cryptanalysis" cipher with Python
Try to make a dihedral group with Python
Try to make a Python module in C language
Try to make a command standby tool with python
How to make a Python package using VS Code
[Python] I want to make a nested list a tuple
Basics of PyTorch (2) -How to make a neural network-
A road to intermediate Python
Make a bookmarklet in Python
Make a fortune with Python
[Python] How to make a list of character strings character by character
Experiment to make a self-catering PDF for Kindle with Python
Python learning basics ~ How to output (display) a character string? ~
I tried to make a stopwatch using tkinter in python
I want to make input () a nice complement in python
How to make a Japanese-English translation
How to write a Python class
Let's make a GUI with python.
How to make a slack bot
How to make a crawler --Advanced
How to make a recursive function
python / Make a dict from a list.
[Python] Make the function a lambda function
Make a recommender system with python
How to make a deadman's switch
[Blender] How to make a Blender plugin
5 Ways to Create a Python Chatbot
How to make a crawler --Basic
[5th] I tried to make a certain authenticator-like tool with python
Rubyist tried to make a simple API with Python + bottle + MySQL
[2nd] I tried to make a certain authenticator-like tool with python
How to make a string into an array or an array into a string in Python
I tried to make a regular expression of "amount" using Python
[Python] I tried to implement stable sorting, so make a note
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
How to make a surveillance camera (Security Camera) with Opencv and Python
Try to make a web service-like guy with 3D markup language
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
Make a request from Device Farm (appium python) to API Gateway
Slack --APIGateway --Lambda (Python) --How to make a RedShift interactive app
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I tried to make a todo application using bottle with python
[Python] How to make a matrix of repeating patterns (repmat / tile)
2. Make a decision tree from 0 with Python and understand it (2. Python program basics)
Python basics ⑤
Python: I tried to make a flat / flat_map just right with a generator
Let's make a shiritori game with Python
Tips to make Python here-documents easier to read
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
[Python] How to convert a 2D list to a 1D list
Python basics ④
A super introduction to Python bit operations
Send a message from Python to Slack
Make a relation diagram of Python module
Try to make a capture software with as high accuracy as possible with python (2)
Fractal to make and play with Python