Introducción al desarrollo de intérpretes y lenguajes de programación

1

Aprende a desarrollar lenguajes de programación con intérpretes

2

Desarrolla LPP o Lenguaje de Programación Platzi

Construcción del lexer o tokenizador

3

¿Qué es análisis léxico? Funcionamiento del lexer y tokens

4

Estructura y definición de tokens en Python

5

Lectura de caracteres y tokens

6

Tokens ilegales, operadores de un solo carácter y delimitadores

7

Reconocimiento y diferenciación entre letras y números

8

Declaración y ejecución de funciones

9

Extensión del lexer: condicionales, operaciones y booleanos

10

Operadores de dos caracteres

11

Primera versión del REPL con tokens

Construcción del parser o analizador sintáctico

12

¿Qué es un parser y AST?

13

Estructura y definición de nodos del AST en Python

14

Parseo del programa o nodo principal

15

Parseo de assignment statements

16

Parseo de let statements

17

Parseo de errores

18

Parseo del return statement

19

Técnicas de parsing y pratt parsing

20

Pruebas del AST

21

Implementación del pratt parser

22

Parseo de Identifiers: testing

23

Parseo de Identifiers: implementación

24

Parseo de enteros

25

Prefix operators: negación y negativos

26

Infix operators y orden de las operaciones: testing

27

Infix operators y orden de las operaciones: implementación

28

Parseo de booleanos

29

Desafío: testing de infix operators y booleanos

30

Parseo de expresiones agrupadas

31

Parseo de condicionales: testing y AST

32

Parseo de condicionales: implementación

33

Parseo de declaración de funciones: testing

34

Parseo de declaración de funciones: AST e implementación

35

Parseo de llamadas a funciones: testing y AST

36

Parseo de llamadas a funciones: implementación

37

Completando los TODOs o pendientes del lexer

38

Segunda versión del REPL con AST

Evaluación o análisis semántico

39

Significado de símbolos

40

Estrategias de evaluación para intérpretes de software

41

Representación de objetos

42

Evaluación de expresiones: enteros

43

Evaluación de expresiones: booleanos y nulos

44

Evaluación de expresiones: prefix

45

Evaluación de expresiones: infix

46

Evaluación de condicionales

47

Evaluación del return statement

48

Manejo de errores

49

Ambiente

50

Bindings

51

Evaluación de funciones

52

Llamadas a funciones

Mejora del intérprete

53

Implementación de strings

54

Operaciones con strings

55

Built-in functions: objeto y tests

56

Built-in functions: evaluación

Siguientes pasos

57

Retos para expandir tu intérprete

58

Continúa con el Curso de Creación de Compiladores de Software

Create an account or log in

Keep learning for free! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
17 Hrs
49 Min
52 Seg

Estructura y definición de tokens en Python

4/58
Resources

How to define the first tokens in a programming language?

Defining tokens is a crucial step in developing any programming language. In the case of the Platzi programming language (LPP), we will start by defining a subset that includes numbers, variables, identifiers, keywords and various special characters. These elements form the basis on which we will create our first tokens. We will learn how to generate a token.py file, where we will define two classes: token type and token itself. We will use enums to differentiate a list of finite values, and we will take advantage of typing 's namedtuple class to improve the definition of tokens.

What is the process to start defining tokens?

  1. Create a token.py file: This file will be the core of our definitions. We will start by importing the necessary modules.

    from enum import Enum, auto, uniquefrom typing import NamedTuple
  2. Define the TokenType class: We create a class containing the different types of tokens we will use.

    @uniqueclass TokenType(Enum): ASSIGN = auto() COMMA = auto() EOF = auto() # End of file FUNCTION = auto() IDENT = auto() # Identifier ILLEGAL = auto() INT = auto() LEFT_BRACE = auto() LET = auto() LEFT_PAREN = auto() PLUS = auto() RIGHT_BRACE = auto() RIGHT_PAREN = auto() SEMICOLON = auto()
  3. Create the Token class: We use NamedTuple to define the structure of our tokens.

    class Token(NamedTuple): token_type: TokenType literal: str
  4. Add additional methods: We integrate the special method __str__ to control how the token is printed.

    def __str__(self)-> str: return f "Type: {self.token_type}, Literal: {self.literal}"

How to prepare the development environment?

Before we start programming, we need to prepare our environment with Python 3.8. To do this, we will follow these steps:

  • Create a virtual environment: we make sure that all development work is isolated.

    python3.8 -m venv bnbsource bnb/bin/activate
  • Install the necessary dependencies: We will do it through the requirements.txt file that contains nose for tests and mypy for typing.

    pip3 install -r requirements.txt

How to manage version control with git?

It is essential to organize our project using git. We set up dedicated branches to divide the work and ensure the stability of our code base.

  1. Check the current branch: Use the main branch as a base.

    git branch
  2. Change or create a new branch:

    git checkout -b define-tokens.

Where to find additional resources and code summaries?

For ease of learning, full source code and other resources will be available on GitHub. Look for related information in the course comments or check the repository directly.

Remember, defining your own tokens and understanding their purpose is vital in the journey of building a programming language. Simplicity and clarity are allies throughout this process, so don't hesitate to review and practice. As we move forward, the concept of tokens and their implementation will become clearer. Keep going!

Contributions 8

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Genial! Todo entendido, sé que esto puede parecer obvio para los Python experts, pero en mi caso donde soy nuevo en Python, para poder usar venv tienen que instalarlo como un módulo de Python, sino dará un error que dice:
.
“The virtual environment was not created successfully because ensurepip is not
available.”
.
Para solucionarlo, simplemente lo instalan:

sudo apt-get install python3-venv

Y con eso queda listo 😄
.
Y algo genial es que acabo de aprender a tipar clases en Python xD Amo el tipado!

Curiosidad, el profe David llama a los métodos especiales ¨dunder¨ Methods. Pero, ¿por qué? por la forma de pronunciar init sería algo como underscore underscore init underscore underscore, o lo que es lo mismo Double underscore init Double underscore que por abreviatura sería algo como
Double underscore o lo que es lo mismo dunder Methods. Tomado de python-course.edu

esta terminal es mas facil de manipular los comandos en windows
https://cmder.net/

Clase TokenType

Clase Token con explicación

Diseño inicial

Para los que usan Windows.

1.-Instalar virtualenv–>pip install virtualenv
2.-Crear entorno virtual–>virtualenv -p python3 env
-------Para activar el entorno virtual ejecute en power shell–
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

3.- Activar el entorno virtual–>D:\Interpretes> .\venv\Scripts\activate

Tuve que implementar el método equals a Token para que los tests funcionen en la siguiente clase. ``` def \_\_eq\_\_(self, other): if not isinstance(other, Token): return False return self.type == other.type and self.literal == other.literal ```