public
Description: ioke is a new language for the JVM, based on Io and other languages.
Homepage: http://ioke.org
Clone URL: git://github.com/olabini/ioke.git
ioke / src / main / ioke / lang / IokeList.java
100644 518 lines (432 sloc) 25.667 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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package ioke.lang;
 
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.HashMap;
 
import ioke.lang.exceptions.ControlFlow;
 
/**
*
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class IokeList extends IokeData {
    private List<Object> list;
 
    public IokeList() {
        this(new ArrayList<Object>());
    }
 
    public IokeList(List<Object> l) {
        this.list = l;
    }
 
    public static void add(Object list, Object obj) {
        ((IokeList)IokeObject.data(list)).list.add(obj);
    }
 
    @Override
    public void init(IokeObject obj) throws ControlFlow {
        final Runtime runtime = obj.runtime;
 
        obj.setKind("List");
        obj.mimics(IokeObject.as(runtime.mixins.getCell(null, null, "Enumerable")), runtime.nul, runtime.nul);
 
        obj.registerMethod(obj.runtime.newJavaMethod("Returns a text inspection of the object", new JavaMethod.WithNoArguments("inspect") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    return method.runtime.newText(IokeList.getInspect(on));
                }
            }));
 
        obj.registerMethod(obj.runtime.newJavaMethod("Returns a brief text inspection of the object", new JavaMethod.WithNoArguments("notice") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    return method.runtime.newText(IokeList.getNotice(on));
                }
            }));
 
        obj.registerMethod(obj.runtime.newJavaMethod("Compares this object against the argument. The comparison is only based on the elements inside the lists, which are in turn compared using <=>.", new JavaMethod("<=>") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("other")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
 
                    List<Object> one = IokeList.getList(on);
                    List<Object> two = IokeList.getList(args.get(0));
 
                    int len = Math.min(one.size(), two.size());
                    SpaceshipComparator sc = new SpaceshipComparator(context, message);
 
                    for(int i = 0; i < len; i++) {
                        int v = sc.compare(one.get(i), two.get(i));
                        if(v != 0) {
                            return context.runtime.newNumber(v);
                        }
                    }
 
                    len = one.size() - two.size();
 
                    if(len == 0) return context.runtime.newNumber(0);
                    if(len > 0) return context.runtime.newNumber(1);
                    return context.runtime.newNumber(-1);
                }
            }));
        
        obj.registerMethod(runtime.newJavaMethod("takes either one or two or three arguments. if one argument is given, it should be a message chain that will be sent to each object in the list. the result will be thrown away. if two arguments are given, the first is an unevaluated name that will be set to each of the values in the list in succession, and then the second argument will be evaluated in a scope with that argument in it. if three arguments is given, the first one is an unevaluated name that will be set to the index of each element, and the other two arguments are the name of the argument for the value, and the actual code. the code will evaluate in a lexical context, and if the argument name is available outside the context, it will be shadowed. the method will return the list.", new JavaMethod("each") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositionalUnevaluated("indexOrArgOrCode")
                    .withOptionalPositionalUnevaluated("argOrCode")
                    .withOptionalPositionalUnevaluated("code")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().checkArgumentCount(context, message, on);
 
                    Runtime runtime = context.runtime;
                    List<Object> ls = ((IokeList)IokeObject.data(on)).list;
                    switch(message.getArgumentCount()) {
                    case 1: {
                        IokeObject code = IokeObject.as(message.getArguments().get(0));
 
                        for(Object o : ls) {
                            code.evaluateCompleteWithReceiver(context, context.getRealContext(), o);
                        }
                        break;
                    }
                    case 2: {
                        LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#each", message, context);
                        String name = IokeObject.as(message.getArguments().get(0)).getName();
                        IokeObject code = IokeObject.as(message.getArguments().get(1));
 
                        for(Object o : ls) {
                            c.setCell(name, o);
                            code.evaluateCompleteWithoutExplicitReceiver(c, c.getRealContext());
                        }
                        break;
                    }
                    case 3: {
                        LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#each", message, context);
                        String iname = IokeObject.as(message.getArguments().get(0)).getName();
                        String name = IokeObject.as(message.getArguments().get(1)).getName();
                        IokeObject code = IokeObject.as(message.getArguments().get(2));
 
                        int index = 0;
                        for(Object o : ls) {
                            c.setCell(name, o);
                            c.setCell(iname, runtime.newNumber(index++));
                            code.evaluateCompleteWithoutExplicitReceiver(c, c.getRealContext());
                        }
                        break;
                    }
                    }
                    return on;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("takes one argument and adds it at the end of the list, and then returns the list", new JavaMethod("<<") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("value")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
                    IokeList.add(on, args.get(0));
                    return on;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("will remove all the entries from the list, and then returns the list", new JavaMethod.WithNoArguments("clear!") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    ((IokeList)IokeObject.data(on)).getList().clear();
                    return on;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns true if this list is empty, false otherwise", new JavaMethod.WithNoArguments("empty?") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    return ((IokeList)IokeObject.data(on)).getList().isEmpty() ? context.runtime._true : context.runtime._false;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns true if the receiver includes the evaluated argument, otherwise false", new JavaMethod("include?") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("object")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
                    return ((IokeList)IokeObject.data(on)).getList().contains(args.get(0)) ? context.runtime._true : context.runtime._false;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns a new list that contains the receivers elements and the elements of the list sent in as the argument.", new JavaMethod("+") {
                private final TypeCheckingArgumentsDefinition ARGUMENTS = TypeCheckingArgumentsDefinition
                    .builder()
                    .receiverMustMimic(runtime.list)
                    .withRequiredPositional("otherList").whichMustMimic(runtime.list)
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    Object receiver = ARGUMENTS.getValidatedArgumentsAndReceiver(context, message, on, args, new HashMap<String, Object>());
                    List<Object> newList = new ArrayList<Object>();
                    newList.addAll(((IokeList)IokeObject.data(receiver)).getList());
                    newList.addAll(((IokeList)IokeObject.data(args.get(0))).getList());
                    return context.runtime.newList(newList, IokeObject.as(receiver));
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns a new list that contains all the elements from the receivers list, except for those that are in the argument list", new JavaMethod("-") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("otherList")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
                    List<Object> newList = new ArrayList<Object>();
                    newList.addAll(((IokeList)IokeObject.data(on)).getList());
                    newList.removeAll(((IokeList)IokeObject.data(args.get(0))).getList());
                    return context.runtime.newList(newList, IokeObject.as(on));
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns a new sorted version of this list", new JavaMethod.WithNoArguments("sort") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    Object newList = IokeObject.mimic(on, message, context);
                    try {
                        Collections.sort(((IokeList)IokeObject.data(newList)).getList(), new SpaceshipComparator(context, message));
                    } catch(RuntimeException e) {
                        if(e.getCause() instanceof ControlFlow) {
                            throw (ControlFlow)e.getCause();
                        }
                        throw e;
                    }
                    return newList;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("sorts this list in place and then returns it", new JavaMethod.WithNoArguments("sort!") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    try {
                        Collections.sort(((IokeList)IokeObject.data(on)).getList(), new SpaceshipComparator(context, message));
                    } catch(RuntimeException e) {
                        if(e.getCause() instanceof ControlFlow) {
                            throw (ControlFlow)e.getCause();
                        }
                        throw e;
                    }
                    return on;
                }
            }));
 
        obj.registerMethod(runtime.newJavaMethod("returns the size of this list", new JavaMethod.WithNoArguments("size") {
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    getArguments().getEvaluatedArguments(context, message, on, new ArrayList<Object>(), new HashMap<String, Object>());
                    return context.runtime.newNumber(((IokeList)IokeObject.data(on)).getList().size());
                }
            }));
        obj.aliasMethod("size", "length", null, null);
 
        obj.registerMethod(runtime.newJavaMethod("takes one argument, the index of the element to be returned. can be negative, and will in that case return indexed from the back of the list. if the index is outside the bounds of the list, will return nil. the argument can also be a range, and will in that case interpret the first index as where to start, and the second the end. the end can be negative and will in that case be from the end. if the first argument is negative, or after the second, an empty list will be returned. if the end point is larger than the list, the size of the list will be used as the end point.", new JavaMethod("at") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("index")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
 
                    Object arg = args.get(0);
 
                    if(IokeObject.data(arg) instanceof Range) {
                        int first = Number.extractInt(Range.getFrom(arg), message, context);
                        
                        if(first < 0) {
                            return context.runtime.newList(new ArrayList<Object>());
                        }
 
                        int last = Number.extractInt(Range.getTo(arg), message, context);
                        boolean inclusive = Range.isInclusive(arg);
 
                        List<Object> o = ((IokeList)IokeObject.data(on)).getList();
                        int size = o.size();
 
                        if(last < 0) {
                            last = size + last;
                        }
 
                        if(last < 0) {
                            return context.runtime.newList(new ArrayList<Object>());
                        }
 
                        if(last >= size) {
                            
                            last = inclusive ? size-1 : size;
                        }
 
                        if(first > last || (!inclusive && first == last)) {
                            return context.runtime.newList(new ArrayList<Object>());
                        }
                        
                        if(!inclusive) {
                            last--;
                        }
                        
                        return context.runtime.newList(new ArrayList<Object>(o.subList(first, last+1)));
                    }
 
                    if(!(IokeObject.data(arg) instanceof Number)) {
                        arg = IokeObject.convertToNumber(arg, message, context);
                    }
                    int index = ((Number)IokeObject.data(arg)).asJavaInteger();
                    List<Object> o = ((IokeList)IokeObject.data(on)).getList();
                    if(index < 0) {
                        index = o.size() + index;
                    }
 
                    if(index >= 0 && index < o.size()) {
                        return o.get((int)index);
                    } else {
                        return context.runtime.nil;
                    }
                }
            }));
 
        obj.aliasMethod("at", "[]", null, null);
 
        obj.registerMethod(runtime.newJavaMethod("takes two arguments, the index of the element to set, and the value to set. the index can be negative and will in that case set indexed from the end of the list. if the index is larger than the current size, the list will be expanded with nils. an exception will be raised if a abs(negative index) is larger than the size.", new JavaMethod("at=") {
                private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
                    .builder()
                    .withRequiredPositional("index")
                    .withRequiredPositional("value")
                    .getArguments();
 
                @Override
                public DefaultArgumentsDefinition getArguments() {
                    return ARGUMENTS;
                }
 
                @Override
                public Object activate(IokeObject method, final IokeObject context, final IokeObject message, Object on) throws ControlFlow {
                    List<Object> args = new ArrayList<Object>();
                    getArguments().getEvaluatedArguments(context, message, on, args, new HashMap<String, Object>());
 
                    Object arg = args.get(0);
                    Object value = args.get(1);
                    if(!(IokeObject.data(arg) instanceof Number)) {
                        arg = IokeObject.convertToNumber(arg, message, context);
                    }
                    int index = ((Number)IokeObject.data(arg)).asJavaInteger();
                    List<Object> o = ((IokeList)IokeObject.data(on)).getList();
                    if(index < 0) {
                        index = o.size() + index;
                    }
 
                    while(index < 0) {
                        final IokeObject condition = IokeObject.as(IokeObject.getCellChain(context.runtime.condition,
                                                                                           message,
                                                                                           context,
                                                                                           "Error",
                                                                                           "Index")).mimic(message, context);
                        condition.setCell("message", message);
                        condition.setCell("context", context);
                        condition.setCell("receiver", on);
                        condition.setCell("index", context.runtime.newNumber(index));
 
                        final int[] newCell = new int[]{index};
 
                        context.runtime.withRestartReturningArguments(new RunnableWithControlFlow() {
                                public void run() throws ControlFlow {
                                    context.runtime.errorCondition(condition);
                                }},
                            context,
                            new Restart.ArgumentGivingRestart("useValue") {
                                public List<String> getArgumentNames() {
                                    return new ArrayList<String>(Arrays.asList("newValue"));
                                }
 
                                public IokeObject invoke(IokeObject context, List<Object> arguments) throws ControlFlow {
                                    newCell[0] = Number.extractInt(arguments.get(0), message, context);
                                    return context.runtime.nil;
                                }
                            }
                            );
 
                        index = newCell[0];
                        if(index < 0) {
                            index = o.size() + index;
                        }
                    }
 
                    if(index >= o.size()) {
                        int toAdd = (index-o.size()) + 1;
                        for(int i=0;i<toAdd;i++) {
                            o.add(context.runtime.nil);
                        }
                    }
 
                    o.set((int)index, value);
 
                    return value;
                }
            }));
 
        obj.aliasMethod("at=", "[]=", null, null);
    }
 
    public void add(Object obj) {
        list.add(obj);
    }
 
    public List<Object> getList() {
        return list;
    }
 
    public static List<Object> getList(Object on) {
        return ((IokeList)(IokeObject.data(on))).getList();
    }
 
    public static String getInspect(Object on) throws ControlFlow {
        return ((IokeList)(IokeObject.data(on))).inspect(on);
    }
 
    public static String getNotice(Object on) throws ControlFlow {
        return ((IokeList)(IokeObject.data(on))).notice(on);
    }
 
    public IokeData cloneData(IokeObject obj, IokeObject m, IokeObject context) {
        return new IokeList(new ArrayList<Object>(list));
    }
 
    @Override
    public boolean isEqualTo(IokeObject self, Object other) {
        return ((other instanceof IokeObject) &&
                (IokeObject.data(other) instanceof IokeList)
                && this.list.equals(((IokeList)IokeObject.data(other)).list));
    }
 
    @Override
    public int hashCode(IokeObject self) {
        return this.list.hashCode();
    }
 
    @Override
    public String toString() {
        return list.toString();
    }
 
    @Override
    public String toString(IokeObject obj) {
        return list.toString();
    }
 
    public String inspect(Object obj) throws ControlFlow {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        String sep = "";
        for(Object o : list) {
            sb.append(sep).append(IokeObject.inspect(o));
            sep = ", ";
        }
        sb.append("]");
        return sb.toString();
    }
 
    public String notice(Object obj) throws ControlFlow {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        String sep = "";
        for(Object o : list) {
            sb.append(sep).append(IokeObject.notice(o));
            sep = ", ";
        }
        sb.append("]");
        return sb.toString();
    }
}// IokeList