Repository navigation
Expand file tree
/
Copy pathinterprete.go
More file actions
331 lines (297 loc) · 8.02 KB
/
Copy pathinterprete.go
File metadata and controls
331 lines (297 loc) · 8.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main
// Memoria, entorno y estado del interprete.
import (
"bufio"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
const limiteLlamadas = 3000
// Memoria
type Memoria struct {
datos map[string]Valor
padre *Memoria
esFuncion bool
compartidas map[string]bool
}
func nuevaMemoria(padre *Memoria, esFuncion bool) *Memoria {
return &Memoria{datos: map[string]Valor{}, padre: padre, esFuncion: esFuncion}
}
func (m *Memoria) existe(n string) bool {
for l := m; l != nil; l = l.padre {
if _, hay := l.datos[n]; hay {
return true
}
}
return false
}
func (m *Memoria) leer(n string) (Valor, bool) {
for l := m; l != nil; l = l.padre {
if v, hay := l.datos[n]; hay {
return v, true
}
}
return nil, false
}
func (m *Memoria) raiz() *Memoria {
l := m
for l.padre != nil {
l = l.padre
}
return l
}
func (m *Memoria) declararCompartida(n string) {
if m.compartidas == nil {
m.compartidas = map[string]bool{}
}
m.compartidas[n] = true
}
// guardar deja lo que escribes DENTRO de la funcion donde estas, salvo que
// hayas dicho "comparte". Sin esto, una funcion podria pisar las variables
// de fuera sin avisar, que es el peor tipo de error: el que no se ve.
func (m *Memoria) guardar(n string, v Valor) {
if m.compartidas[n] {
for l := m.padre; l != nil; l = l.padre {
if _, hay := l.datos[n]; hay {
l.datos[n] = v
return
}
}
m.raiz().datos[n] = v
return
}
for l := m; l != nil; l = l.padre {
if _, hay := l.datos[n]; hay {
l.datos[n] = v
return
}
if l.esFuncion {
break
}
}
m.datos[n] = v
}
func (m *Memoria) nombres() []string {
vistos := map[string]bool{}
var salida []string
for l := m; l != nil; l = l.padre {
for n := range l.datos {
if !vistos[n] {
vistos[n] = true
salida = append(salida, n)
}
}
}
return salida
}
// Salida es a donde escribe el programa. En el escritorio y en las pruebas
// es un bufio.Writer de toda la vida. En el navegador es algo que manda cada
// trozo a la pagina segun se escribe, para que se vea en vivo y no de golpe
// al terminar.
type Salida interface {
WriteString(string) (int, error)
Flush() error
}
// Señales de control (no son errores)
type senal int
const (
sigNada senal = iota
sigDetente
sigContinua
sigDevuelve
)
type resultado struct {
sig senal
valor Valor
}
var seguir = resultado{}
// El interprete
type Interprete struct {
global *Memoria
funciones map[string]*Funcion
tipos map[string]*Tipo
carpeta string
argumentos []string
cargados map[string]Valor
pila []Marco
// Tope de tiempo. En el navegador hace falta: sin el, un bucle sin
// salida colgaria la pestaña. Con la hora a cero no se comprueba nada,
// que es como corre en el escritorio.
limite time.Time
pasos int
tipoError *Tipo
salida Salida
entrada *bufio.Reader
tortuga *Tortuga
// teclado dice si "tecla" le pregunta al teclado de verdad. Cuando esta
// apagado, las pulsaciones se sacan del mismo texto que lee "pregunta".
// Eso es lo que permite escribir una partida de antemano y repetirla
// igual, y sin ello un juego no habria forma de probarlo.
teclado bool
}
// conEntrada cambia de donde lee el programa, y de paso apaga el teclado: si
// el texto se lo estamos dando nosotros, las teclas tienen que salir de ahi
// tambien y no del teclado de quien haya lanzado esto.
func (in *Interprete) conEntrada(r io.Reader) {
in.entrada = bufio.NewReader(r)
in.teclado = false
}
func nuevoInterprete(carpeta string, args []string) *Interprete {
in := &Interprete{
global: nuevaMemoria(nil, false),
funciones: map[string]*Funcion{},
tipos: map[string]*Tipo{},
carpeta: carpeta,
argumentos: args,
cargados: map[string]Valor{},
salida: bufio.NewWriter(os.Stdout),
entrada: bufio.NewReader(os.Stdin),
tortuga: nuevaTortuga(),
teclado: hayTecladoDeVerdad(),
}
in.tipoError = &Tipo{Nombre: "Error", Propios: []string{"mensaje", "clase", "linea", "pista"},
Metodos: map[string]*Funcion{}, EsError: true}
in.tipos["error"] = in.tipoError
// pi y e con muchos decimales, guardados como fraccion exacta.
pi, _ := NumDesdeTexto("3.14159265358979323846")
e, _ := NumDesdeTexto("2.71828182845904523536")
in.global.datos["pi"] = pi
in.global.datos["e"] = e
interpreteActual = in
return in
}
func (in *Interprete) rutaDe(r string) string {
if filepath.IsAbs(r) {
return r
}
return filepath.Join(in.carpeta, r)
}
// escribir manda el texto y su salto de linea de una sola vez. En el
// navegador cada escritura es un mensaje que cruza del worker a la pagina,
// asi que mandarlos por separado costaba el doble de mensajes para nada.
func (in *Interprete) escribir(s string, salto bool) {
if salto {
s += "\n"
}
in.salida.WriteString(s)
}
func (in *Interprete) preguntar(mensaje string) (string, bool) {
in.salida.WriteString(mensaje)
in.salida.Flush()
linea, err := in.entrada.ReadString('\n')
if err != nil && linea == "" {
return "", false
}
return strings.TrimRight(linea, "\r\n"), true
}
func (in *Interprete) correr(instrucciones []Instruccion) *ErrorFal {
if err := in.registrar(instrucciones); err != nil {
return err
}
for _, ins := range instrucciones {
switch ins.(type) {
case *InsFuncion, *InsTipo:
continue
}
if _, err := in.ejecutar(ins, in.global); err != nil {
return err
}
}
return nil
}
// registrar apunta funciones y tipos antes de empezar, para poder usarlos
// desde arriba del archivo aunque esten definidos mas abajo.
func (in *Interprete) registrar(instrucciones []Instruccion) *ErrorFal {
for _, ins := range instrucciones {
switch x := ins.(type) {
case *InsFuncion:
in.funciones[x.Nombre] = &Funcion{Nombre: x.Nombre, Parametros: x.Parametros,
Cuerpo: x.Cuerpo, Entorno: in.global}
case *InsTipo:
metodos := map[string]*Funcion{}
for _, m := range x.Metodos {
metodos[m.Nombre] = &Funcion{Nombre: m.Nombre, Parametros: m.Parametros,
Cuerpo: m.Cuerpo, Entorno: in.global}
}
var madre *Tipo
if x.Madre != "" {
m, hay := in.tipos[x.Madre]
if !hay {
return nuevoError(`No conozco ningun tipo llamado "`+x.Madre+`" para heredar.`,
x.Ln, sugerirDeMapaTipos(x.Madre, in.tipos), ClaseNombre)
}
madre = m
}
in.tipos[x.Nombre] = &Tipo{Nombre: x.Escrito, Propios: x.Campos,
Metodos: metodos, Madre: madre}
}
}
return nil
}
func (in *Interprete) ejecutarBloque(cuerpo []Instruccion, mem *Memoria) (resultado, *ErrorFal) {
for _, ins := range cuerpo {
r, err := in.ejecutar(ins, mem)
if err != nil {
return seguir, err
}
if r.sig != sigNada {
return r, nil
}
}
return seguir, nil
}
// sinTiempo corta los bucles eternos. Mirar el reloj en cada vuelta
// costaria caro, asi que solo se comprueba de vez en cuando.
func (in *Interprete) sinTiempo(ln int) *ErrorFal {
if in.limite.IsZero() {
return nil
}
in.pasos++
if in.pasos%2048 != 0 {
return nil
}
if time.Now().After(in.limite) {
return nuevoError("El programa lleva demasiado rato dando vueltas.", ln,
"Comprueba que el bucle tenga forma de terminar.", ClaseLimite)
}
return nil
}
// bucle ejecuta el cuerpo y dice si hay que seguir dando vueltas.
func (in *Interprete) bucle(cuerpo []Instruccion, mem *Memoria) (bool, resultado, *ErrorFal) {
if err := in.sinTiempo(0); err != nil {
return false, seguir, err
}
r, err := in.ejecutarBloque(cuerpo, mem)
if err != nil {
return false, seguir, err
}
switch r.sig {
case sigDetente:
return false, seguir, nil
case sigDevuelve:
return false, r, nil
}
return true, seguir, nil
}
func (in *Interprete) objetoError(e *ErrorFal) *Objeto {
o := &Objeto{Tipo: in.tipoError, Campos: map[string]Valor{}}
o.Pon("mensaje", e.Mensaje)
o.Pon("clase", string(e.Clase))
o.Pon("linea", Entero(int64(e.Linea)))
o.Pon("pista", e.Pista)
return o
}
func sugerirDeMapaTipos(nombre string, tipos map[string]*Tipo) string {
var claves []string
for k := range tipos {
claves = append(claves, k)
}
sort.Strings(claves)
if s := sugerir(nombre, claves); s != "" {
return s
}
return "El tipo del que se hereda tiene que estar definido antes."
}