Python3
200 subscribers
100 photos
6 videos
26 files
518 links
🎓 آموزش و پروژه‌های Python
آموزش‌های کاربردی و پروژه‌های عملی Python برای همه سطوح. 🚀
Download Telegram
ساخت یک مفسر ساده در پایتون 🚀

مرحله ۱: تعریف زبان برنامه‌نویسی 📜

ابتدا باید قواعد و دستورات زبان برنامه‌نویسی خودتون رو تعریف کنید. برای این آموزش، ما یک زبان ساده به نام "MiniLang" با دستورات پایه‌ای تعریف می‌کنیم:

1. دستور PRINT برای چاپ متن.
2. دستور SET برای تعریف متغیرها.
3. دستور ADD برای جمع کردن مقادیر.

مرحله ۲: نوشتن Lexer 🔍

Lexer یا تجزیه‌کننده لغوی، متن برنامه را به توکن‌ها (قطعات کوچکتر) تقسیم می‌کند.

import re

def lexer(code):
tokens = []
for line in code.splitlines():
line = line.strip()
if line:
if line.startswith("PRINT"):
tokens.append(("PRINT", line[6:]))
elif line.startswith("SET"):
match = re.match(r"SET (\w+) (.+)", line)
if match:
tokens.append(("SET", match.group(1), match.group(2)))
elif line.startswith("ADD"):
match = re.match(r"ADD (\w+) (\w+)", line)
if match:
tokens.append(("ADD", match.group(1), match.group(2)))
return tokens

مرحله ۳: نوشتن Parser 🔍

Parser یا تجزیه‌کننده نحوی، توکن‌ها را به دستورات قابل اجرا تبدیل می‌کند.

def parser(tokens):
commands = []
for token in tokens:
if token[0] == "PRINT":
commands.append(("PRINT", token[1]))
elif token[0] == "SET":
commands.append(("SET", token[1], token[2]))
elif token[0] == "ADD":
commands.append(("ADD", token[1], token[2]))
return commands

مرحله ۴: اجرای دستورات 🏃‍♂️

Interpreter یا مفسر، دستورات را اجرا می‌کند.

def interpreter(commands):
variables = {}
for command in commands:
if command[0] == "PRINT":
print(command[1])
elif command[0] == "SET":
variables[command[1]] = eval(command[2], {}, variables)
elif command[0] == "ADD":
if command[1] in variables and command[2] in variables:
variables[command[1]] += variables[command[2]]
return variables

مرحله ۵: استفاده از مفسر 📟

حالا کد کامل برای مفسر خودمون رو داریم. می‌تونیم یک برنامه MiniLang رو اجرا کنیم.

code = """
SET x 5
SET y 10
ADD x y
PRINT x
"""

tokens = lexer(code)
commands = parser(tokens)
interpreter(commands)

این کد مقدار ۱۵ را چاپ خواهد کرد چون ابتدا مقدار ۵ به متغیر x و مقدار ۱۰ به متغیر y اختصاص داده شده و سپس این دو مقدار با هم جمع شده و نتیجه چاپ می‌شود.

[آموزش ساخت مفسر]

#Python #Programming #CodingTips #LearnPython #Interpreter #MiniLang
👍2