summary refs log tree commit diff stats
path: root/compiler/lookups.nim
blob: 962c28613c5b738d522811b026b1aa4156cf9cee (plain) (blame)
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#
#
#           The Nim Compiler
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# This module implements lookup helpers.

import
  intsets, ast, astalgo, idents, semdata, types, msgs, options, rodread,
  renderer, wordrecg, idgen, nimfix.prettybase

proc ensureNoMissingOrUnusedSymbols(scope: PScope)

proc considerQuotedIdent*(n: PNode): PIdent =
  ## Retrieve a PIdent from a PNode, taking into account accent nodes.
  case n.kind
  of nkIdent: result = n.ident
  of nkSym: result = n.sym.name
  of nkAccQuoted:
    case n.len
    of 0:
      localError(n.info, errIdentifierExpected, renderTree(n))
      result = getIdent"<Error>"
    of 1: result = considerQuotedIdent(n.sons[0])
    else:
      var id = ""
      for i in 0.. <n.len:
        let x = n.sons[i]
        case x.kind
        of nkIdent: id.add(x.ident.s)
        of nkSym: id.add(x.sym.name.s)
        else:
          localError(n.info, errIdentifierExpected, renderTree(n))
          return getIdent"<Error>"
      result = getIdent(id)
  of nkOpenSymChoice, nkClosedSymChoice: result = n.sons[0].sym.name
  else:
    localError(n.info, errIdentifierExpected, renderTree(n))
    result = getIdent"<Error>"

template addSym*(scope: PScope, s: PSym) =
  strTableAdd(scope.symbols, s)

proc addUniqueSym*(scope: PScope, s: PSym): bool =
  result = not strTableIncl(scope.symbols, s)

proc openScope*(c: PContext): PScope {.discardable.} =
  result = PScope(parent: c.currentScope,
                  symbols: newStrTable(),
                  depthLevel: c.scopeDepth + 1)
  c.currentScope = result

proc rawCloseScope*(c: PContext) =
  c.currentScope = c.currentScope.parent

proc closeScope*(c: PContext) =
  ensureNoMissingOrUnusedSymbols(c.currentScope)
  rawCloseScope(c)

iterator walkScopes*(scope: PScope): PScope =
  var current = scope
  while current != nil:
    yield current
    current = current.parent

proc skipAlias*(s: PSym; n: PNode): PSym =
  if s == nil or s.kind != skAlias:
    result = s
  else:
    result = s.owner
    if gCmd == cmdPretty:
      prettybase.replaceDeprecated(n.info, s, result)
    else:
      message(n.info, warnDeprecated, "use " & result.name.s & " instead; " &
              s.name.s)

proc localSearchInScope*(c: PContext, s: PIdent): PSym =
  result = strTableGet(c.currentScope.symbols, s)

proc searchInScopes*(c: PContext, s: PIdent): PSym =
  for scope in walkScopes(c.currentScope):
    result = strTableGet(scope.symbols, s)
    if result != nil: return
  result = nil

proc debugScopes*(c: PContext; limit=0) {.deprecated.} =
  var i = 0
  for scope in walkScopes(c.currentScope):
    echo "scope ", i
    for h in 0 .. high(scope.symbols.data):
      if scope.symbols.data[h] != nil:
        echo scope.symbols.data[h].name.s
    if i == limit: break
    inc i

proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym =
  for scope in walkScopes(c.currentScope):
    result = strTableGet(scope.symbols, s)
    if result != nil and result.kind in filter: return
  result = nil

proc errorSym*(c: PContext, n: PNode): PSym =
  ## creates an error symbol to avoid cascading errors (for IDE support)
  var m = n
  # ensure that 'considerQuotedIdent' can't fail:
  if m.kind == nkDotExpr: m = m.sons[1]
  let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}:
      considerQuotedIdent(m)
    else:
      getIdent("err:" & renderTree(m))
  result = newSym(skError, ident, getCurrOwner(), n.info)
  result.typ = errorType(c)
  incl(result.flags, sfDiscardable)
  # pretend it's imported from some unknown module to prevent cascading errors:
  if gCmd != cmdInteractive and c.compilesContextId == 0:
    c.importTable.addSym(result)

type
  TOverloadIterMode* = enum
    oimDone, oimNoQualifier, oimSelfModule, oimOtherModule, oimSymChoice,
    oimSymChoiceLocalLookup
  TOverloadIter*{.final.} = object
    it*: TIdentIter
    m*: PSym
    mode*: TOverloadIterMode
    symChoiceIndex*: int
    scope*: PScope
    inSymChoice: IntSet

proc getSymRepr*(s: PSym): string =
  case s.kind
  of skProc, skMethod, skConverter, skIterator: result = getProcHeader(s)
  else: result = s.name.s

proc ensureNoMissingOrUnusedSymbols(scope: PScope) =
  # check if all symbols have been used and defined:
  var it: TTabIter
  var s = initTabIter(it, scope.symbols)
  var missingImpls = 0
  while s != nil:
    if sfForward in s.flags:
      # too many 'implementation of X' errors are annoying
      # and slow 'suggest' down:
      if missingImpls == 0:
        localError(s.info, errImplOfXexpected, getSymRepr(s))
      inc missingImpls
    elif {sfUsed, sfExported} * s.flags == {} and optHints in s.options:
      # BUGFIX: check options in s!
      if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam}:
        # XXX: implicit type params are currently skTypes
        # maybe they can be made skGenericParam as well.
        if s.typ != nil and tfImplicitTypeParam notin s.typ.flags:
          message(s.info, hintXDeclaredButNotUsed, getSymRepr(s))
    s = nextIter(it, scope.symbols)

proc wrongRedefinition*(info: TLineInfo, s: string) =
  if gCmd != cmdInteractive:
    localError(info, errAttemptToRedefine, s)

proc addDecl*(c: PContext, sym: PSym) =
  if not c.currentScope.addUniqueSym(sym):
    wrongRedefinition(sym.info, sym.name.s)

proc addPrelimDecl*(c: PContext, sym: PSym) =
  discard c.currentScope.addUniqueSym(sym)

proc addDeclAt*(scope: PScope, sym: PSym) =
  if not scope.addUniqueSym(sym):
    wrongRedefinition(sym.info, sym.name.s)

proc addInterfaceDeclAux(c: PContext, sym: PSym) =
  if sfExported in sym.flags:
    # add to interface:
    if c.module != nil: strTableAdd(c.module.tab, sym)
    else: internalError(sym.info, "addInterfaceDeclAux")

proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) =
  addDeclAt(scope, sym)
  addInterfaceDeclAux(c, sym)

proc addOverloadableSymAt*(scope: PScope, fn: PSym) =
  if fn.kind notin OverloadableSyms:
    internalError(fn.info, "addOverloadableSymAt")
    return
  let check = strTableGet(scope.symbols, fn.name)
  if check != nil and check.kind notin OverloadableSyms:
    wrongRedefinition(fn.info, fn.name.s)
  else:
    scope.addSym(fn)

proc addInterfaceDecl*(c: PContext, sym: PSym) =
  # it adds the symbol to the interface if appropriate
  addDecl(c, sym)
  addInterfaceDeclAux(c, sym)

proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) =
  # it adds the symbol to the interface if appropriate
  addOverloadableSymAt(scope, sym)
  addInterfaceDeclAux(c, sym)

when defined(nimfix):
  import strutils

  # when we cannot find the identifier, retry with a changed identifer:
  proc altSpelling(x: PIdent): PIdent =
    case x.s[0]
    of 'A'..'Z': result = getIdent(toLower(x.s[0]) & x.s.substr(1))
    of 'a'..'z': result = getIdent(toLower(x.s[0]) & x.s.substr(1))
    else: result = x

  template fixSpelling(n: PNode; ident: PIdent; op: expr) =
    let alt = ident.altSpelling
    result = op(c, alt).skipAlias(n)
    if result != nil:
      prettybase.replaceDeprecated(n.info, ident, alt)
      return result
else:
  template fixSpelling(n: PNode; ident: PIdent; op: expr) = discard

proc errorUseQualifier*(c: PContext; info: TLineInfo; s: PSym) =
  var err = "Error: ambiguous identifier: '" & s.name.s & "'"
  var ti: TIdentIter
  var candidate = initIdentIter(ti, c.importTable.symbols, s.name)
  var i = 0
  while candidate != nil:
    if i == 0: err.add " --use "
    else: err.add " or "
    err.add candidate.owner.name.s & "." & candidate.name.s
    candidate = nextIdentIter(ti, c.importTable.symbols)
    inc i
  localError(info, errGenerated, err)

proc lookUp*(c: PContext, n: PNode): PSym =
  # Looks up a symbol. Generates an error in case of nil.
  case n.kind
  of nkIdent:
    result = searchInScopes(c, n.ident).skipAlias(n)
    if result == nil:
      fixSpelling(n, n.ident, searchInScopes)
      localError(n.info, errUndeclaredIdentifier, n.ident.s)
      result = errorSym(c, n)
  of nkSym:
    result = n.sym
  of nkAccQuoted:
    var ident = considerQuotedIdent(n)
    result = searchInScopes(c, ident).skipAlias(n)
    if result == nil:
      fixSpelling(n, ident, searchInScopes)
      localError(n.info, errUndeclaredIdentifier, ident.s)
      result = errorSym(c, n)
  else:
    internalError(n.info, "lookUp")
    return
  if contains(c.ambiguousSymbols, result.id):
    errorUseQualifier(c, n.info, result)
  if result.kind == skStub: loadStub(result)

type
  TLookupFlag* = enum
    checkAmbiguity, checkUndeclared

proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym =
  case n.kind
  of nkIdent, nkAccQuoted:
    var ident = considerQuotedIdent(n)
    result = searchInScopes(c, ident).skipAlias(n)
    if result == nil and checkUndeclared in flags:
      fixSpelling(n, ident, searchInScopes)
      localError(n.info, errUndeclaredIdentifier, ident.s)
      result = errorSym(c, n)
    elif checkAmbiguity in flags and result != nil and
        contains(c.ambiguousSymbols, result.id):
      errorUseQualifier(c, n.info, result)
  of nkSym:
    result = n.sym
    if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id):
      errorUseQualifier(c, n.info, n.sym)
  of nkDotExpr:
    result = nil
    var m = qualifiedLookUp(c, n.sons[0], flags*{checkUndeclared})
    if m != nil and m.kind == skModule:
      var ident: PIdent = nil
      if n.sons[1].kind == nkIdent:
        ident = n.sons[1].ident
      elif n.sons[1].kind == nkAccQuoted:
        ident = considerQuotedIdent(n.sons[1])
      if ident != nil:
        if m == c.module:
          result = strTableGet(c.topLevelScope.symbols, ident).skipAlias(n)
        else:
          result = strTableGet(m.tab, ident).skipAlias(n)
        if result == nil and checkUndeclared in flags:
          fixSpelling(n.sons[1], ident, searchInScopes)
          localError(n.sons[1].info, errUndeclaredIdentifier, ident.s)
          result = errorSym(c, n.sons[1])
      elif n.sons[1].kind == nkSym:
        result = n.sons[1].sym
      elif checkUndeclared in flags and
           n.sons[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}:
        localError(n.sons[1].info, errIdentifierExpected,
                   renderTree(n.sons[1]))
        result = errorSym(c, n.sons[1])
  else:
    result = nil
  if result != nil and result.kind == skStub: loadStub(result)

proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  case n.kind
  of nkIdent, nkAccQuoted:
    var ident = considerQuotedIdent(n)
    o.scope = c.currentScope
    o.mode = oimNoQualifier
    while true:
      result = initIdentIter(o.it, o.scope.symbols, ident).skipAlias(n)
      if result != nil:
        break
      else:
        o.scope = o.scope.parent
        if o.scope == nil: break
  of nkSym:
    result = n.sym
    o.mode = oimDone
  of nkDotExpr:
    o.mode = oimOtherModule
    o.m = qualifiedLookUp(c, n.sons[0])
    if o.m != nil and o.m.kind == skModule:
      var ident: PIdent = nil
      if n.sons[1].kind == nkIdent:
        ident = n.sons[1].ident
      elif n.sons[1].kind == nkAccQuoted:
        ident = considerQuotedIdent(n.sons[1])
      if ident != nil:
        if o.m == c.module:
          # a module may access its private members:
          result = initIdentIter(o.it, c.topLevelScope.symbols,
                                 ident).skipAlias(n)
          o.mode = oimSelfModule
        else:
          result = initIdentIter(o.it, o.m.tab, ident).skipAlias(n)
      else:
        localError(n.sons[1].info, errIdentifierExpected,
                   renderTree(n.sons[1]))
        result = errorSym(c, n.sons[1])
  of nkClosedSymChoice, nkOpenSymChoice:
    o.mode = oimSymChoice
    result = n.sons[0].sym
    o.symChoiceIndex = 1
    o.inSymChoice = initIntSet()
    incl(o.inSymChoice, result.id)
  else: discard
  if result != nil and result.kind == skStub: loadStub(result)

proc lastOverloadScope*(o: TOverloadIter): int =
  case o.mode
  of oimNoQualifier: result = if o.scope.isNil: -1 else: o.scope.depthLevel
  of oimSelfModule:  result = 1
  of oimOtherModule: result = 0
  else: result = -1

proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym =
  case o.mode
  of oimDone:
    result = nil
  of oimNoQualifier:
    if o.scope != nil:
      result = nextIdentIter(o.it, o.scope.symbols).skipAlias(n)
      while result == nil:
        o.scope = o.scope.parent
        if o.scope == nil: break
        result = initIdentIter(o.it, o.scope.symbols, o.it.name).skipAlias(n)
        # BUGFIX: o.it.name <-> n.ident
    else:
      result = nil
  of oimSelfModule:
    result = nextIdentIter(o.it, c.topLevelScope.symbols).skipAlias(n)
  of oimOtherModule:
    result = nextIdentIter(o.it, o.m.tab).skipAlias(n)
  of oimSymChoice:
    if o.symChoiceIndex < sonsLen(n):
      result = n.sons[o.symChoiceIndex].sym
      incl(o.inSymChoice, result.id)
      inc o.symChoiceIndex
    elif n.kind == nkOpenSymChoice:
      # try 'local' symbols too for Koenig's lookup:
      o.mode = oimSymChoiceLocalLookup
      o.scope = c.currentScope
      result = firstIdentExcluding(o.it, o.scope.symbols,
                                   n.sons[0].sym.name, o.inSymChoice).skipAlias(n)
      while result == nil:
        o.scope = o.scope.parent
        if o.scope == nil: break
        result = firstIdentExcluding(o.it, o.scope.symbols,
                                     n.sons[0].sym.name, o.inSymChoice).skipAlias(n)
  of oimSymChoiceLocalLookup:
    result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice).skipAlias(n)
    while result == nil:
      o.scope = o.scope.parent
      if o.scope == nil: break
      result = firstIdentExcluding(o.it, o.scope.symbols,
                                   n.sons[0].sym.name, o.inSymChoice).skipAlias(n)

  if result != nil and result.kind == skStub: loadStub(result)

proc pickSym*(c: PContext, n: PNode; kind: TSymKind;
              flags: TSymFlags = {}): PSym =
  var o: TOverloadIter
  var a = initOverloadIter(o, c, n)
  while a != nil:
    if a.kind == kind and flags <= a.flags:
      return a
    a = nextOverloadIter(o, c, n)
="o">:number <- get *editor, left:offset right:number <- get *editor, right:offset row:number, column:number <- render screen, editor clear-line-until screen, right row <- add row, 1 draw-horizontal screen, row, left, right, 9480/horizontal-dotted row <- add row, 1 clear-screen-from screen, row, left, left, right ] scenario editor-handles-empty-event-queue [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data assume-console [] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abc . .┈┈┈┈┈┈┈┈┈┈. . . ] ] scenario editor-handles-mouse-clicks [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 1, 1 # on the 'b' ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] screen-should-contain [ . . .abc . .┈┈┈┈┈┈┈┈┈┈. . . ] memory-should-contain [ 3 <- 1 # cursor is at row 0.. 4 <- 1 # ..and column 1 ] check-trace-count-for-label 0, [print-character] ] scenario editor-handles-mouse-clicks-outside-text [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right $clear-trace assume-console [ left-click 1, 7 # last line, to the right of text ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] memory-should-contain [ 3 <- 1 # cursor row 4 <- 3 # cursor column ] check-trace-count-for-label 0, [print-character] ] scenario editor-handles-mouse-clicks-outside-text-2 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc def] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right $clear-trace assume-console [ left-click 1, 7 # interior line, to the right of text ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] memory-should-contain [ 3 <- 1 # cursor row 4 <- 3 # cursor column ] check-trace-count-for-label 0, [print-character] ] scenario editor-handles-mouse-clicks-outside-text-3 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc def] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right $clear-trace assume-console [ left-click 3, 7 # below text ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] memory-should-contain [ 3 <- 2 # cursor row 4 <- 3 # cursor column ] check-trace-count-for-label 0, [print-character] ] scenario editor-handles-mouse-clicks-outside-column [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] # editor occupies only left half of screen 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ # click on right half of screen left-click 3, 8 ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] screen-should-contain [ . . .abc . .┈┈┈┈┈ . . . ] memory-should-contain [ 3 <- 1 # no change to cursor row 4 <- 0 # ..or column ] check-trace-count-for-label 0, [print-character] ] scenario editor-handles-mouse-clicks-in-menu-area [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ # click on first, 'menu' row left-click 0, 3 ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] # no change to cursor memory-should-contain [ 3 <- 1 4 <- 0 ] ] scenario editor-inserts-characters-into-empty-editor [ assume-screen 10/width, 5/height 1:address:array:character <- new [] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ type [abc] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abc . .┈┈┈┈┈ . . . ] check-trace-count-for-label 3, [print-character] ] scenario editor-inserts-characters-at-cursor [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace # type two letters at different places assume-console [ type [0] left-click 1, 2 type [d] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .0adbc . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 7, [print-character] # 4 for first letter, 3 for second ] scenario editor-inserts-characters-at-cursor-2 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 1, 5 # right of last line type [d] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abcd . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 1, [print-character] ] scenario editor-inserts-characters-at-cursor-5 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc d] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 1, 5 # right of non-last line type [e] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abce . .d . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 1, [print-character] ] scenario editor-inserts-characters-at-cursor-3 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 3, 5 # below all text type [d] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abcd . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 1, [print-character] ] scenario editor-inserts-characters-at-cursor-4 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc d] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 3, 5 # below all text type [e] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abc . .de . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 1, [print-character] ] scenario editor-inserts-characters-at-cursor-6 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc d] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right editor-render screen, 2:address:editor-data $clear-trace assume-console [ left-click 3, 5 # below all text type [ef] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .abc . .def . .┈┈┈┈┈┈┈┈┈┈. . . ] check-trace-count-for-label 2, [print-character] ] scenario editor-moves-cursor-after-inserting-characters [ assume-screen 10/width, 5/height 1:address:array:character <- new [ab] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data assume-console [ type [01] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .01ab . .┈┈┈┈┈ . . . ] ] # if the cursor reaches the right margin, wrap the line scenario editor-wraps-line-on-insert [ assume-screen 5/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data # type a letter assume-console [ type [e] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] # no wrap yet screen-should-contain [ . . .eabc . .┈┈┈┈┈. . . . . ] # type a second letter assume-console [ type [f] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] # now wrap screen-should-contain [ . . .efab. .c . .┈┈┈┈┈. . . ] ] scenario editor-wraps-line-on-insert-2 [ # create an editor with some text assume-screen 10/width, 5/height 1:address:array:character <- new [abcdefg defg] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right editor-render screen, 2:address:editor-data # type more text at the start assume-console [ left-click 3, 0 type [abc] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] # cursor is not wrapped memory-should-contain [ 3 <- 3 4 <- 3 ] # but line is wrapped screen-should-contain [ . . .abcd . .efg . .abcd . .efg . ] ] after <insert-character-special-case> [ # if the line wraps at the cursor, move cursor to start of next row { # if we're at the column just before the wrap indicator wrap-column:number <- subtract right, 1 at-wrap?:boolean <- greater-or-equal cursor-column, wrap-column break-unless at-wrap? cursor-column <- subtract cursor-column, wrap-column cursor-column <- add cursor-column, left *editor <- put *editor, cursor-column:offset, cursor-column cursor-row <- add cursor-row, 1 *editor <- put *editor, cursor-row:offset, cursor-row # if we're out of the screen, scroll down { below-screen?:boolean <- greater-or-equal cursor-row, screen-height break-unless below-screen? } go-render? <- copy 1/true return } ] scenario editor-wraps-cursor-after-inserting-characters [ assume-screen 10/width, 5/height 1:address:array:character <- new [abcde] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right assume-console [ left-click 1, 4 # line is full; no wrap icon yet type [f] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] screen-should-contain [ . . .abcd . .fe . .┈┈┈┈┈ . . . ] memory-should-contain [ 3 <- 2 # cursor row 4 <- 1 # cursor column ] ] scenario editor-wraps-cursor-after-inserting-characters-2 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abcde] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right assume-console [ left-click 1, 3 # right before the wrap icon type [f] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] screen-should-contain [ . . .abcf . .de . .┈┈┈┈┈ . . . ] memory-should-contain [ 3 <- 2 # cursor row 4 <- 0 # cursor column ] ] scenario editor-wraps-cursor-to-left-margin [ assume-screen 10/width, 5/height 1:address:array:character <- new [abcde] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 2/left, 7/right assume-console [ left-click 1, 5 # line is full; no wrap icon yet type [01] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] screen-should-contain [ . . . abc0 . . 1de . . ┈┈┈┈┈ . . . ] memory-should-contain [ 3 <- 2 # cursor row 4 <- 3 # cursor column ] ] # if newline, move cursor to start of next line, and maybe align indent with previous line container editor-data [ indent?:boolean ] after <editor-initialization> [ *result <- put *result, indent?:offset, 1/true ] scenario editor-moves-cursor-down-after-inserting-newline [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right assume-console [ type [0 1] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . .0 . .1abc . .┈┈┈┈┈┈┈┈┈┈. . . ] ] after <handle-special-character> [ { newline?:boolean <- equal c, 10/newline break-unless newline? <insert-enter-begin> editor <- insert-new-line-and-indent editor, screen <insert-enter-end> go-render? <- copy 1/true return } ] def insert-new-line-and-indent editor:address:editor-data, screen:address:screen -> editor:address:editor-data, screen:address:screen, go-render?:boolean [ local-scope load-ingredients cursor-row:number <- get *editor, cursor-row:offset cursor-column:number <- get *editor, cursor-column:offset before-cursor:address:duplex-list:character <- get *editor, before-cursor:offset left:number <- get *editor, left:offset right:number <- get *editor, right:offset screen-height:number <- screen-height screen # insert newline insert 10/newline, before-cursor before-cursor <- next before-cursor *editor <- put *editor, before-cursor:offset, before-cursor cursor-row <- add cursor-row, 1 *editor <- put *editor, cursor-row:offset, cursor-row cursor-column <- copy left *editor <- put *editor, cursor-column:offset, cursor-column # maybe scroll { below-screen?:boolean <- greater-or-equal cursor-row, screen-height # must be equal, never greater break-unless below-screen? go-render? <- copy 1/true cursor-row <- subtract cursor-row, 1 # bring back into screen range *editor <- put *editor, cursor-row:offset, cursor-row } # indent if necessary indent?:boolean <- get *editor, indent?:offset return-unless indent? d:address:duplex-list:character <- get *editor, data:offset end-of-previous-line:address:duplex-list:character <- prev before-cursor indent:number <- line-indent end-of-previous-line, d i:number <- copy 0 { indent-done?:boolean <- greater-or-equal i, indent break-if indent-done? editor, screen, go-render?:boolean <- insert-at-cursor editor, 32/space, screen i <- add i, 1 loop } ] # takes a pointer 'curr' into the doubly-linked list and its sentinel, counts # the number of spaces at the start of the line containing 'curr'. def line-indent curr:address:duplex-list:character, start:address:duplex-list:character -> result:number [ local-scope load-ingredients result:number <- copy 0 return-unless curr at-start?:boolean <- equal curr, start return-if at-start? { curr <- prev curr break-unless curr at-start?:boolean <- equal curr, start break-if at-start? c:character <- get *curr, value:offset at-newline?:boolean <- equal c, 10/newline break-if at-newline? # if c is a space, increment result is-space?:boolean <- equal c, 32/space { break-unless is-space? result <- add result, 1 } # if c is not a space, reset result { break-if is-space? result <- copy 0 } loop } ] scenario editor-moves-cursor-down-after-inserting-newline-2 [ assume-screen 10/width, 5/height 1:address:array:character <- new [abc] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 1/left, 10/right assume-console [ type [0 1] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] screen-should-contain [ . . . 0 . . 1abc . . ┈┈┈┈┈┈┈┈┈. . . ] ] scenario editor-clears-previous-line-completely-after-inserting-newline [ assume-screen 10/width, 5/height 1:address:array:character <- new [abcde] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 5/right assume-console [ press enter ] screen-should-contain [ . . .abcd . .e . . . . . ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data ] # line should be fully cleared screen-should-contain [ . . . . .abcd . .e . .┈┈┈┈┈ . ] ] scenario editor-inserts-indent-after-newline [ assume-screen 10/width, 10/height 1:address:array:character <- new [ab cd ef] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right # position cursor after 'cd' and hit 'newline' assume-console [ left-click 2, 8 type [ ] ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] # cursor should be below start of previous line memory-should-contain [ 3 <- 3 # cursor row 4 <- 2 # cursor column (indented) ] ] scenario editor-skips-indent-around-paste [ assume-screen 10/width, 10/height 1:address:array:character <- new [ab cd ef] 2:address:editor-data <- new-editor 1:address:array:character, screen:address:screen, 0/left, 10/right # position cursor after 'cd' and hit 'newline' surrounded by paste markers assume-console [ left-click 2, 8 press 65507 # start paste press enter press 65506 # end paste ] run [ editor-event-loop screen:address:screen, console:address:console, 2:address:editor-data 3:number <- get *2:address:editor-data, cursor-row:offset 4:number <- get *2:address:editor-data, cursor-column:offset ] # cursor should be below start of previous line memory-should-contain [ 3 <- 3 # cursor row 4 <- 0 # cursor column (not indented) ] ] after <handle-special-key> [ { paste-start?:boolean <- equal k, 65507/paste-start break-unless paste-start? *editor <- put *editor, indent?:offset, 0/false go-render? <- copy 1/true return } ] after <handle-special-key> [ { paste-end?:boolean <- equal k, 65506/paste-end break-unless paste-end? *editor <- put *editor, indent?:offset, 1/true go-render? <- copy 1/true return } ] ## helpers def draw-horizontal screen:address:screen, row:number, x:number, right:number -> screen:address:screen [ local-scope load-ingredients style:character, style-found?:boolean <- next-ingredient { break-if style-found? style <- copy 9472/horizontal } color:number, color-found?:boolean <- next-ingredient { # default color to white break-if color-found? color <- copy 245/grey } bg-color:number, bg-color-found?:boolean <- next-ingredient { break-if bg-color-found? bg-color <- copy 0/black } screen <- move-cursor screen, row, x { continue?:boolean <- lesser-or-equal x, right # right is inclusive, to match editor-data semantics break-unless continue? print screen, style, color, bg-color x <- add x, 1 loop } ]