public
Description: A Nu and Objective-C wrapper for John Ousterhout's Tool Command Language (Tcl).
Homepage: http://programming.nu
Clone URL: git://github.com/timburks/nutcl.git
nutcl / objc / Tcl.m
100644 241 lines (214 sloc) 7.317 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
/*!
@file Tcl.m
@discussion Objective-C wrapper for the Tcl interpreter.
@copyright Copyright (c) 2008 Neon Design Technology, Inc.
 
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.
*/
 
#import <Foundation/Foundation.h>
#import <readline/readline.h>
#import <tcl.h>
 
static void freeObjC(Tcl_Obj *objPtr)
{
    id object = objPtr->internalRep.otherValuePtr;
    [object release];
}
 
static void dupObjC(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr)
{
    dupPtr->internalRep.otherValuePtr = srcPtr->internalRep.otherValuePtr;
    id object = srcPtr->internalRep.otherValuePtr;
    [object retain];
}
 
static void updateStringObjC (Tcl_Obj *objPtr)
{
    char *string;
    int length = asprintf(&string, "obj-%p", objPtr->internalRep.otherValuePtr);
    if (!length) {
        NSLog(@"out of memory");
        exit(-1);
    }
    length++;
    objPtr->bytes = Tcl_Alloc(length);
    strcpy(objPtr->bytes, string);
    objPtr->length = length;
    free(string);
}
 
static Tcl_ObjType tclObjCType =
{
    "object", /* name */
    freeObjC, /* freeIntRepProc */
    dupObjC, /* dupIntRepProc */
    updateStringObjC, /* updateStringProc */
    NULL /* setFromAnyProc */
};
 
// The TclCommand is the base class for commands to be added to the interpreter.
@interface TclCommand : NSObject
{
}
 
// override main: to implement a Tcl Command.
- (id) main:(NSArray *) arguments;
@end
 
@implementation TclCommand
- (id) main:(NSArray *) arguments
{
    [NSException raise:@"InvalidTclCommand"
        format:@"Please inherit from the TclCommand class and override main: to create command handlers."];
    return nil;
}
 
@end
 
// Create one of these to get a Tcl interpreter.
@interface TclInterpreter : NSObject
{
    Tcl_Interp *interp;
}
 
@end
 
//typedef int (Tcl_ObjCmdProc) _ANSI_ARGS_((ClientData clientData,
//Tcl_Interp *interp, int objc, struct Tcl_Obj * CONST * objv));
 
int TclCommandHandler(ClientData clientData, Tcl_Interp *interp, int objc, struct Tcl_Obj *objv[])
{
    NSMutableArray *arguments = [NSMutableArray array];
    int i;
    for(i = 0; i < objc; i++) {
        Tcl_Obj *obj = objv[i];
        if (obj->typePtr == &tclObjCType) {
            //NSLog(@"passing object as argument %d", i);
            [arguments addObject:obj->internalRep.otherValuePtr];
        }
        else if (obj->typePtr == Tcl_GetObjType("int")) {
            int argInt;
            Tcl_GetIntFromObj(interp, obj, &argInt);
            [arguments addObject:[NSNumber numberWithInt:argInt]];
        }
        else if (obj->typePtr == Tcl_GetObjType("double")) {
            double argDouble;
            Tcl_GetDoubleFromObj(interp, obj, &argDouble);
            [arguments addObject:[NSNumber numberWithDouble:argDouble]];
        }
        else {
            int argLength;
            const char *argString = Tcl_GetStringFromObj(obj, &argLength);
            //NSLog(@"passing string %s as argument %d", argString, i);
            [arguments addObject:[NSString stringWithCString:argString encoding:NSUTF8StringEncoding]];
        }
    }
    TclCommand *command = (TclCommand *) clientData;
    @try
    {
        id result = [command main:arguments];
        if ([result isKindOfClass:[NSString class]]) {
            Tcl_SetResult(interp, (char *) [result cStringUsingEncoding:NSUTF8StringEncoding], TCL_VOLATILE);
        }
        else if ([result isKindOfClass:[NSNumber class]]) {
            const char *typeCode = [result objCType];
            //NSLog(@"converting number of type %s", typeCode);
            if (!strcmp(typeCode, "i")) {
                Tcl_Obj *tclObj = Tcl_NewIntObj([result intValue]);
                Tcl_SetObjResult(interp, tclObj);
            }
            else {
                Tcl_Obj *tclObj = Tcl_NewDoubleObj([result doubleValue]);
                Tcl_SetObjResult(interp, tclObj);
            }
        }
        else {
            //NSLog(@"returning object as an objc object: %@", [result description]);
            Tcl_Obj *tclObj = Tcl_NewObj();
            tclObj->typePtr = &tclObjCType;
            tclObj->internalRep.otherValuePtr = [result retain];
            tclObj->bytes = 0;
            tclObj->length = 0;
            Tcl_SetObjResult(interp, tclObj);
        }
        return TCL_OK;
    }
    @catch(id exception) {
        return TCL_ERROR;
    }
}
 
void TclCommandRelease(ClientData clientData)
{
    TclCommand *command = (TclCommand *) clientData;
    [command release];
}
 
@implementation TclInterpreter
 
- (TclInterpreter *) init
{
    [super init];
    interp = Tcl_CreateInterp();
    Tcl_RegisterObjType(&tclObjCType);
    return self;
}
 
- (void) dealloc
{
    Tcl_DeleteInterp(interp);
    [super dealloc];
}
 
- (NSString *) eval:(NSString *) script
{
    int resultCode = Tcl_Eval(interp, [script cStringUsingEncoding:NSUTF8StringEncoding]);
    switch (resultCode) {
        case TCL_OK:
        {
            return [NSString stringWithCString:Tcl_GetStringResult(interp) encoding:NSUTF8StringEncoding];
        }
        case TCL_ERROR:
        {
            return [NSString stringWithFormat:@"error: %s", Tcl_GetStringResult(interp)];
        }
        default:
        {
            return [NSString stringWithFormat:@"result code: %d", resultCode];
        }
    }
}
 
- (int) addCommand:(TclCommand *) handler withName:(NSString *) name
{
    [handler retain];
    Tcl_CreateObjCommand(interp,
        [name cStringUsingEncoding:NSUTF8StringEncoding], TclCommandHandler,
        (ClientData) handler, (Tcl_CmdDeleteProc *) TclCommandRelease);
}
 
- (int) interact
{
    printf("Tcl Shell.\n");
    do {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        char *prompt = ("Tcl> ");
        char *line = readline(prompt);
        if (line && *line)
            add_history(line);
        if(!line || !strcmp(line, "quit") || !strcmp(line, "exit")) {
            break;
        }
        else {
            id result = [self eval:[NSString stringWithCString:line encoding:NSUTF8StringEncoding]];
            printf("%s\n", [result cStringUsingEncoding:NSUTF8StringEncoding]);
        }
        [pool release];
    } while(1);
    return 0;
}
 
- (NSString *) types
{
    Tcl_Obj *tclObj = Tcl_NewObj();
    Tcl_AppendAllObjTypes(interp, tclObj);
    int argLength;
    const char *argString = Tcl_GetStringFromObj(tclObj, &argLength);
    return [NSString stringWithCString:argString encoding:NSUTF8StringEncoding];
}
 
- (id) valueForKey:(NSString *) key
{
    const char *value = Tcl_GetVar(interp, [key cStringUsingEncoding:NSUTF8StringEncoding], 0);
    if (value)
        return [NSString stringWithCString:value encoding:NSUTF8StringEncoding];
    else
        return nil;
}
 
@end