Skip to content

Commit c1ec78c

Browse files
committed
[UPDATE] Indent
1 parent 8e828b8 commit c1ec78c

File tree

8 files changed

+138
-32
lines changed

8 files changed

+138
-32
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
def validar_indentacion(codigo):
2+
indent_stack = [
3+
0
4+
] # Pila para los niveles de indentación, empezando en 0 (sin indentación)
5+
INDENT = None # Para guardar el tipo de indentación (tabs o espacios)
6+
line_number = 0 # Número de línea para propósitos de error
7+
8+
for linea in codigo.splitlines():
9+
line_number += 1
10+
11+
# Ignorar líneas vacías o comentarios
12+
if linea.strip() == "" or linea.strip().startswith("#"):
13+
continue
14+
15+
# Contar la indentación de la línea actual
16+
stripped_line = linea.lstrip() # Quitar los espacios o tabs al inicio
17+
indent_level = len(linea) - len(stripped_line)
18+
19+
# Detectar si es la primera vez que vemos una indentación
20+
if indent_level > 0 and INDENT is None:
21+
INDENT = linea[
22+
:indent_level
23+
] # Guardar el tipo de indentación (tabs o espacios)
24+
25+
# Validar que todas las líneas estén usando el mismo tipo de indentación
26+
if INDENT and not linea.startswith(INDENT * (indent_level // len(INDENT))):
27+
print(f"Error: mezcla de tipos de indentación en la línea {line_number}")
28+
return False
29+
30+
# Si la línea tiene menos indentación, verificar que coincida con la pila
31+
if indent_level < indent_stack[-1]:
32+
while indent_stack and indent_stack[-1] > indent_level:
33+
indent_stack.pop() # Reducir el nivel de indentación
34+
if indent_stack[-1] != indent_level:
35+
print(
36+
f"Error: nivel de indentación incorrecto en la línea {line_number}"
37+
)
38+
return False
39+
40+
# Si la línea tiene más indentación, agregar el nivel a la pila
41+
elif indent_level > indent_stack[-1]:
42+
indent_stack.append(indent_level)
43+
44+
print("Indentación correcta")
45+
return True
46+
47+
48+
# Ejemplo de uso
49+
codigo_python = """
50+
def ejemplo():
51+
if True:
52+
print("Indentado correctamente")
53+
print("Fin del bloque")
54+
"""
55+
56+
validar_indentacion(codigo_python)

src/main/java/ParserOperations/Assignments.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ public boolean isValueAssign() {
107107
} else if (tool.isAssignment(tool.getCurrentToken())) {
108108
tool.incrementIndex();
109109
if (tool.isValueToken(tool.getCurrentToken())) {
110-
System.out.println("VARIABLE AUGASSIGN");
110+
// System.out.println("VARIABLE AUGASSIGN");
111111
flag = true;
112112
tool.incrementIndex();
113113
} else {

src/main/java/ParserOperations/CompoundStatements.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ public boolean isCompoundStatement() {
1616
tool.setCurrentRow(tool.getCurrentToken().getRow());
1717
if (isFunctionDef() || isClassDeclaration() || isIfStatement() || isForStatement()
1818
|| isWhileStatement() || isMatchStatement() || isTryStatement()) {
19-
// tool.indent();
20-
// System.out.println(tool.getCurrentToken().getToken() + " - " + tool.getCurrentIndent());
19+
tool.indent();
20+
// System.out.println(tool.getCurrentToken().getToken() + " - " +
21+
// tool.getCurrentIndent());
2122
return true;
2223
} else {
2324
return false;

src/main/java/ParserOperations/Parser.java

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class Parser {
99
private Utilities tool;
1010
private CompoundStatements comp;
1111
private SimpleStatements simp;
12-
private boolean printFlag;
12+
public static boolean flag;
1313

1414
public Parser(ArrayList<Token> tokenList, JTextArea console) {
1515
tool = new Utilities();
@@ -23,35 +23,28 @@ public Parser(ArrayList<Token> tokenList, JTextArea console) {
2323
}
2424

2525
public void parseCode() {
26-
System.out.println("INDENTACION -> " + tool.getCurrentIndent());
27-
while (comp.isCompoundStatement()) {
28-
if (simp.isSimpleStatement()) {
29-
} else if (tool.getCurrentIndent() != tool.getCurrentToken().getColumn()) {
30-
tool.getConsole().setText(tool.getConsole().getText() + "Indentacion no valida en la linea "
31-
+ tool.getCurrentToken().getRow() + "\n");
32-
}
33-
tool.indent();
34-
parseCode();
35-
}
36-
tool.dedent();
37-
// if (tool.getCurrentIndent() == tool.getCurrentToken().getColumn()) {
38-
// tool.indent();
39-
// if (comp.isCompoundStatement()) {
40-
// if (simp.isSimpleStatement()) {
41-
// parseCode();
42-
// } else {
43-
// tool.dedent();
44-
// }
45-
// } // Fin de la ejecucion
46-
// } else if (simp.isSimpleStatement()) {
47-
// // No hay cambio en la indentacion.
48-
// } else {
49-
// tool.getConsole().setText(tool.getConsole().getText() + "Indentacion no
50-
// valida en la linea "
51-
// + tool.getCurrentToken().getRow() + "\n");
52-
// }
26+
System.out.println("\nEjecución");
27+
statements();
5328
}
5429

55-
public void statement() {
30+
public void statements() {
31+
System.out.println("INDENTACION -> " + tool.getCurrentIndent() + " - " + tool.getCurrentToken().getLexeme());
32+
33+
if (comp.isCompoundStatement() || simp.isSimpleStatement()) {
34+
if (flag) {
35+
if (tool.getCurrentToken().getColumn() <= tool.getCurrentIndent()) {
36+
flag = false;
37+
statements();
38+
}
39+
} else {
40+
if (tool.getCurrentToken().getColumn() != tool.getCurrentIndent()) {
41+
tool.getConsole().setText(tool.getConsole().getText() + "Indentacion no valida en la linea "
42+
+ tool.getCurrentToken().getRow() + "\n");
43+
} else {
44+
flag = true;
45+
statements();
46+
}
47+
}
48+
}
5649
}
5750
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
def validar_indentacion(codigo):
2+
indent_stack = [
3+
0
4+
] # Pila para los niveles de indentación, empezando en 0 (sin indentación)
5+
INDENT = None # Para guardar el tipo de indentación (tabs o espacios)
6+
line_number = 0 # Número de línea para propósitos de error
7+
8+
for linea in codigo.splitlines():
9+
line_number += 1
10+
11+
# Ignorar líneas vacías o comentarios
12+
if linea.strip() == "" or linea.strip().startswith("#"):
13+
continue
14+
15+
# Contar la indentación de la línea actual
16+
stripped_line = linea.lstrip() # Quitar los espacios o tabs al inicio
17+
indent_level = len(linea) - len(stripped_line)
18+
19+
# Detectar si es la primera vez que vemos una indentación
20+
if indent_level > 0 and INDENT is None:
21+
INDENT = linea[
22+
:indent_level
23+
] # Guardar el tipo de indentación (tabs o espacios)
24+
25+
# Validar que todas las líneas estén usando el mismo tipo de indentación
26+
if INDENT and not linea.startswith(INDENT * (indent_level // len(INDENT))):
27+
print(f"Error: mezcla de tipos de indentación en la línea {line_number}")
28+
return False
29+
30+
# Si la línea tiene menos indentación, verificar que coincida con la pila
31+
if indent_level < indent_stack[-1]:
32+
while indent_stack and indent_stack[-1] > indent_level:
33+
indent_stack.pop() # Reducir el nivel de indentación
34+
if indent_stack[-1] != indent_level:
35+
print(
36+
f"Error: nivel de indentación incorrecto en la línea {line_number}"
37+
)
38+
return False
39+
40+
# Si la línea tiene más indentación, agregar el nivel a la pila
41+
elif indent_level > indent_stack[-1]:
42+
indent_stack.append(indent_level)
43+
44+
print("Indentación correcta")
45+
return True
46+
47+
48+
# Ejemplo de uso
49+
codigo_python = """
50+
def ejemplo():
51+
if True:
52+
print("Indentado correctamente")
53+
print("Fin del bloque")
54+
"""
55+
56+
validar_indentacion(codigo_python)
-36 Bytes
Binary file not shown.
26 Bytes
Binary file not shown.
95 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)