/
Interp.java
1331 lines (1179 loc) · 36.3 KB
/
Interp.java
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2004-2010 David N. Welton, DedaSys LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.hecl;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
//#if j2se
import java.util.LinkedList;
import java.util.List;
import jline.ArgumentCompletor;
import jline.ConsoleReader;
import jline.NullCompletor;
import jline.SimpleCompletor;
//#endif
/**
* <code>Interp</code> is the Hecl interpreter, the class responsible for
* knowing what variables and commands are available.
*
* @author <a href="mailto:davidw@dedasys.com">David N. Welton </a>
* @version 1.0
*/
public class Interp extends Thread/*implements Runnable*/ {
/**
* Package name prefix of the module classes.
*/
public static final String MODULE_CLASS_PACKAGE = "org.hecl";
/**
* Flags for the event loop.
*/
public static final int DONT_WAIT = 1;
public static final int IDLE_EVENTS = 2;
public static final int TIMER_EVENTS = 4;
public static final int ALL_EVENTS = ~DONT_WAIT;
/**
* Some string constants used to generate names for internal events.
*/
public static final String ASYNCPREFIX = "async";
public static final String IDLEPREFIX = "idle";
public static final String TIMERPREFIX = "timer";
/**
* The prompt for the <code>readEvalPrint</code> loop.
*/
public final String PROMPT = "hecl> ";
/**
* The prompt for continued lines in the <code>readEvalPrint</code> loop.
*/
public final String PROMPT2 = "hecl+ ";
/**
* A <code>Thing</code> to indicate global reference.
*/
static final Thing GLOBALREFTHING = new Thing("");
/* Used to cache command lookups. */
public long cacheversion = 0;
/* Do we have the Java reflection stuff? */
private static boolean javacmdpresent = false;
/**
* The <code>commands</code> <code>Hashtable</code> provides the
* mapping from the strings containing command names to the code
* implementing the commands.
*/
protected Hashtable commands = new Hashtable();
/**
* The <code>auxdata</code> <code>Hashtable</code> is a place to
* store extra information about the state of the program.
*
*/
protected Hashtable auxdata = new Hashtable();
protected Stack stack = new Stack();
protected Stack error = new Stack();
protected Vector timers = new Vector();
protected Vector asyncs = new Vector();
protected Vector idle = new Vector();
protected Hashtable waittokens = new Hashtable();
protected long idlegeneration = 0;
protected boolean running = true;
protected long maxblocktime = 0; // block time in milliseconds
protected Vector ci = new Vector();
protected Hashtable classcmdcache = new Hashtable();
/**
* <code>procclass</code> is used by CLDC 1.0 to store the 'Proc'
* class, since you can't just do Proc.class in that version of
* J2ME.
*
*/
//#if cldc == 1.0
static Class procclass;
//#endif
/**
* <code>eol</code> is the end-of-line character or characters.
*
*/
//#ifdef j2se
public static final char eol[] =
System.getProperty("line.separator").toCharArray();
//#else
public static final char eol[] = { '\n' };
//#endif
//#if files || j2se
/**
* <code>fileseparator</code> is the file separator, such as "/".
*
*/
public static final String fileseparator =
System.getProperty("file.separator");
public Thing currentFile = new Thing("");
//#endif
/**
* Creates a new <code>Interp</code> instance, initializing command and
* variable hashtables, a stack, and an error stack.
*
* @exception HeclException if an error occurs
*/
public Interp() throws HeclException {
try {
//#if cldc == 1.0
procclass = Class.forName("Proc");
//#endif
/* Check and see if the "java" extension is present */
Class.forName("org.hecl.java.JavaCmd");
javacmdpresent = true;
} catch (ClassNotFoundException e) {
/* Ignore it - nothing changes. */
}
// Set up stack frame for globals.
stack.push(new Hashtable());
initInterp();
start();
}
//#ifdef j2se
protected String[] hashKeysToArray(Hashtable h) {
return hashKeysToArray(h, "");
}
protected String[] hashKeysToArray(Hashtable h, String prefix) {
Vector<String> cmds = new Vector<String>();
for (Enumeration e = h.keys(); e.hasMoreElements();) {
cmds.add(prefix + (String)e.nextElement());
}
String[] scmds = new String[cmds.size()];
cmds.copyInto(scmds);
return scmds;
}
//#endif
/**
* The <code>commandLine</code> method implements a
* Read/Eval/Print Loop.
*
* @param in Input stream to read input from.
* @param out Output stream to print results to.
* @param err Output stream for error messages.
*
* This function never returns.
*/
public void readEvalPrint(InputStream in, PrintStream out, PrintStream err) {
String prompt = PROMPT;
StringBuffer sb = new StringBuffer();
//#if j2se
List completors = null;
ConsoleReader reader = null;
int oldsz = 0;
int newsz = 0;
//#else
InputStreamReader reader = new InputStreamReader(in);
//#endif
while(true) {
byte outbytes[] = null;
String line = null;
//#if j2se
Hashtable vars = getVarhash(-1);
newsz = commands.size() + vars.size();
/* If the number of commands or variables has increased,
* reindex them in the command line completor. Currently,
* it uses commands for the first completion, and variable
* names (with leading $) for subsequent completions. */
if (newsz > oldsz) {
completors = new LinkedList();
completors.add(
new SimpleCompletor(hashKeysToArray(commands)));
completors.add(
new SimpleCompletor(hashKeysToArray(vars, "$")));
completors.add(new NullCompletor());
try {
reader = new ConsoleReader();
reader.addCompletor(new ArgumentCompletor(completors));
} catch (IOException e) {
System.err.println(e);
return;
}
oldsz = newsz;
}
try {
line = reader.readLine(prompt);
} catch (IOException e) {
err.println(e);
break;
}
//#else
out.print(prompt);
out.flush();
line = readLine(reader);
//#endif
if(line == null)
break;
if(sb.length() > 0)
sb.append('\n');
sb.append(line);
try {
if(sb.length() <= 0)
continue;
Thing res = evalAsyncAndWait(new Thing(sb.toString()));
if (res != null) {
String s = res.toString();
if(s.length() > 0) {
// It seems that DataOutputStream.println(String)
// is broken and returns OutOfmemory when the
// string is to long, so we convert the string
// into bytes and write out the pure bytes
// directly.
outbytes = s.getBytes();
}
}
sb.delete(0,sb.length());
prompt = PROMPT;
}
catch(HeclException he) {
if (he.code.equals("PARSE_ERROR")) {
// Change prompt and get more input
prompt = PROMPT2;
} else {
sb.delete(0,sb.length());
he.printStackTrace();
outbytes = he.getMessage().getBytes();
prompt = PROMPT;
}
}
if(outbytes != null) {
// result output
try {
out.write(outbytes);
out.println();
}
catch(IOException ioex) {
err.println(ioex.getMessage());
break;
}
outbytes = null;
}
}
}
/**
* Add a new class command to an <code>Interp</code>.
*
* @param clazz The Java class the command should operate on.
* @param cmd The command to add. When this paramter is <code>null</code>,
* an existing command is removed.
*/
public void addClassCmd(Class clazz,ClassCommand cmd) {
// clear cache first, even when deleting a cmd
this.classcmdcache.clear();
int l = this.ci.size();
for(int i=0; i<l; ++i) {
ClassCommandInfo info = (ClassCommandInfo)this.ci.elementAt(i);
if(info.forClass() == clazz) {
//identical, replace
if(cmd == null) {
ci.removeElementAt(i);
} else {
info.setCommand(cmd);
}
return;
}
}
if(cmd != null)
this.ci.addElement(new ClassCommandInfo(clazz,cmd));
}
/**
* Remove a command for a specific class from an <code>Interp</code>.
*
* @param clazz The class to remove the command for.
*/
public void removeClassCmd(Class clazz) { addClassCmd(clazz,null);}
/**
* Add a new class command to an <code>Interp</code>.
*<br>
* The current implementation does not support any subclassing and selects
* the first class command <code>clazz</code> is assignable to.
*
* @param clazz The Java class to look up the class command for.
* @return A <code>ClassCommandInfo</code> decsribing the class command,
* or <code>null</null> if no command was found.
*/
ClassCommandInfo findClassCmd(Class clazz) {
ClassCommandInfo found = (ClassCommandInfo)this.classcmdcache.get(clazz);
if(found == null) {
// No entry in cache, so we loop over all class commands and try
// to detect the most specific one.
int l = this.ci.size();
for(int i=0; i<l; ++i) {
ClassCommandInfo info = (ClassCommandInfo)this.ci.elementAt(i);
Class cl2 = info.forClass();
if(cl2.isAssignableFrom(clazz)) {
//System.err.println("clazz="+clazz+" assignable to cl="+cl2);
if(found == null)
found = info;
else {
// check if this is more specialized than the one we
// already have.
if(found.forClass().isAssignableFrom(cl2)) {
//System.err.println("superclass="+found.forClass()+" for cl="+cl2);
found = info;
}
// else keep existing one
}
}
}
// Add what we found to the cache, so we do not need to look it up
// next time.
if(found != null) {
this.classcmdcache.put(clazz,found);
} else if (javacmdpresent) {
/* Still nothing - let's see if we have the Java
* reflection stuff loaded and try using that. FIXME -
* consider making this configurable? */
//#ifdef j2se
try {
org.hecl.java.JavaCmd.load(this, clazz.getName(), null);
return findClassCmd(clazz);
} catch (HeclException he) {
/* Ignore this. */
}
//#else
return findClassCmd(clazz);
//#endif
}
}
return found;
}
/**
* Add a new command to an <code>Interp</code>.
*
* @param name the name of the command to add.
* @param c the command to add.
*/
public synchronized String addCommand(String name,Command c) {
commands.put(name,c);
return name;
}
/**
* Remove a command from an <code>Interp</code>.
*
* @param name the name of the command to add.
*/
public synchronized void removeCommand(String name) {
commands.remove(name);
}
/**
* The <code>commandExists</code> method returns true if a command
* exists, otherwise false.
*
* @param name a <code>String</code> value
* @return a <code>boolean</code> value
*/
public synchronized boolean commandExists(String name) {
return commands.containsKey(name);
}
/**
* Attach auxiliary data to an <code>Interp</code>.
*/
public synchronized void setAuxData(String key,Object value) {
auxdata.put(key, value);
}
/**
* Retrieve auxiliary data from an <code>Interp</code>.
*
* @return a <code>Object</code> value or <code>null</code> when no
* auxiliary data under the given key is attached to the interpreter.
*/
public synchronized Object getAuxData(String key) {
return auxdata.get(key);
}
/**
* Remove auxiliary data from an <code>Interp</code>.
*/
public synchronized void removeAuxData(String key) {
auxdata.remove(key);
}
/**
* The <code>eval</code> method evaluates some Hecl code passed to
* it.
*
* @return a <code>Thing</code> value - the result of the
* evaluation.
* @exception HeclException if an error occurs.
*/
public synchronized Thing eval(Thing in) throws HeclException {
//System.err.println("-->eval: "+in.toString());
return CodeThing.get(this, in).run(this);
}
public HeclTask evalIdle(Thing idleThing) {
return addTask(idle,new HeclTask(idleThing,idlegeneration,IDLEPREFIX),-1);
}
public HeclTask evalAsync(Thing asyncThing) {
return addTask(asyncs, new HeclTask(asyncThing,0,ASYNCPREFIX),-1);
}
public Thing evalAsyncAndWait(Thing in) throws HeclException {
HeclTask t = evalAsync(in);
t.setErrorPrint(false);
boolean done = false;
while(!t.isDone()) {
try {
synchronized(t) {
t.wait();
}
}
catch(Exception e) {
// ignore
e.printStackTrace();
}
}
try {
Exception e = t.getError();
if(e != null)
throw e;
return t.getResult();
}
catch (HeclException he) {
throw he;
}
catch(Exception e) {
throw new HeclException(e.getMessage());
}
}
/**
* This version of <code>eval</code> takes a 'level' argument that
* tells Hecl what level to run the code at. Level 0 means
* global, negative numbers indicate relative levels down from the
* current stackframe, and positive numbers mean absolute stack
* frames counting up from 0.
*
* @param in a <code>Thing</code> value
* @param level an <code>int</code> value
* @return a <code>Thing</code> value
* @exception HeclException if an error occurs
*/
public Thing eval(Thing in, int level) throws HeclException {
Thing result = null;
Vector savedstack = new Vector();
int stacklen = stack.size();
int i = 0;
int end = 0;
HeclException save_exception = null;
if (level >= 0) {
end = level;
} else {
end = (stacklen - 1 + level);
}
/* Save the old stack frames... */
for (i = stacklen - 1; i > end; i--) {
savedstack.addElement(stackDecr());
}
try {
result = eval(in);
} catch (HeclException he) {
/* If this is an upeval situation, we need to catch the
* exception and then throw it *after* the old stack frame
* has been restored. */
save_exception = he;
}
/* ... and then restore them after evaluating the code. */
for (i = savedstack.size() - 1; i >= 0; i--) {
stackPush((Hashtable)savedstack.elementAt(i));
}
if (save_exception != null) {
throw save_exception;
}
return result;
}
public boolean hasIdleTasks() {
return this.idle.size() == 0;
}
public synchronized HeclTask getEvent(String name) {
int n = timers.size();
Vector v = new Vector();
HeclTask t = null;
for(int i=0; i<n; ++i) {
t = (HeclTask)timers.elementAt(i);
if(name.equals(t.getName()))
return t;
}
n = idle.size();
for(int i=0; i<n; ++i) {
t = (HeclTask)idle.elementAt(i);
if(name.equals(t.getName()))
return t;
}
return null;
}
public synchronized Vector getAllEvents() {
int n = timers.size();
Vector v = new Vector();
for(int i=0; i<n; ++i)
v.addElement(timers.elementAt(i));
n = idle.size();
for(int i=0; i<n; ++i)
v.addElement(timers.elementAt(i));
return v;
}
public HeclTask addTimer(Thing timerThing, int millisecs) {
synchronized (timers) {
int n = timers.size();
long ts = System.currentTimeMillis()+millisecs;
HeclTask t = new HeclTask(timerThing, ts, TIMERPREFIX);
int i;
for(i=0; i<n; ++i) {
HeclTask other = (HeclTask)timers.elementAt(i);
if(other.getGeneration() > ts)
break;
}
//System.err.println("Adding timer, time="+ts);
return addTask(timers,t,i);
}
}
public void cancelTimer(String name) {
cancelTask(timers,name);
}
public void cancelIdle(String name) {
cancelTask(idle,name);
}
public void cancelAsync(String name) {
cancelTask(asyncs,name);
}
public synchronized void cancelIdle(HeclTask idletask) {
idle.removeElement(idletask);
}
public synchronized boolean doOneEvent(int flags) {
if((flags & ALL_EVENTS) == 0)
flags = ALL_EVENTS;
// The core of this procedure is an infinite loop, even though
// we only service one event. The reason for this is that we
// may be processing events that don't do anything inside of Hecl.
int count = 0;
while(true) {
// First check for async events...
HeclTask t = nextTask(asyncs,-1);
if(t != null) {
return executeTask(t);
}
long now = System.currentTimeMillis();
if((flags & TIMER_EVENTS) != 0) {
t = nextTask(timers,now);
if(t != null) {
return executeTask(t);
}
}
// Determine maxblocktime
if ((flags & DONT_WAIT) != 0) {
maxblocktime = 0;
} else {
maxblocktime = 1000;
synchronized(this) {
if(timers.size() > 0) {
t = (HeclTask)timers.elementAt(0);
maxblocktime = t.getGeneration() - now;
}
}
}
// this may reduce maxblocktime!
if((flags & IDLE_EVENTS) != 0) {
serviceIdleTask();
}
if(count > 0 || maxblocktime <= 0)
break;
yield(); // give other thread a chance
synchronized(this) {
try {
this.wait(maxblocktime);
} catch (InterruptedException e) {
// it doesn't matter
}
}
//System.err.println("interp wait done, next loop iteration");
++count;
}
//System.err.println("<--doOneEvent:false");
return false;
}
public void waitForToken(String tokenname) throws HeclException {
boolean exists = false;
WaitToken token = null;
synchronized(this) {
exists = waittokens.containsKey(tokenname);
if(exists)
throw new HeclException("Wait token '"+tokenname+"' already exists.");
token = new WaitToken();
waittokens.put(tokenname,token);
}
// Endless loop, some event in the future should kick us off this loop
boolean b = true;
while(b) {
// Carefully read/modify status information
synchronized(this) {
b = token.waiting;
}
if(b) {
// Service one event
doOneEvent(Interp.ALL_EVENTS);
}
}
}
public void notifyToken(String tokenname) throws HeclException {
synchronized(this) {
WaitToken token = (WaitToken)waittokens.get(tokenname);
if(token == null)
throw new HeclException("No wait token '"+tokenname+"'.");
token.waiting = false;
waittokens.remove(tokenname);
}
}
/**
* The <code>terminate</code> method terminates the Hecl
* interpreter thread in a graceful manner. The thread will
* eventually finish its run-method.
*
*/
public void terminate() {
running = false;
synchronized(this) {
notify();
}
}
public void run() {
// System.err.println("interp running...");
long now = System.currentTimeMillis();
while(running) {
doOneEvent(ALL_EVENTS);
}
// System.err.println("interp stopped!");
}
/**
* The <code>initCommands</code> method initializes all the built in
* commands. These are commands available in all versions of Hecl. J2SE
* commands are initialized in Standard.java, and J2ME commands in
* Micro.java.
*
* @exception HeclException if an error occurs
*/
private void initInterp() throws HeclException {
/* Do not use the 'Facade' style commands as an example if you
* just have to add a simple command or two. The pattern
* works best when you need to add several commands with
* related functionality. */
// System.err.println("-->initinterp");
// System.err.println("loading interp cmds...");
/* Commands that manipulate interp data structures -
* variables, procs, commands, and so forth. */
InterpCmds.load(this);
// System.err.println("loading math cmds...");
/* Math and logic commands. */
MathCmds.load(this);
// System.err.println("loading list cmds...");
/* List related commands. */
ListCmds.load(this);
// System.err.println("loading control cmds...");
/* Control commands. */
ControlCmds.load(this);
// System.err.println("loading string cmds...");
/* String commands. */
StringCmds.load(this);
// System.err.println("loading hash cmds...");
/* Hash table commands. */
HashCmds.load(this);
commands.put("puts", new PutsCmd());
commands.put("sort", new SortCmd());
//#if cldc == 1.0
addClassCmd(procclass, new AnonProc());
//#else
addClassCmd(Proc.class, new AnonProc());
//#endif
// System.err.println("<--initinterp");
}
/**
* The <code>cmdRename</code> method renames a command, or throws
* an error if the original command didn't exist.
*
* @param oldname a <code>String</code> value
* @param newname a <code>String</code> value
* @exception HeclException if an error occurs
*/
public synchronized void cmdRename(String oldname, String newname)
throws HeclException {
cmdAlias(oldname, newname);
commands.remove(oldname);
}
public synchronized void cmdAlias(String oldname, String newname)
throws HeclException {
Command tmp = (Command)commands.get(oldname);
if (tmp == null) {
throw new HeclException("Command " + oldname + " does not exist");
}
commands.put(newname, tmp);
}
/**
* The <code>stackIncr</code> method creates a new stack frame. Used in
* the Proc class.
*
*/
public synchronized void stackIncr() {
stackPush(new Hashtable());
}
/**
* <code>stackDecr</code> pops the stack frame, returning it so that
* commands like upeval can save it. If it's not saved, it's gone.
*
*/
public synchronized Hashtable stackDecr() {
return (Hashtable) stack.pop();
}
/**
* <code>stackDecr</code> pushes a new variable hashtable
* (probably saved via upeval) onto the stack frame.
*
*/
public synchronized void stackPush(Hashtable vars) {
cacheversion++;
stack.push(vars);
}
/**
* <code>getVarhash</code> fetches the variable Hashtable at the
* given level, where -1 means to just get the hashtable on top of
* the stack.
*
* @param level an <code>int</code> value
* @return a <code>Hashtable</code> value
*/
private Hashtable getVarhash(int level) {
return level < 0 ? (Hashtable)stack.peek()
: (Hashtable)stack.elementAt(level);
}
/**
* <code>getVar</code> returns the value of a variable given its name.
*
* @param varname a <code>Thing</code> value
*
* @return a <code>Thing</code> value
* @exception HeclException if an error occurs
*/
public Thing getVar(Thing varname) throws HeclException {
return getVar(varname.toString(), -1);
}
/**
* <code>getVar</code> returns the value of a variable given its name.
*
* @param varname a <code>String</code> value
* @return a <code>Thing</code> value
* @exception HeclException if an error occurs
*/
public Thing getVar(String varname) throws HeclException {
return getVar(varname, -1);
}
/**
* <code>getVar</code> returns the value of a variable given its name and
* level.
*
* @param varname a <code>String</code> value
* @param level an <code>int</code> value
* @return a <code>Thing</code> value
* @exception HeclException if an error occurs
*/
public synchronized Thing getVar(String varname, int level) throws HeclException {
Hashtable lookup = getVarhash(level);
//System.out.println("getvar: " + varname + " " + level + " " + lookup);
Thing res = (Thing) lookup.get(varname);
//#ifdef old
if (res == null) {
throw new HeclException("Variable " + varname + " does not exist");
}
return res;
//#else
if(res == GLOBALREFTHING) {
// ref to a global var
Hashtable globalhash = getVarhash(0);
res = (Thing)globalhash.get(varname);
if(res == GLOBALREFTHING) {
// should not happen, but just in case...
System.err.println("Unexpected GLOBALREFTHING in globalhash");
res = null;
}
//#ifdef emptyglobals
else if (res == null) {
// Return a fake empty value for a non-set global variable for
// the sake of modifying commands.
// !!!! THIS IS STRANGE !!!
System.err.println("FAKE EMPTY VALUE for global var");
res = new Thing("");
globalhash.put(varname,res);
}
//#endif
}
if (res == null) {
throw new HeclException("Variable " + varname + " does not exist");
}
//System.err.println("<<getvar, res="+res);
return res;
//#endif
}
/**
* <code>setVar</code> sets a variable in the innermost variable stack
* frame to a value.
*
* @param varname a <code>Thing</code> value
* @param value a <code>Thing</code> value
*/
public void setVar(Thing varname, Thing value) throws HeclException {
setVar(varname.toString(), value);
}
/**
* <code>setVar</code> sets a variable in the innermost variable stack
* frame to a value.
*
* @param varname a <code>String</code> value
* @param value a <code>Thing</code> value
*/
public void setVar(String varname, Thing value) {
setVar(varname, value, -1);
}
/**
* <code>setVar</code> sets a variable to a value in the variable stack
* frame specified by <code>level</code>.
*
* @param varname a <code>String</code> value
* @param value a <code>Thing</code> value
* @param level an <code>int</code> value
*/
public synchronized void setVar(String varname, Thing value, int level) {
Hashtable lookup = getVarhash(level);
// Bump the cache number so that SubstThing.get refetches the
// variable.
cacheversion++;
//if(value == GLOBALREFTHING) System.err.println("flag '"+varname+"' as global on level="+level);
//System.err.println("set local("+level+") var="+varname + ", val="+value.toString());
//#ifdef old
if (lookup.containsKey(varname)) {
Thing oldval = (Thing) lookup.get(varname);
/* In order to make the 'global' command work, we check
* and see if the previous 'inhabitant' of the hashtable
* had its global flag set. If that's the case, then we
* set the variable both at the local level, and at the
* global level. */
if (oldval.global && level != 0) {
value.global = true;
Hashtable globalhash = getVarhash(0);
globalhash.put(varname, value);
}
}
lookup.put(varname, value);
//#else
if (value.isLiteral()) {
try {
Thing copy = value.deepcopy();
value = copy;
} catch (HeclException he) {
/* This isn't going to happen - we're dealing with a