/ Check-in [688524166d]
DEMO | DOWNLOAD | DEPLOY | SEARCH
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Release "2.8.17". - Add warn for duplicate "var" (means lots of scripts changed) - A new example CData example module, DBI (uses libdbi). - CData changes: - Output file is now .c instead of .h - C-code now uses #line to help with compile warnings. - Add arg -noline, to turn off #line when debugging. - Add a new "code" section for raw output. - Added options for struct-fields. - Struct-field names starting with "_" are non-visible/configurable. - Comments now stripped only at top of file. - Fix bug for no-arg commands.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:688524166deeea504585fe8ad72860b3468c4867
User & Date: pmacdona 2019-04-10 03:39:08
Context
2019-04-10
22:45
Release "2.8.18" CData: fix config memory handling. check-in: 2ea4655166 user: pmacdona tags: trunk
03:39
Release "2.8.17". - Add warn for duplicate "var" (means lots of scripts changed) - A new example CData example module, DBI (uses libdbi). - CData changes: - Output file is now .c instead of .h - C-code now uses #line to help with compile warnings. - Add arg -noline, to turn off #line when debugging. - Add a new "code" section for raw output. - Added options for struct-fields. - Struct-field names starting with "_" are non-visible/configurable. - Comments now stripped only at top of file. - Fix bug for no-arg commands. check-in: 688524166d user: pmacdona tags: trunk
2019-04-08
02:01
Release "2.8.16" Cleanup new module info/status. check-in: 26a9652bfa user: pmacdona tags: trunk
Changes

Added DBI/DBI.jsc.



































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#!/usr/local/bin/jsish -c %s
// The libDBI object.  Create with "new DBI()"

code Header = {
#include <dbi/dbi.h>
};

struct DBI_ = { // Module struct (optional), will be per-interp if no DBI_Data var.
    bool loaded;        // <RO> Module load count.
    int activeCnt;      // Count of active objects.
    int newCnt;         // Total number of new.
    int init;           // is init
    dbi_inst _dbi;      //  db instance
};

struct DBI = {              // Per-object struct
    Jsi_Interp* interp;     // Note: must add interp field for object command.
    DBI_* _;                // Ptr to DBI_ defined above
    const char* driver;     // <IO> Name of driver (sqlite)
    const char* sqlite_dbdir;// File path: for sqlite
    const char* username;   // Userid for login
    const char* password;   // Password for login
    const char* dbname;     // Database
    const char* host;       // Hostname
    const char* encoding;   // Char encoding (UTF-8)
    int port;               // Timeout.
    int sqlite_timeout;     // Timeout for sqlite.
    int timeout;            // Timeout.
    int version;
    bool isopen;            // <RO> Is database connection open.
    OBJ drvOpts;            // Other driver options.
    FUNC callback;          // <IO; FUNC(str:string, id:number)> Callback function for queries.
    dbi_conn  _db;          // The database connection
    int _idx;
    Jsi_Hash* _resHash;
};

struct DBI_toArray = {
    double Max;
    int Cnt;
};

struct DBI_eval = {
    double Max;
    int Cnt;
};
        
struct DBI_id = {
    int id;
    Jsi_HashEntry* _hPtr;
    dbi_result _res;
    DBI* _cmdPtr;
    bool onrecord;
    int resultCount;
    int fieldCount;
    short* _fieldTypes;
    char** _fieldNames;
};

vars DBIVars = {
    DBI_eval DBI_eval_Data;
    DBI_ DBI_Data; // ie. Module struct is not per-interp.
};

extension DBI = { // Extension to create a DBI object command.

    // Anything outside of a 'function' definition is C-code.
    #include "DBIinc.c"
    
    function _() {
        /* C code for Init/Done */
        _->init += (isRelease?-1:1);
        if (isRelease) {
            if (_->init == 0)
                dbi_shutdown_r(_->_dbi);
            puts("Unloading DBI");
        } else {
            if (_->init==1)
                dbi_initialize_r(NULL, &_->_dbi);
            puts("Loading DBI");
        }
    }
    
    function ~() {
        /* C code for Object free */
        puts("CLOSING");
        cmdPtr->_->activeCnt--;
        if (cmdPtr->_resHash)
            Jsi_HashDelete(cmdPtr->_resHash);
        if (cmdPtr->_db)
            dbi_conn_close(cmdPtr->_db);
    }
    
    function DBI(options:object=void):userobj { // DBI constructor
        /* C code. */
        Jsi_RC rc = JSI_OK;
        cmdPtr->interp = interp;
        cmdPtr->version = LIBDBI_VERSION;
        if (!cmdPtr->driver)
            cmdPtr->driver = "sqlite";
        cmdPtr->_db = dbi_conn_new_r( cmdPtr->driver, cmdPtr->_->_dbi );
        if (!cmdPtr->_db)
            return Jsi_LogError("connection failed");
        const char *msg = "N/A";
#define MYDBI_OPT_SET(name,typ) \
        if (cmdPtr->name) \
            if (dbi_conn_set_option##typ( cmdPtr->_db, #name, cmdPtr->name )) { \
                msg = #name; \
                goto bail; \
            }
                
        MYDBI_OPT_SET(username,)
        MYDBI_OPT_SET(password,)
        MYDBI_OPT_SET(dbname,)
        MYDBI_OPT_SET(encoding,)
        MYDBI_OPT_SET(host,)
        MYDBI_OPT_SET(sqlite_dbdir,)
        MYDBI_OPT_SET(sqlite_timeout,_numeric)
        MYDBI_OPT_SET(timeout,_numeric)
        MYDBI_OPT_SET(port,_numeric)
        
        if (cmdPtr->drvOpts) {
            Jsi_Value *dargs = cmdPtr->drvOpts;
            Jsi_TreeEntry *tPtr;
            Jsi_TreeSearch search;
            Jsi_Tree *tp = Jsi_TreeFromValue(interp, dargs);
            if (!tp)
                goto bail;
            
            for (tPtr = Jsi_TreeSearchFirst(tp, &search, 0, NULL);
                tPtr != NULL; tPtr = Jsi_TreeSearchNext(&search)) {
                const char *arg =(char*) Jsi_TreeKeyGet(tPtr);
                Jsi_Value *optval = (Jsi_Value*)Jsi_TreeValueGet(tPtr);
                
                if( Jsi_ValueIsString(interp, optval) )
                {
                    // Set as string option:
                    const char *vstr = Jsi_ValueString(interp, optval, 0);
                    if (dbi_conn_set_option( cmdPtr->_db, arg, vstr ))
                        rc = Jsi_LogWarn("option set failed: ", arg);
                }
                else if( Jsi_ValueIsNumber(interp, optval) )
                {
                    // Set as numeric option:
                    int vnum = Jsi_ValueToNumberInt(interp, optval, 1);
                    if (dbi_conn_set_option_numeric( cmdPtr->_db, arg, vnum ))
                        rc = Jsi_LogWarn("option set failed: ", arg);
                }
                else
                    rc = Jsi_LogWarn("expected int or string");
            }
            Jsi_TreeSearchDone(&search);
            if (rc != JSI_OK)
                goto bail;
        }
        cmdPtr->_resHash = Jsi_HashNew(interp, JSI_KEYS_ONEWORD, DBI_IdErase);
        cmdPtr->_->newCnt++;
        cmdPtr->_->activeCnt++;
        return JSI_OK;
bail:
        return Jsi_LogError("failed to create DBI: %s", msg);
    }

    function conf(options:object|string=void):any { // Function to configure DBI options
        /* C code. */
    }

    function begin():boolean { // Open a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_begin( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function commit():boolean { // Commit a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_commit( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function rollback():boolean { // Rollback a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_rollback( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function open():boolean { // Open connection
        /* C-code. */
        bool b = (0 == dbi_conn_connect(cmdPtr->_db));
        cmdPtr->isopen = b;
        RETURN(b);
    }
    
    function error():object { // Return the last error on this connection
        /* C-code. */
        const char *errstr;
        int errnum = dbi_conn_error(cmdPtr->_db, &errstr);
        Jsi_Obj *nobj = Jsi_ObjNew(interp);
        Jsi_ValueMakeObject(interp, ret, nobj);
        Jsi_ValueInsert(interp, *ret, "number", Jsi_ValueNewBlob(interp, (uchar*)errstr, Jsi_Strlen(errstr)), 0);
        Jsi_ValueInsert(interp, *ret, "text", Jsi_ValueNewNumber(interp, errnum), 0);
        return JSI_OK;
    }
    
    function use(dbname:string):boolean { // Use a database 
        int rval = dbi_conn_select_db(cmdPtr->_db, dbname);
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }

    function lastseq(seqname:string=void):number { // Fetch the last sequence ID assigned if supported
        const char *seqname = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
        Jsi_Number n = dbi_conn_sequence_last(cmdPtr->_db, seqname);
        RETURN(n);
    }
    
    function nextseq(seqname:string=void):number { // Fetch the next sequence ID if supported
        const char *seqname = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
        Jsi_Number n = dbi_conn_sequence_next(cmdPtr->_db, seqname);
        RETURN(n);
    }
    
    function check():boolean { // Check the server connection
        bool b = dbi_conn_ping(cmdPtr->_db);
        RETURN(b);
    }

    function escape(vstr:string):string { // Escape a string
        int bufLength;
        char *quoted;
        const char *unquoted = Jsi_ValueArrayIndexToStr(interp, args, 0, &bufLength);
        int newLength = dbi_conn_quote_binary_copy(cmdPtr->_db, (const unsigned char *)unquoted,
            bufLength, (unsigned char **)&quoted );
        Jsi_ValueMakeBlob(interp, ret, (unsigned char *)quoted, newLength);
        return JSI_OK;
    }
    
    function query(query:string, params:array=void):number { // Run query and return id
        /* C-code. */
        int qlen;
        Jsi_Value *params = Jsi_ValueArrayIndex(interp, args, 1);
        const char *qstr = Jsi_ValueArrayIndexToStr(interp, args, 0, &qlen);
        Jsi_DString dStr = {};
        if (!params || !Jsi_ValueGetLength(interp, params))
            Jsi_DSAppendLen(&dStr, qstr, qlen);
        else
            if (DBI_AddArgs(cmdPtr, &dStr, qstr, qlen, params) != JSI_OK)
                return JSI_ERROR;

        dbi_result res = dbi_conn_query( cmdPtr->_db, Jsi_DSValue(&dStr));
        Jsi_DSFree(&dStr);
        if (!res) {
            const char *msg = "N/A";
            int num = dbi_conn_error(cmdPtr->_db, &msg);
            return Jsi_LogError("query failure: %d %s", num, msg);
        }
        DBI_id *pss = DBI_IdGet(cmdPtr, -1, 1);
        if (!pss) {
            dbi_result_free(res);
            return JSI_ERROR;
        }

        pss->onrecord = dbi_result_first_row(res);
        pss->resultCount = dbi_result_get_numrows( res );
        pss->fieldCount = dbi_result_get_numfields( res );
        pss->_fieldTypes = (short*)Jsi_Calloc( pss->fieldCount, sizeof(unsigned short) );
        pss->_fieldNames = (char**)Jsi_Calloc( pss->fieldCount, sizeof(char *) );
        for( int x=0; x < pss->fieldCount; x++ )
        {
            const char *fieldname = dbi_result_get_field_name( res, x+1 );
            pss->_fieldTypes[x] = dbi_result_get_field_type_idx( res, x+1 );
            pss->_fieldNames[x] = (char*)Jsi_KeyAdd(interp, fieldname);
        }

        pss->_res = res;
        int id = pss->id;
        RETURN(id);
    }
    
    function ids():array { // Return list of query ids
        /* C code. */
        Jsi_DString dStr;
        Jsi_DSInit(&dStr);
        Jsi_DSAppend(&dStr, "{", NULL);
        DBI_id *pss = NULL;
        Jsi_HashEntry *hPtr;
        Jsi_HashSearch cursor;
        int cnt = 0;
        for (hPtr = Jsi_HashSearchFirst(cmdPtr->_resHash, &cursor);
            hPtr != NULL; hPtr = Jsi_HashSearchNext(&cursor)) {
            pss = (DBI_id *)Jsi_HashValueGet(hPtr);
            Jsi_DSPrintf(&dStr, "%s%d", cnt++?",":"", pss->id);
        }
        Jsi_DSAppend(&dStr, "}", NULL);
        Jsi_RC rc = Jsi_JSONParse(interp, Jsi_DSValue(&dStr), ret, 0);
        Jsi_DSFree(&dStr);
        return rc;
    }

    function idconf(id:number, options:object|string=void):any { // Function to configure query id options
        /* C code. */
        return JSI_OK;
    }

    function idseek(id:number, row:number):boolean { // Seek to a row
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)
            return JSI_ERROR;
        bool b = pss->onrecord = dbi_result_seek_row(pss->_res, row+1);
        RETURN(b);
    }

    function idcolumn(id:number, column:number):any { // Fetch a single column value
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)
            return JSI_ERROR;
        return DBI_IdValue(interp, pss, ret, column);
    }
    
    function idrow(id:number):any { // Fetch a row
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)
            return JSI_ERROR;
        Jsi_Obj *res = Jsi_ObjNew(interp);
        Jsi_ValueMakeObject(interp, ret, res);
        //Jsi_IncrRefCount(interp, *ret);
        int i;
        for (i=0; i<pss->fieldCount; i++) {
            Jsi_Value *v = Jsi_ValueNew(interp);
            if (JSI_OK != DBI_IdValue(interp, pss, &v, i))
                Jsi_ValueMakeNull(interp, &v);
            Jsi_ObjInsert(interp, res, pss->_fieldNames[i], v, JSI_OM_READONLY );
        }
        return JSI_OK;
    }

    function idfree(id:number):void { // Delete query id
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)
            return JSI_ERROR;
        Jsi_HashEntryDelete(pss->_hPtr);
        return JSI_OK;
    }


};

Added DBI/DBIinc.c.











































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#include <ctype.h>

// Must define this IdGet function when using "idconf".
static DBI_id* DBI_IdGet(DBI *cmdPtr, int id, bool create) {
    Jsi_HashEntry *hPtr;
    Jsi_Interp *interp = interp;
    DBI_id* pss;
    bool isNew;
    if (id<0)
        id = ++cmdPtr->_idx;
    if (create)
        hPtr = Jsi_HashEntryNew(cmdPtr->_resHash, (void*)(long)id, &isNew);
    else
        hPtr = Jsi_HashEntryFind(cmdPtr->_resHash, (void*)(long)id);
    if (!hPtr) {
        Jsi_LogError("failed to %s id", (create?"create":"get"));
        return NULL;
    }
    if (create == 0 || isNew == 0) {
        pss = (DBI_id*)Jsi_HashValueGet(hPtr);
    } else {
        pss = (DBI_id*)Jsi_Calloc(1, sizeof(*pss));
        pss->_hPtr = hPtr;
        Jsi_HashValueSet(hPtr, pss);
        pss->_cmdPtr = cmdPtr;
        pss->id = id;
    }
    return pss;
}

static Jsi_RC DBI_IdErase(Jsi_Interp *interp, Jsi_HashEntry* hPtr, void *ptr) {
    DBI_id *pss = (DBI_id *)ptr;
    if (pss) {
        printf("FREEPSS: %d\n", pss->id);
        pss->_hPtr = NULL;
        if (pss->_res)
            dbi_result_free(pss->_res);
        if (pss->_fieldTypes)
            Jsi_Free(pss->_fieldTypes);
        if (pss->_fieldNames)
            Jsi_Free(pss->_fieldNames);
        Jsi_Free(pss);
        //sockDeletePss(pss);
    }
    return JSI_OK;
}

static Jsi_RC DBI_AddArgs(DBI *cmdPtr, Jsi_DString *dStr, const char *query, int qlen, Jsi_Value *args) {
    Jsi_Interp *interp = cmdPtr->interp;
    int n, idx, len, argc = Jsi_ValueGetLength(interp, args);
    Jsi_Value *val;
    char *str, *cp, *qp = (char*)query;
    
    while ((cp = Jsi_Strchr(qp, '%'))) {
        if (cp[1] == '%') {
            Jsi_DSAppendLen(dStr, qp, cp-qp+1);
            qp = cp+2;
            continue;
        }
        Jsi_DSAppendLen(dStr, qp, cp-qp);
        n = 0;
        while (isdigit(cp[n])) n++;
        idx = atoi(cp+1);
        qp = cp + n + 2;
        if( idx <= 0 || idx > argc || !(val = Jsi_ValueArrayIndex(interp, args, idx-1)))
            return Jsi_LogError("failure in DBI_AddArgs");

        if (Jsi_ValueIsNumber(interp, val)) {
            Jsi_Number num;
            Jsi_ValueGetNumber(interp, val, &num);
            Jsi_DSPrintf(dStr, "%g", num);
        } else if ((str = (char*)Jsi_ValueToString(interp, val, &len)) && len) {
            uchar quoted[len*2+100], *qp = quoted;
            len = dbi_conn_quote_binary_copy( cmdPtr->_db, (const uchar*)str, len, &qp );
            if( len <= 0 )
                return Jsi_LogError("quote failure in DBI_AddArgs");
            Jsi_DSAppendLen(dStr, (char*)qp, len);
            free(qp);
        } else
            Jsi_DSAppend(dStr, "null", 0);
    }
    Jsi_DSAppend(dStr, qp, 0);
    return JSI_OK;
}

static Jsi_RC DBI_IdValue(Jsi_Interp *interp, DBI_id *pss, Jsi_Value **ret, int idx)
{
    if( idx < 0 || idx >= pss->fieldCount || !pss->onrecord )
        return Jsi_LogError("index out of range");
    int fidx = pss->_fieldTypes[idx];
    char *str = NULL;

    if (dbi_result_field_is_null_idx(pss->_res, idx+1))
        Jsi_ValueMakeNull(interp, ret);
    else
        switch (fidx)
        {
            case DBI_TYPE_DATETIME:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_datetime_idx( pss->_res, idx+1));
                break;
            case DBI_TYPE_INTEGER:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_longlong_idx(pss->_res, idx+1 ));
                break;
            case DBI_TYPE_DECIMAL:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_double_idx( pss->_res, idx+1 ));
                break;
            case DBI_TYPE_BINARY:
                str = (char*)dbi_result_get_binary_copy_idx( pss->_res, idx+1 );;
            case DBI_TYPE_STRING:
                if (!str) 
                    str = dbi_result_get_string_copy_idx( pss->_res, idx+1 );
                Jsi_ValueMakeBlob(interp, ret, (unsigned char *)str,
                    dbi_result_get_field_length_idx(pss->_res, idx+1));
        }

    return JSI_OK;
}

Added DBI/Makefile.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
CDCMD=../jsish -c
#CDCMD=../jsish ../lib/Jsi_CData.jsi
#CDOPTS= -noline true
#CC=cc -fsanitize=address 

DBI.so: DBI.c
	$(CC)  `$(CDCMD) -cflags true DBI.so` -ldbi

DBI.c: DBI.jsc DBIinc.c
	$(CDCMD) $(CDOPTS)  DBI.jsc

test:
	../jsish --U dbi_mysql.jsi

Added DBI/dbi_mysql.jsi.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
#!/usr/bin/env jsish

require('DBI');

var opts = { driver:'mysql', username:'jsish', password:'abc', dbname:'jsitest', host:'localhost', port:3306  }; 
//var opts = { driver:'sqlite', dbname:'test2.db', sqlite_dbdir:'/tmp' }; 

var id, db = new DBI(opts);
;db.open();
;db.check();
;db.conf();

;// db.conf({driver:'sqlite'});
;// db.conf({isopen:false});

;id = db.query('SELECT * FROM test1;');
;db.idconf(id);
;db.idcolumn(id,0);
;db.idrow(id);

;id = db.query('SELECT * FROM test1 WHERE last=%1;', ['Box']);
;db.ids();
;db.idconf(id);
;db.idrow(id);
;db.idseek(id,3);
;db.idrow(id);
;db.idfree(id);

delete db;

/*
=!EXPECTSTART!=
db.open() ==> true
db.check() ==> true
db.conf() ==> { callback:null, dbname:"jsitest", driver:"mysql", drvOpts:null, encoding:null, host:"localhost", isopen:true, password:"abc", port:3306, sqlite_dbdir:null, sqlite_timeout:0, timeout:0, username:"jsish", version:900 }
db.conf({driver:'sqlite'}) ==>
PASS!: err = Error can not update option: "driver"
db.conf({isopen:false}) ==>
PASS!: err = Error option is readonly: "isopen"
id = db.query('SELECT * FROM test1;') ==> 1
db.idconf(id) ==> { fieldCount:3, id:1, onrecord:true, resultCount:26 }
db.idcolumn(id,0) ==> 44
db.idrow(id) ==> { id:44, last:"Box", name:"Barry" }
id = db.query('SELECT * FROM test1 WHERE last=%1;', ['Box']) ==> 2
db.ids() ==> { 1:2 }
db.idconf(id) ==> { fieldCount:3, id:2, onrecord:true, resultCount:26 }
db.idrow(id) ==> { id:44, last:"Box", name:"Barry" }
db.idseek(id,3) ==> true
db.idrow(id) ==> { id:44, last:"Box", name:"Barry" }
db.idfree(id) ==> undefined
=!EXPECTEND!=
*/

Changes to Makefile.

330
331
332
333
334
335
336



337
338
339
340
341
342
343
	$(CC) $(CFLAGS) $(OBJS) -Wl,--export-dynamic  -shared -o $@ $(LDFLAGS)

# Supported modules (unix only)
mysql: MySql$(SHLEXT)
sqlite: Sqlite$(SHLEXT)
websocket: WebSocket$(SHLEXT)




MySql$(SHLEXT): src/jsiMySql.c
	-$(CC) $(CFLAGS) $(PROGFLAGS) $(MODFLAGS) -DJSI__ISMODULE=1 src/jsiMySql.c $(SLIBCFLAGS) -o $@ $(LDFLAGS) -lmysqlclient

Sqlite$(SHLEXT): src/jsiSqlite.c
	-$(CC) $(CFLAGS) $(PROGFLAGS) $(MODFLAGS) -DJSI__ISMODULE=1 src/jsiSqlite.c $(SLIBCFLAGS) -o $@ $(LDFLAGS) -lsqlite3
	
WebSocket$(SHLEXT): src/jsiWebSocket.c







>
>
>







330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
	$(CC) $(CFLAGS) $(OBJS) -Wl,--export-dynamic  -shared -o $@ $(LDFLAGS)

# Supported modules (unix only)
mysql: MySql$(SHLEXT)
sqlite: Sqlite$(SHLEXT)
websocket: WebSocket$(SHLEXT)

dbi:
	(cd src && $(CC) `../jsish -c -cflags true DBI.so`)
	
MySql$(SHLEXT): src/jsiMySql.c
	-$(CC) $(CFLAGS) $(PROGFLAGS) $(MODFLAGS) -DJSI__ISMODULE=1 src/jsiMySql.c $(SLIBCFLAGS) -o $@ $(LDFLAGS) -lmysqlclient

Sqlite$(SHLEXT): src/jsiSqlite.c
	-$(CC) $(CFLAGS) $(PROGFLAGS) $(MODFLAGS) -DJSI__ISMODULE=1 src/jsiSqlite.c $(SLIBCFLAGS) -o $@ $(LDFLAGS) -lsqlite3
	
WebSocket$(SHLEXT): src/jsiWebSocket.c

Changes to c-demos/cdata/Car.jsc.

1
2







3
4
5
6
7
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
..
44
45
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/local/bin/jsish -c %s
// Car object.  Created with "new Car()"








struct Car_ = { // Module struct (optional), will be per-interp if no Car_Data var.
    bool loaded;
    int activeCnt; // Count of active objects.
    int newCnt;  // Total number of new.
};

struct Car = { // Per-object struct
    Jsi_Interp* interp; // Note: must add interp field for object command.
    int maxSpeed=120;
    int gear;
    int shiftCnt;
    uchar* myPtr; // NOWARN: Stuff

    Car_* _;    // Ptr to Car_ defined above
};


struct Car_fix = {
    double Max;
    int Cnt;
................................................................................
    
    function _() {
        /* C code for Init/Done */
        if (CarInitDone(interp, isRelease, _) != JSI_OK)
            return JSI_ERROR;
    }
    
    function ~() {
        /* C code for Object free */
        cmdPtr->_->activeCnt--;

        Jsi_Free(cmdPtr->myPtr);
    }
    
    function Car(options:object=void):userobj { // Car constructor
        /* C code. */
        cmdPtr->myPtr = (uchar*)Jsi_Calloc(1, 100);
        cmdPtr->_->newCnt++;
        cmdPtr->_->activeCnt++;
        return JSI_OK;
    }

    function conf(options:object|string=void):any { // Function to configure Car options
        /* C code. */


>
>
>
>
>
>
>












|
>







 







|


>
|




|







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
..
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/local/bin/jsish -c %s
// Car object.  Created with "new Car()"
// Note: leading #! and comments get stripped.

enum LoadType = {
    Light,
    Medium,
    Heavy
};

struct Car_ = { // Module struct (optional), will be per-interp if no Car_Data var.
    bool loaded;
    int activeCnt; // Count of active objects.
    int newCnt;  // Total number of new.
};

struct Car = { // Per-object struct
    Jsi_Interp* interp; // Note: must add interp field for object command.
    int maxSpeed=120;
    int gear;
    int shiftCnt;
    uchar* _myPtr; // Stuff
    FUNC callback;
    Car_* _;    // Ptr to Car_ defined above
};


struct Car_fix = {
    double Max;
    int Cnt;
................................................................................
    
    function _() {
        /* C code for Init/Done */
        if (CarInitDone(interp, isRelease, _) != JSI_OK)
            return JSI_ERROR;
    }
    
    function ~() { // Cleanup
        /* C code for Object free */
        cmdPtr->_->activeCnt--;
        if (cmdPtr->_myPtr)
            Jsi_Free(cmdPtr->_myPtr);
    }
    
    function Car(options:object=void):userobj { // Car constructor
        /* C code. */
        cmdPtr->_myPtr = (uchar*)Jsi_Calloc(1, 100);
        cmdPtr->_->newCnt++;
        cmdPtr->_->activeCnt++;
        return JSI_OK;
    }

    function conf(options:object|string=void):any { // Function to configure Car options
        /* C code. */

Changes to c-demos/cdata/Makefile.

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
OTHER=
CSTRFN=../../lib/Jsi_CData.jsi 
JSISH=../../jsish
#CSTRPP=$(JSISH) $(CSTRFN) 
CSTRPP=$(JSISH) -c
CCGET=$(CSTRPP) -cflags true
DEPS=$(CSTRFN) $(JSIDIR)/jsi.c $(JSIDIR)/jsi.h Makefile
CFILES=demo0.h demo1.h demo2.h demo.c
SHFLAGS= -DJSI_CDATA_SHARED=1 -shared

all: Bee Car Baker Bag Tiny demo

shared: Bee.so Car.so Baker.so Bag.so Tiny.so demo.so

test: shared
	$(JSISH) -u ext_test.jsi
	$(JSISH) -u cdatatest.jsi
	$(JSISH) -u bagtest.jsi
	$(JSISH) -u tinytest.jsi
	$(JSISH) -u demotest.jsi

demo.so: demo.c demo0.h demo1.h demo2.h $(DEPS)
	$(CC) $(CFLAGS) $(SHFLAGS) -x c -o $@ demo.c $(LDFLAGS)

demo: demo.c demo0.h demo1.h demo2.h $(DEPS)
	$(CC) $(CFLAGS) -DJSI_CDATA_MAIN=1 -x c -o $@ demo.c $(LDFLAGS)

demosh: demo
	jsish -z zvfs demo


Tiny: Tiny.h $(DEPS)
	$(CC) `$(CCGET) $@`

Tiny.so: Tiny.h $(DEPS)
	$(CC) `$(CCGET) $@`

Bag: Bag.h $(DEPS)
	$(CC) `$(CCGET) $@`

Bag.so: Bag.h $(DEPS)
	$(CC) `$(CCGET) $@`

Bee: Bee.h $(DEPS)
	$(CC) `$(CCGET) $@`

Bee.so: Bee.h $(DEPS)
	$(CC) `$(CCGET) $@`

Car: Car.h $(DEPS)
	$(CC) `$(CCGET) $@`

Car.so: Car.h $(DEPS)
	$(CC) `$(CCGET) $@`

Carsh: Car
	jsish -z zvfs Car

Baker: Baker.h $(DEPS)
	$(CC) `$(CCGET) $@`

Baker.so: Baker.h $(DEPS)
	$(CC) `$(CCGET) $@`

%.h: %.jsc $(DEPS)
	$(CSTRPP) $<

clean:
	rm -f demo1.h demo2.h demo

depend:
	$(CC) -E -MM $(CFLAGS) $(CFILES) > .depend

-include .depend









|













|


|






|


|


|


|


|


|


|


|





|


|


|



|


|




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
OTHER=
CSTRFN=../../lib/Jsi_CData.jsi 
JSISH=../../jsish
#CSTRPP=$(JSISH) $(CSTRFN) 
CSTRPP=$(JSISH) -c
CCGET=$(CSTRPP) -cflags true
DEPS=$(CSTRFN) $(JSIDIR)/jsi.c $(JSIDIR)/jsi.h Makefile
CFILES=demo0.c demo1.c demo2.c
SHFLAGS= -DJSI_CDATA_SHARED=1 -shared

all: Bee Car Baker Bag Tiny demo

shared: Bee.so Car.so Baker.so Bag.so Tiny.so demo.so

test: shared
	$(JSISH) -u ext_test.jsi
	$(JSISH) -u cdatatest.jsi
	$(JSISH) -u bagtest.jsi
	$(JSISH) -u tinytest.jsi
	$(JSISH) -u demotest.jsi

demo.so: demo.c $(CFILES) $(DEPS)
	$(CC) $(CFLAGS) $(SHFLAGS) -x c -o $@ demo.c $(LDFLAGS)

demo: demo.c $(CFILES) $(DEPS)
	$(CC) $(CFLAGS) -DJSI_CDATA_MAIN=1 -x c -o $@ demo.c $(LDFLAGS)

demosh: demo
	jsish -z zvfs demo


Tiny: Tiny.c $(DEPS)
	$(CC) `$(CCGET) $@`

Tiny.so: Tiny.c $(DEPS)
	$(CC) `$(CCGET) $@`

Bag: Bag.c $(DEPS)
	$(CC) `$(CCGET) $@`

Bag.so: Bag.c $(DEPS)
	$(CC) `$(CCGET) $@`

Bee: Bee.c $(DEPS)
	$(CC) `$(CCGET) $@`

Bee.so: Bee.c $(DEPS)
	$(CC) `$(CCGET) $@`

Car: Car.c $(DEPS)
	$(CC) `$(CCGET) $@`

Car.so: Car.c $(DEPS)
	$(CC) `$(CCGET) $@`

Carsh: Car
	jsish -z zvfs Car

Baker: Baker.c $(DEPS)
	$(CC) `$(CCGET) $@`

Baker.so: Baker.c $(DEPS)
	$(CC) `$(CCGET) $@`

%.c: %.jsc $(DEPS)
	$(CSTRPP) $<

clean:
	rm -f $(CFILES) demo

depend:
	$(CC) -E -MM $(CFLAGS) $(CFILES) demo.c > .depend

-include .depend


Changes to c-demos/cdata/demo.c.

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#define JSI_USE_STUBS 1
#include "jsi.h"
#else
#include "jsiOne.c"
#undef JSI_CDATA_MAIN
#endif
#define JSI_CDATA_IMPL
#include "demo0.h"
#include "demo1.h"
#include "demo2.h"

Jsi_InitProc Jsi_InitDemo;

Jsi_RC Jsi_InitDemo(Jsi_Interp *interp, int release)
{
#if JSI_USE_STUBS
    if (Jsi_StubsInit(interp, 0) != JSI_OK)







|
|
|







3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#define JSI_USE_STUBS 1
#include "jsi.h"
#else
#include "jsiOne.c"
#undef JSI_CDATA_MAIN
#endif
#define JSI_CDATA_IMPL
#include "demo0.c"
#include "demo1.c"
#include "demo2.c"

Jsi_InitProc Jsi_InitDemo;

Jsi_RC Jsi_InitDemo(Jsi_Interp *interp, int release)
{
#if JSI_USE_STUBS
    if (Jsi_StubsInit(interp, 0) != JSI_OK)

Changes to c-demos/cdata/demo0.jsc.

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

enum Bitvals = {
    first,
    second,
    third
};

struct Foo = { // My Foo struct
     // TODO: Parameters for defn.
    <stuff:true>
    Jsi_Sig     sig;
    int         fld1 = 2;   // An int field with default value of 2
    double      val1;       // A float
    int         arr[9];
    int         bit:4;
    uint64_t    bit2:44;







|
<







12
13
14
15
16
17
18
19

20
21
22
23
24
25
26

enum Bitvals = {
    first,
    second,
    third
};

struct Foo = { // My Foo struct.  TODO: Parameters for defn.

    <stuff:true>
    Jsi_Sig     sig;
    int         fld1 = 2;   // An int field with default value of 2
    double      val1;       // A float
    int         arr[9];
    int         bit:4;
    uint64_t    bit2:44;

lib/JsiCompat.jsi became executable.

Changes to lib/Jsi_Archive.jsi.

1

2
3
4
5
6
7
8
#!/usr/bin/env jsish


require('Jsish');

// Run module or main.js from a zip, sqlar or fossil repository.

require('Jsi_Vfs');


>







1
2
3
4
5
6
7
8
9
#!/usr/bin/env jsish
"use strict";

require('Jsish');

// Run module or main.js from a zip, sqlar or fossil repository.

require('Jsi_Vfs');

Changes to lib/Jsi_CData.jsi.

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
..
42
43
44
45
46
47
48

49
50

51
52
53
54
55
56
57
58
..
81
82
83
84
85
86
87
88
89
90
91


92
93
94
95
96
97
98
...
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
...
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
...
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
...
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
...
305
306
307
308
309
310
311
312





313
314
315
316
317
318
319
320
...
325
326
327
328
329
330
331

332
333
334
335
336
337
338
339
...
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
...
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
...
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
...
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
...
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
...
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
...
852
853
854
855
856
857
858
859


860
861
862
863
864
865
866
867
868
...
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
...
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
....
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061






1062
1063
1064
1065
1066
1067
1068
....
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
....
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192




1193
1194
1195
1196

1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256

1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288

1289
1290
1291
1292
1293
1294





1295
1296
1297
1298
1299
1300


1301
1302
1303
1304
1305
1306
1307

1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
....
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
....
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500

require('Jsish');

// A C-API generator for structs, enums, maps, and extensions.

function Jsi_CData(args:array, conf:object=void)
{
    var self = {};
    
    var options = {         // The C-API preprocessor for structs and enums.
        confSuffix  :'',    // Suffix to add to struct used for object config.
        eval        :false, // Evaluate in interp.
        cflags      :false, // Return CFLAGS to compile FILE/FILE.so from .h generated by a .jsc.
        inStr       :'',    // Input string.
        json        :false, // Output json definitions.
        memDebug    :false, // Enable memdebug
        name        :null,  // Name of group

        O           :'',    // Output file, or '-' to return string. Default is FILE.h.
        test        :false, // Test output.
        trace       :false, // Trace output.
        unkType     :true,  // Warn of unknown struct fields self will be ignored.
        varSuffix   :'_Data'// Suffix to add to data used for object config.
    };

    var self = {
        pre:'', pre0:'', pre1:'', out0:'', out1:'', out:'', iout:'',
        init:[], types:'',  structs:'', enums:'', vars:'', cmds:'',
        varnames:[], mapnames:[], cmdnames:[], 
        structmap:{}, enummap:{}, enumzero:{},
        vardefs:'',  siglst:[], varinits:'', mapinits:'', enumIni:{},
        portlst:[], statlst:[], cmddefs:'', cmddef:'',
        enumvals:{}, infiles:[], outFile:null, rootname:null

    };
    var Ex = {asize:0, offs:1, size:2, sig:3};
    var EV = { enum:[], struct:[], vars:[] };

    parseOpts(self, options, conf);

    var defs = {structs:[], enums:[], types:[], vars:[], cmds:[]};
................................................................................


    var typeNameStr = "number string boolean array function object regexp any userobj void null undefined";
    var typeNameList = typeNameStr.split(' ');
    
    var portTypes = 'BOOL,UINT8,UINT16,UINT32,UINT64,INT8,INT16,INT32,INT64,DOUBLE,LDOUBLE,TIME_W,TIME_D,STRBUF';
    var statTypes = 'TIME_T,INT,UINT,LONG,ULONG,SHORT,USHORT,INTPTR,UINTPTR,SIZE_T,'+portTypes;

    var portableTypes = portTypes.split(',');
    var staticTypes = statTypes.split(',');


    function GetBaseType(styp) { //TODO: lookup with info type.
        switch (styp) {
            case 'bool':     return 'BOOL';  case 'uint':     return 'UINT'; 
            case 'int':      return 'INT';   case 'double':   return 'DOUBLE';  
            case 'int8_t':   return 'INT8';  case 'int16_t':  return 'INT16';
            case 'int32_t':  return 'INT32'; case 'int64_t':  return 'INT64';   
            case 'uint8_t':  return 'UINT8'; case 'uint16_t': return 'UINT16';
................................................................................
    
    function GetCflags() {
        var fn = args[0], fne = File.extension(fn), fnr=File.rootname(fn), name=fnr, fnc = fnr;
        if (fn.indexOf('/')>=0)
            throw('file may not have path: '+fn);
        switch (fne) {
            case '.so': fnr += '.so';
            case '.h':
            case '': fnc += '.h'; break;
            default: throw('extension not one of: .so .h ""');
        }


        if (!File.readable(fnc))
            LogWarn('file not found: '+fnc);
        var s = '-g -Og -O0 -Wall -fPIC -DJSI__SQLITE=1'
            + ' -DJSI__READLINE=1 -fno-diagnostics-show-caret -Wc++-compat'
            + ' -Wwrite-strings -DJSI_CDATA_MAIN=1 -x c -rdynamic';
        if (args.length<=1 && self.memDebug)
            s += ' -DJSI__MEMDEBUG=1';
................................................................................
        if (isWS)
            s += format(' -DJSI__WEBSOCKET=1 -I%s/src/lib  -I%s/src/build -I%s/unix -I%s/build/unix ', wDir, wDir, wDir, wDir);
        s += ' -o '+fnr+' '+fnc;
        if (args.length>1) {
            s += ' -DCDATA_MULTI_INC=1 -DCDATA_JSI_C_MAIN_'+name;
            var aalst = [], arst = args.slice(1);
            for (var al of arst) {
                if (File.extension(al) == '.h')
                    aalst.push(File.rootname(al));
            }
            var pnl = name;
            for (var al of aalst) {
                s += ' -DCDATA_MODINIT_CHAIN_'+pnl+'=Jsi_Init'+al;
                pnl = al;
            }
            s += ' '+arst.join(' ');
            if (aalst.length && fne == '.so')
                throw("can not add .h files to a .so build");
        }
        s += ' -lm';
        if (fne === '.so')
            s += ' -shared -DJSI_CDATA_SHARED=1';
        if (isWS)
            s += ' -L '+wDir+'/build/unix/ -lwebsockets';
         var sDir = pDir + '/sqlite';
................................................................................
        var tlst = typ.split('|');
        var i = -1;
        for (i = 0; i<tlst.length; i++)
            if (typeNameList.indexOf(tlst[i]) < 0)
                throw prefix+ " type unknown '"+tlst[i]+'" not one of: '+typeNameStr;
        return tlst;
    }






















    function GenType(def) {
        // TODO
        //self.types += "  { \""+name+"\", \""+label+"\", 0, sizeof(name), \""+fmt+"\", "+cformat+", },\n";
    };

    // Define an enum
    function GenEnum(def) {
        // TODO: generate lookup string table. Also enhance Jsi_Opt_SwitchEnum to support more than just 0,1,2...
        LogDebug("def=",def);
        var flags = 0;
        with (def) {
            self.portlst.push(name);
            self.statlst.push(name);
            if (label)
                self.pre0 += "/* "+label+" */\n";

            self.pre0 += "typedef enum "+name+" {\n";
            //self.pre += "  ";
            var eName = name+"_Enum"; "jsi_csitems_"+name;
            var evDef = {name:name}, evItems = [];
            self.enummap[name] = eName;
            self.enums += "    {.sig=JSI_SIG_OPTS_ENUM, .id=JSI_OPTION_CUSTOM, .name=\""+name+"\""
                +", .offset="+flds.length+", .size=sizeof(enum "+name+"), .init={}"
                + ", .help=\""+(label?label:'')+"\""
................................................................................
            self.pre0 += "} "+name+";\n\n";
            EV.enum.push([evDef, evItems]);
        }
    }
    
    // Define a struct
    function GenStruct(def) {
        var sc = '', fieldstr = '', name = def.name, definit = def.init, sig = 0, cnt = 0, aspre = '';
        var hassig = false;
        if (!def.Array)
            def.Array = 0;
        var evDef = {name:name}, evItems = [];
         if (def.label) {
            sc += "/* "+def.label+" */\n";
            evDef.help = def.label;
        } else {
            def.label = '';
        }

        sc += "typedef struct "+name+" {\n";
        var bsgets=[], bscnt = 0, inits = [], hasinit = 0, fcnt = 0, flags = 0, bsget = 0,
            crc = 0, scrc = '', port=1, stat=1, portconds='';
        // self.out( [subst -novariables fields]
        for (var ii in def.flds) {
            var f = def.flds[ii];
            if (!f)
                continue;
            LogTrace("f:",f);
            var type = f.id, fname = f.name, ofname = fname, fflags = f.flags, st = GetBaseType(type);

            var evIt = {name:fname, type:f.id};


            //if (fflags)
            //    evIt.flags=fflags;
            if (f.label)
                evIt.help = f.label;
            //if (f.flags)
            //    evIt.flags = f.flags;
            if (type == 'Jsi_Sig')
                st = 'UINT32';
            if (scrc === '')
                scrc += ',';
            scrc += type;
            var des = '',
                fdescr = (f.label?f.label:'');
            if (!cnt++ && fname == 'sig') {
                fflags += '|JSI_OPT_FMT_HEX';
                if (!f.bit && !f.asize) {
                    hassig = true; sig = f.init;
                }
................................................................................
                option = bscnt++;
                bitsiz = f.bit;
                bsgets.push([f.name, type+" "+f.name+":"+bitsiz,type, f.idx]);
                bsiz = Math.floor((f.bit+7)/8);
                bsizstr = ':'+f.bit;
            } else {
                offset = "Jsi_Offset("+name+","+fname+")";
                bsiz = "sizeof("+type+")";
                bitsiz = "8*"+bsiz;
                if (stat) {
                    if ((!st || staticTypes.indexOf(st)<0) && self.statlst.indexOf(type)<0)
                        stat = 0;
                }
                if (!stat)
                    port =0;
                else if (port) {
                    if ((!st || portableTypes.indexOf(st)<0) && self.portlst.indexOf(type)<0)
                        port = 0;
                }
            }




            if (f.asize) {
                bsizstr = '['+f.asize+']';
                scrc += bsizstr;
            }
            var sinit = 0, csinit = 0;
            if (self.enumIni[type] !== undefined)
                sinit = self.enumIni[type];
................................................................................
            var otype = st;
            
            var issubopt = (self.structmap[type] !== undefined);
            var isenum = (self.enummap[type] !== undefined);
            if (isenum && !self.enumzero[type])
                LogWarn(name, '.', fname, ': enum ', type, "does not define a zero value");
            var bdata = 0;
            var rest = ', .custom=0, .data=0';





            if (!st) {
                otype = st = 'CUSTOM';
                if (issubopt) {
                    LogTest("SUB:", type);
                    rest = ', .custom=Jsi_Opt_SwitchSuboption, .data=(void*)'+self.structmap[type];
                } else if (isenum) {
                    rest = ', .custom=Jsi_Opt_Switch'+(f.bitset?'Bitset':'Enum')+', .data=(void*)'+self.enummap[type];
                    fflags += '|JSI_OPT_ENUM_SPEC';
................................................................................
                    if (self.unkType && !f.nowarn && type !== "Jsi_Interp*" && type !== "void*") {
                        var tvlen = type.length;
                        if (type[tvlen-1] !== '*' || type[tvlen-2] !== '_' || !self.structmap[type.substr(0,tvlen-2)])
                            puts('ignoring unknown type "'+type+'": ' +name+'.'+fname);
                    }
                }
            }

            if (f.asize) {
                evIt.size = f.asize;
                if (f.bit)
                    throw("array of bits unsupported: "+name+'.'+fname);
                if (isenum)
                    throw("array of enums unsupported: "+name+'.'+fname);
                if (self.structmap[type]) {
                    csinit = "(uchar*)&jsi_csini_data_"+type;
................................................................................
                if (isenum)
                    bdata = '&'+self.enummap[type];
                fieldstr += '    JSI_OPT_BITS_(JSI_SIG_OPTS_FIELD, '+type+', '+fname+', "'+fdescr+'", '+fflags+', '+bsget+', '+f.idx+', "'+type+'", '+bdata+'),\n';
            } else {
                fieldstr += "    JSI_OPT_(JSI_SIG_OPTS_FIELD, "+otype+", "+name+", "+fname+", .help=\""+fdescr+"\", .flags="+fflags+rest
                    +", .info=0, .tname=\""+type+"\""+", .value=0, .bits="+option+",.boffset="+bitsiz+" ),\n";
            }
            sc += "  "+type+" "+ofname+bsizstr+";"+des+"\n";
            inits.push(sinit);
            evItems.push(evIt);
        }
        crc = 0;
        if (!port) // Non-portable fields add platform crc.
            crc = Info.platform().crc;
        else
................................................................................
        }
    }

    // Define a command extern/extension
    function GenCmd(def) {
        LogDebug("def=",def);
        var hasconstr = 0, hastilde = 0;
        var ind='  ', sc = '', fldini = '', name = def.name, definit = def.init;
        var reg = /^function\s*(~|[a-zA-Z0-9_]*)\s*\(([^)]*)\)(:[\|a-z]+|)\s*\{(.*)$/;
        var rega = /^([a-zA-Z0-9_]+)(:[|a-z]+|)(=.+|)$/;
        var keys = Info.keywords();
        var fnames = def.fnames;
        var isObj = (fnames.indexOf(name)>=0);
        var intData = (!isObj && self.varnames.indexOf(name+self.varSuffix)<0);
        keys.push('length', 'constructor','prototype');
        if (def.label)
            sc += "/* "+def.label+" */\n";
        else
            def.label = '';


        var fcnt = 0;
        var otyp = name+self.confSuffix;
        var ifpre = def.preface, ipre = '', ffpre = '\nstatic Jsi_CmdSpec '+name+'Cmds[] = {\n';
        if (self.structmap[name+'_']) {
            if (self.varnames.indexOf(name+'_Data')>=0)
                self.out += '\n#define CDATA_CODE_GLOB_VAR_'+name+' 1\n';
            else
                self.out += '\n#define CDATA_CODE_PER_INTERP_'+name+' 1\n';
        }
        // Process functions
        for (var f of def.flds) {


            LogTrace("f=",f);
            var fre = reg.exec(f.trim());
            if (!fre)
                throw "invalid function: "+f;
            var fflags = 0, finfo = 0, fopts = 0, fretType = 0;
            var fbody = fre[4];
            var fhelp = ''; // TODO: pull out of comment.
            var fhnl = fbody.indexOf('\n');
            var fhcm = fbody.indexOf('//');
            if (fhnl>0 && fhcm>=0 && fhcm<fhnl)
                fhelp = fbody.substr(fhcm+2, fhnl-3).trim();
            var fname = fre[1];
            var fconstr = (fname === name);
            if (fconstr)
                hasconstr = 1;
            if (fname === '_' || fname === '~') {


                if (fname === '~')
                    hastilde = 1;
                if (fhelp !== '') throw('function '+fname+' must not contain a "//" comment');
                if (fre[3] || fre[2])  throw('function '+fname+' may not have args or return type');
                var fff = (fname==='_'?'INIT_DONE':'OBJ_FREE');
                self.out += '\n#define CDATA_CODE_'+fff+'_'+name+' {\\\n'+fbody.trim().map(['\n', '\\\n'])+'\n\n';

                continue;
            }
            if (keys.indexOf(fname)>=0)
                throw("function name can not be a keyword: "+fname);
            if (!fre[3] || fre[3] == ':')
                throw "must specify a return type for function: "+fname;
            var fcmdName = name.toTitle()+fname.toTitle()+'Cmd';
            ifpre += '\n// function '+fre[1]+'('+fre[2]+')'+fre[3];
            var ifprecc = '\nstatic Jsi_RC '+fcmdName+'(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr';
            var isObjNew = (isObj && name === fname);
            if (isObjNew) {
                ifprecc += ', '+otyp+' *cmdPtr';
            }
            ifprecc += ')';
            ifpre += ifprecc +' {\n';
            if (isObj && name != fname) {

                self.out += '#define CDATA_CONSTRUCTOR 1\n';

                ifpre += '  '+otyp+' *cmdPtr = ('+otyp+' *)Jsi_UserObjGetData(interp, _this, funcPtr);\n'
                    + '  if (!cmdPtr) { Jsi_LogError("Apply in a non object"); return JSI_ERROR; }\n';
            } else if (intData) {
                ifpre += '#ifdef JSI_INI_DEFN_'+otyp+'\n  '+otyp+' *cmdPtr = ('+otyp+' *)Jsi_InterpGetData(interp, "'+name+'", NULL);\n'
                    + '  if (!cmdPtr) { Jsi_LogError("Missing interp data"); return JSI_ERROR; }\n#endif\n';
            }
            var rettyp = typeValidate('return', fre[3].substr(1));
................................................................................
                for (var rti of rettyp) {
                    rtvl.push('JSI_TT_'+rti.toUpperCase());
                    
                }
                fflags = '(uint)('+rtvl.join('|')+')';
            }
            var args = fre[2].trim();
            var alst = args.split(',');

            var minargs = alst.length, maxargs = minargs;
            var last = alst.length-1;
            // Process parameters
            for (var i = 0; args !== '' && i<=last; i++) {
                var aval = alst[i].trim();
                if (aval === '...') {
................................................................................
                    ifpre += ind + vget;

                //var voao = afnam+'_value';
                //ifpre += ind+'Jsi_Value *'+voao+' = Jsi_ValueArrayIndex(interp, args, '+i+');\n';
                    
                if (!isObjNew && i === last && afnam === 'options' && tvlst.indexOf('object')>=0) {
                    var iopnam = name;


                    if (fname !== 'conf' && fname !== name)
                        iopnam += '_'+fname;
                    iopnam +=  self.confSuffix;
                    if (!self.structmap[iopnam])
                        throw('Can not find struct "'+iopnam+'" for cmd '+fname);
                    var iopnamS = iopnam+'_Specs';
                    var iodnam, iott = self.structmap[iopnam];
                    LogDebug('NAM:', iopnamS);
                    if (fname === 'conf') {
                        if (isObj || intData)
                            iodnam = 'cmdPtr';
                        else
                            iodnam = '&'+name+self.varSuffix;




                    } else {
                        // Cmd-local options.
                        iodnam = '&data';
                        ifpre += '  '+iopnam + ' data = {};\n';
                    }
                    if (fname === 'conf') {
                        if (i>0) throw("Conf command takes only a single argument");
                        ifpre += '  return Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0);\n';


                    } else {
                        ifpre += '  if ('+voao+' && Jsi_OptionsProcess(interp, (Jsi_OptionSpec*)'+iopnamS+', &data, '+voao+', 0) < 0) return JSI_ERROR;\n';
                    }
                }

            }
            var fcmdNameI =  (isObj && name === fname ? name+'Constructor': fcmdName);
            ffpre += ind+'{ "'+fname+'",\t'+fcmdNameI+',\t'+minargs+','+maxargs+',"'+args+'", .help="'+fhelp
                +'", .retType='+fretType+', .flags='+fflags+', .info='+finfo+', .opts='+fopts+' },\n';
            var ofbody = '';
            for (i of fbody.split('\n')) {
                var ipre = i.trim();
                if (ipre.substr(0,6) === 'RETURN') {
                    var retre = ipre.match(/^RETURN\s*\(([a-zA-Z0-9_]*)\);/);


                    var coffs = ipre.indexOf('//:');
                    var ctyp;
                    if (coffs<0) {
                        if (rettyp.length!=1)
                            throw("return missing type comment '//:TYPE': "+i);
                        ctyp = rettyp[0];
                    } else {
................................................................................
                    }
                    i = '        '+i;
                }
                ofbody += i + '\n';
            }
            ifpre += ofbody+'\n';
            if (fconstr)
                ifpre += self.objCmdStr.replace(/Demo/g, name);
        }
        if (hastilde && !hasconstr)
            throw('defined "function ~" without constructor');
        ffpre += ind+'{ NULL, .help="'+def.label+'" }\n  };\n';
        self.cmddef += '\n' + ifpre + ffpre;
        if (isObj)
            self.cmddefs += ''; //'\n  if (Jsi_Init'+name+'(interp, 0) != JSI_OK) return NULL;\n';
................................................................................
    
    function GenAllItems(items:object)
    {
        for (var i of items.enums) {
            LogTrace("enum:", i);
            GenEnum(i);
        }
        for (var i of items.structs) {
            LogDebug("struct:", i);
            GenStruct(i);
        }
        for (var i of items.types) {
            LogDebug("types:", i);
            GenType(i);
        }
        for (var i of items.vars) {
            LogDebug("var:", i);
            GenVars(i);
        }
        for (var i of items.cmds) {
            LogDebug("cmd:", i);
            GenCmd(i);
        }
        return;
    };

    self.jscHeaderStr = '
................................................................................
#endif
#endif
#endif
';

    function CDataFinalize () {
        var name = self.name;



        self.out = '// DO NOT EDIT: file generated by Jsi_CData.jsi from: '+self.infiles.join(',')+'\n\n'
            + self.jscHeaderStr.replace(/Demo/g, name)
        /*+ "#ifndef _JSI_CDEFS_"+name+"_H_\n"
        + "#define _JSI_CDEFS_"+name+"_H_\n\n"
        + '#define _GNU_SOURCE\n#include <string.h>\n#ifdef JSI_CDATA_MAIN\n#define JSI_CDATA_IMPL\n\n'
        + '#ifdef JSI_CDATA_SHARED\n#define JSI_USE_STUBS 1\n#include "jsi.h"\n#else\n#include "jsi.c"\n#endif\n#endif\n\n' */
        + self.pre0 + '\n' + self.pre + "\n#ifdef JSI_CDATA_IMPL\n\nJSI_EXTENSION_INI\n#undef JSI_EXTENSION_INI\n#define JSI_EXTENSION_INI\n"
        + self.out0 + self.out + self.out1
        + self.pre1 + '\n' + self.iout
................................................................................
        + '  if (interp && (Jsi_PkgRequire(interp, "CData", 0)<0 || \n'
        + "      JSI_OK != Jsi_CDataRegister(interp, &CS_STATICS_"+name+"))) return NULL;\n\n"

        + self.cmddefs 

        + "\n  return &CS_STATICS_"+name+";\n}\n\n"
        + "\n#endif\n#endif\n"
        + self.selfSuffix.replace(/Demo/g, name);
        if (self.outFile) {
            if (File.exists(self.outFile)) {
                var ofpre = File.read(self.outFile),
                    ofpp1 = '// DO NOT EDIT: file generated by Jsi_CData.jsi from';
                if (ofpre && ofpre.substr(0, ofpp1.length) != ofpp1)
                    throw('can not overwrite non-generated file: '+self.outFile);
            }
            File.write(self.outFile, self.out);
        } else
            return(self.out);
    }
    
    function StrGetEnum(str:string) {
        LogDebug("DO:", str);
        var top = -1;
        var flds = [];
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad def: " + str);
        var name = ina[2];
        var def = {name:name, type:ina[1]};
        var vli;
        var l = str.trim().split('\n');




        l = l.splice(1, l.length-2);
        var lastv = -1;
        for (var i in l) {
            //var res = {};
            var s, label = '', v = l[i].trim();
            LogDebug("v:", v);
            if (flds.length == 0 && v.substr(0,2) === '//') {;
                label = v.substr(2).trim();
                if (!def.label)
                    def.label = label;
                else
                    throw("multiline label not allowed: "+v);
                continue;
            }
            vli = v.indexOf('//');
            var reslabel;
            if (vli>0) {
                reslabel = v.substr(vli+2);
                v = v.substr(0,vli).trim();
            }
            if (v === '') continue;
................................................................................
        }
        LogTrace("AAAA:", top, flds);
        def.flds = flds;
        self.enumIni[name] = flds[0].name;
        return def;
    };

    self.parmFlags = ("isSpecified,initOnly,readOnly,noDupValue,noClear,dbDirty,dbIgnore,dbRowid,"









        +"nocase,forceInt,bitsetBool,dateOnly,timeOnly,isBits,fmtTime,fmtHex,strict,fieldSetup,"
        +"coerce,noSig").split(',');


    function ParseFlags(rest:string) {

        if (rest.substr(0,1) !== '<')
            return;
        var ree = rest.indexOf('>');
        if (ree<0)
            throw("expected end bracket: "+rest);

        var parms = rest.substr(1, ree-1);
        rest = rest.substr(ree+1).trim();
        LogTrace('parms:', parms);
        var pf = self.parmFlags;
        var f = 0;
        for (var o of parms.split(',')) {

            var oi = pf.indexOf(o);
            if (oi<0)




                throw("unknown flag '"+o+"' expected: "+pf.join(', '));

            f |= (1<<oi);
        }
        return [f, rest];
    }

    function StrGetStruct(str:string) {
        LogDebug("DO: "+str);
        var flds = [], fcnt = 0;
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad def: " + str);
        var label, def = {name:ina[2], type:ina[1], opts:null, label:null, init:true};
        var li, l = str.trim().split('\n');
        if ((li=l[0].indexOf('//'))>0) {
            label = l[0].substr(li+2).trim();
            def.label = label;
        }
        l = l.splice(1, l.length-2);
        var dfn = def.name+'_Specs';
        if (self.structmap[dfn])
            throw("duplicate struct name");
        self.structmap[def.name] = dfn;
        for (var i in l) {
            var res = {label:'', bit:0, bitset:0, asize:0, flags:0, isstr:false, nowarn:false};
            var v = l[i].trim();
            LogTrace("v:". v);
            if (v.match(/^<.*>$/)) {
                if (def.opts) throw("multiple opts");
                LogDebug("OPTS:", v);
                def.opts = v.substr(1,v.length-2);
                continue;
................................................................................
            var s = v.match(/^\s*(\S+)\s+([^;]+)\s*;\s*(.*)$/);
            LogTrace('SS:', v);
            if (s === null || s.length < 2)
                throw('invalid field: "'+v+'"');
            res.id = spref + s[1];
            var namval = s[2].trim();
            var rest = s[3].trim();
            var pfi = ParseFlags(rest);
            if (pfi) {
                res.flags = pfi[0].toString(16);
                rest = pfi[1];
            }
            label = rest;
            if (label !== "") {
                if (label.substr(0,2) !== '//')
                    throw('expected // after definition: '+label);
                label = label.substr(2).trim();
                if (label.substr(0, 7) === 'NOWARN:') {
                    res.nowarn = true;
                    label = label.substr(7).trim();
                }






            }
            res.label = label.trim();
            var nam = namval, val = null, nn;
            if (nam.indexOf('=')>=0)
            {
                nn = nam.split('=');
                if (nn.length != 2)
................................................................................
            LogTrace('res:', res);
            flds.push(res);
        }
        def.flds = flds;
        return def;
    }
    
    function StrGetVars(str:string) {
        LogDebug("DO: "+str);
        var flds = [];
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad vars def: " + str);
        var label, def = {name:ina[2], type:ina[1]};
        var l = str.trim().split('\n');
        l = l.splice(1, l.length-2);
        for (var i in l) {
            var res = {label:'', asize:0, opts:'', ismap:false, ktype:null, varParam:''};
            var v = l[i].trim();
            LogTrace("v:", v);
            if (v === '') continue;
            if (flds.length == 0 && v.substr(0,2) === '//') {
                label = v.substr(2).trim();
                if (!def.label)
                    def.label = label;
................................................................................
            LogTrace('res:', res);
            flds.push(res);
        }
        def.flds = flds;
        return def;
    }

    function StrGetCmd(str:string) {
        LogDebug("DO:", str);
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad cmds def: " + str);
        var preface = '';;
        var label, sdefs=[], def = {name:ina[2], type:ina[1], fnames:[]};
        var curdef = '', fcnt = 0;
        var l = str.trim().split('\n');




        l = l.splice(1, l.length-2);
        var nam = def.name;

        for (var i of l) {

            var ipre = i.trim();
            if (curdef == '' && ipre.substr(0,2) === '//') {
                label = ipre.substr(2).trim();
                if (!def.label)
                    def.label = label;
                else
                    throw("multiline label not allowed: "+ipre);
                continue;
            }
            var reg;
            if ((reg=ipre.match(/^function\s*(~|[a-zA-Z0-9_]*)/))) {
                fcnt++;
                def.fnames.push(reg[1]);
                if (curdef !== '') {
                    sdefs.push(curdef);
                    curdef = '';
                }
            } else if (curdef === '') {
                if (fcnt === 0) {
                    preface += i + '\n';
                    continue;
                }
                throw("expected function: "+i);
            }
            curdef += i + '\n';
        }
        if (curdef != '') {
            sdefs.push(curdef);
            curdef = '';
        }
        LogTrace("sdefs:", sdefs.join(','));
        def.flds = sdefs;
        def.preface = preface;
        return def;
    }

    function GetIncludeReg(match, file) {
        str = File.read(file);
        return GetInclude(str);
    }
    
    function GetInclude(str:string) {
        if (str.indexOf('include')<0)
            return str;
        return str.replace(/^include\s*=\s*([a-zA-Z0-9_.]+)\s*;$/gm, GetIncludeReg);
    }
    
    // Gather all the definitions 
    function GetDefs(str) {
        var curdef = '', gdefs = [], slst, cnt = 0;
        str = GetInclude(str);
        slst = str.split('\n');
        for (var i of slst) {
            cnt++;
            var ipre = i.trim().substr(0,2);
            if (ipre === '//' || ipre == '') continue;
            if (i.trimRight() === '};') {
                if (curdef === '') throw("extra end found at line "+cnt);
                curdef += i;
                gdefs.push(curdef);

                curdef = '';
                continue;
            }
            if (curdef === ''  && i.indexOf('//')<0 && i.indexOf(';')>=0)
                throw("defn can not be all on one line: "+i);
            curdef += i + '\n';
        }
        if (curdef !== '') throw("extra input found at end");
        return gdefs;
    }
    
    function mainSub() {
        if (typeof args !== 'array' || (!args.length && self.inStr===''))
            throw "expected 1 or more args";
        
        if (self.cflags)
            return GetCflags();
    
        if (args.length)
            self.rootname = File.rootname(File.tail(args[0]));
        if (self.O !== '-') {
            if (self.O !== '')
                self.outFile = self.O;
            else if (self.rootname)
                self.outFile = self.rootname+'.h';
        }
        if (!self.name)
            if (self.rootname)
                self.name = self.rootname;
            else
                self.name = 'main';
        var inp = self.inStr;

        for (var fname of args) {
            self.infiles.push(fname);
            var cinp = File.read(fname);
            if (cinp.substr(0,2) === '#!')
                cinp = cinp.substr(cinp.indexOf('\n'));
            inp += cinp;





        }

        var ina = GetDefs(inp);
        //var ina = inp.match(/([a-zA-Z0-9_]+\s+\S+\s*\{[^\}]+\};)/g);
        LogTrace('INA:', ina);
        for (var i of ina) {


            LogTrace("i:", i);
            var in1 = i.match(/^([a-zA-Z0-9_]+)\s+[a-zA-Z0-9_]+\s*=\s*\{/);
            var in1 = i.match(/^([a-zA-Z0-9_]+)\s+[a-zA-Z0-9_]+\s*=\s*\{/);
            if (!in1)
                throw("unknown input: "+i);
            var nam = in1[1];
            switch (nam) {

                case 'enum':    defs.enums.push(StrGetEnum(i)); break;
                case 'struct':  defs.structs.push(StrGetStruct(i)); break;
                //case 'types':    defs.types.push(StrGetTypes(i)); break;
                case 'vars':    defs.vars.push(StrGetVars(i)); break;
                case 'extension':  defs.cmds.push(StrGetCmd(i)); break;
                default: throw("unknown defn ' "+nam+"' expected: struct, enum, vars, extension");
            }
        }
        if (self.json)
            return JSON.stringify(defs);
        GenAllItems(defs);
        if (self.eval) {
            puts(EV);
................................................................................
    Jsi_OptionsFree(cmdPtr->interp, Demo_Specs, cmdPtr, 0);
    memset(cmdPtr, 0, sizeof(*cmdPtr));;
}

static Jsi_RC DemoObjFree(Jsi_Interp *interp, void *data)
{
    Demo *cmdPtr = (Demo *)data;
#ifdef CDATA_CODE_OBJ_FREE_Demo
    CDATA_CODE_OBJ_FREE_Demo
#endif
    DemoObjErase(cmdPtr);
    Jsi_Free(cmdPtr);
    return JSI_OK;
}

static bool DemoObjIsTrue(void *data)
{
................................................................................
        _ = (Demo_ *)Jsi_InterpGetData(interp, "Demo_InterpData", NULL);
    else {
        _ = (Demo_ *)Jsi_Calloc(1, sizeof(Demo_));
        Jsi_InterpSetData(interp, "Demo_InterpData", _, Jsi_DeleteData);
    }
    ddPtr = (void*)_;
#endif
#ifdef CDATA_CODE_INIT_DONE_Demo
    CDATA_CODE_INIT_DONE_Demo
#endif
#ifdef CDATA_CODE_PER_INTERP_Demo
    if (isRelease)
        Jsi_InterpFreeData(interp, "Demo_InterpData");
#endif
    if (!isRelease) {
        Jsi_VarRef vr = {};
#if (defined(CDATA_CODE_GLOB_VAR_Demo) || defined(CDATA_CODE_PER_INTERP_Demo))







<




|
<



>
|













|
>







 







>


>
|







 







|
|
|

>
>







 







|



|





|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





>










>
|







 







|










>
|








|
>
|
>
>










|







 







|












>
>
>
>







 







|
>
>
>
>
>
|







 







>
|







 







|







 







|











>
>










|
>
>
|









|




|
>
>


<

|
|
>






|








|
>
|
>







 







|







 







>
>
|












>
>
>
>








>
>

|




|


|

|


>
>







 







|







 







|



|



|



|







 







<
>
>
|
|







 







|












|







|

|
>
>
>
>






<
<
<
<
<
<
<
<







 







|
>
>
>
>
>
>
>
>
>
|
<
>


>


|


>





|
>

|
>
>
>
>
|
>


|


|





|











|







 







<
<
<
<
<









>
>
>
>
>
>







 







|









|







 







|





|

|
>
>
>
>

|


>

|






|





|












|













|



|



|
|




|

|

|
>



|



|




|











|






|
>
|
|
|
|
<
|
>
>
>
>
>





|
>
>

<





>
|
|

|
|
|







 







|
<
<







 







<
|
<







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
..
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
...
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
...
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
...
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
...
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
...
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
...
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
...
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
...
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
...
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
...
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
...
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
...
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
...
911
912
913
914
915
916
917

918
919
920
921
922
923
924
925
926
927
928
...
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
....
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
....
1114
1115
1116
1117
1118
1119
1120





1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
....
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
....
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373

1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388

1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
....
1436
1437
1438
1439
1440
1441
1442
1443


1444
1445
1446
1447
1448
1449
1450
....
1569
1570
1571
1572
1573
1574
1575

1576

1577
1578
1579
1580
1581
1582
1583

require('Jsish');

// A C-API generator for structs, enums, maps, and extensions.

function Jsi_CData(args:array, conf:object=void)
{

    
    var options = {         // The C-API preprocessor for structs and enums.
        confSuffix  :'',    // Suffix to add to struct used for object config.
        eval        :false, // Evaluate in interp.
        cflags      :false, // Return CFLAGS to compile FILE/FILE.so from .c generated by a .jsc.

        json        :false, // Output json definitions.
        memDebug    :false, // Enable memdebug
        name        :null,  // Name of group
        noline      :false, // Do not add #line to c output file
        O           :'',    // Output file, or '-' to return string. Default is FILE.c.
        test        :false, // Test output.
        trace       :false, // Trace output.
        unkType     :true,  // Warn of unknown struct fields self will be ignored.
        varSuffix   :'_Data'// Suffix to add to data used for object config.
    };

    var self = {
        pre:'', pre0:'', pre1:'', out0:'', out1:'', out:'', iout:'',
        init:[], types:'',  structs:'', enums:'', vars:'', cmds:'',
        varnames:[], mapnames:[], cmdnames:[], 
        structmap:{}, enummap:{}, enumzero:{},
        vardefs:'',  siglst:[], varinits:'', mapinits:'', enumIni:{},
        portlst:[], statlst:[], cmddefs:'', cmddef:'',
        enumvals:{}, indata:'', infile:'', outFile:null, rootname:null,
        lnstart:0, setCons:0, icode:[], outcode:''
    };
    var Ex = {asize:0, offs:1, size:2, sig:3};
    var EV = { enum:[], struct:[], vars:[] };

    parseOpts(self, options, conf);

    var defs = {structs:[], enums:[], types:[], vars:[], cmds:[]};
................................................................................


    var typeNameStr = "number string boolean array function object regexp any userobj void null undefined";
    var typeNameList = typeNameStr.split(' ');
    
    var portTypes = 'BOOL,UINT8,UINT16,UINT32,UINT64,INT8,INT16,INT32,INT64,DOUBLE,LDOUBLE,TIME_W,TIME_D,STRBUF';
    var statTypes = 'TIME_T,INT,UINT,LONG,ULONG,SHORT,USHORT,INTPTR,UINTPTR,SIZE_T,'+portTypes;
    var valpTypes = 'STRING,VALUE,VAR,FUNC,ARRAY,OBJ,REGEX,USEROBJ';
    var portableTypes = portTypes.split(',');
    var staticTypes = statTypes.split(',');
    var valuePTypes = valpTypes.split(',');
    
    function GetBaseType(styp) { //TODO: lookup with info type.
        switch (styp) {
            case 'bool':     return 'BOOL';  case 'uint':     return 'UINT'; 
            case 'int':      return 'INT';   case 'double':   return 'DOUBLE';  
            case 'int8_t':   return 'INT8';  case 'int16_t':  return 'INT16';
            case 'int32_t':  return 'INT32'; case 'int64_t':  return 'INT64';   
            case 'uint8_t':  return 'UINT8'; case 'uint16_t': return 'UINT16';
................................................................................
    
    function GetCflags() {
        var fn = args[0], fne = File.extension(fn), fnr=File.rootname(fn), name=fnr, fnc = fnr;
        if (fn.indexOf('/')>=0)
            throw('file may not have path: '+fn);
        switch (fne) {
            case '.so': fnr += '.so';
            case '.c':
            case '': fnc += '.c'; break;
            default: throw('extension not one of: .so .c ""');
        }
        if (!File.readable(fnc) && File.readable(name+'.c'))
            fnc = name+'.c';
        if (!File.readable(fnc))
            LogWarn('file not found: '+fnc);
        var s = '-g -Og -O0 -Wall -fPIC -DJSI__SQLITE=1'
            + ' -DJSI__READLINE=1 -fno-diagnostics-show-caret -Wc++-compat'
            + ' -Wwrite-strings -DJSI_CDATA_MAIN=1 -x c -rdynamic';
        if (args.length<=1 && self.memDebug)
            s += ' -DJSI__MEMDEBUG=1';
................................................................................
        if (isWS)
            s += format(' -DJSI__WEBSOCKET=1 -I%s/src/lib  -I%s/src/build -I%s/unix -I%s/build/unix ', wDir, wDir, wDir, wDir);
        s += ' -o '+fnr+' '+fnc;
        if (args.length>1) {
            s += ' -DCDATA_MULTI_INC=1 -DCDATA_JSI_C_MAIN_'+name;
            var aalst = [], arst = args.slice(1);
            for (var al of arst) {
                if (File.extension(al) == '.c')
                    aalst.push(File.rootname(al));
            }
            var pnl = name;
            for (al of aalst) {
                s += ' -DCDATA_MODINIT_CHAIN_'+pnl+'=Jsi_Init'+al;
                pnl = al;
            }
            s += ' '+arst.join(' ');
            if (aalst.length && fne == '.so')
                throw("can not add .c files to a .so build");
        }
        s += ' -lm';
        if (fne === '.so')
            s += ' -shared -DJSI_CDATA_SHARED=1';
        if (isWS)
            s += ' -L '+wDir+'/build/unix/ -lwebsockets';
         var sDir = pDir + '/sqlite';
................................................................................
        var tlst = typ.split('|');
        var i = -1;
        for (i = 0; i<tlst.length; i++)
            if (typeNameList.indexOf(tlst[i]) < 0)
                throw prefix+ " type unknown '"+tlst[i]+'" not one of: '+typeNameStr;
        return tlst;
    }
    
    function CountNL(str:string) {
        return str.split('\n').length;
    }
    
    function HashLine(lnum:number, str:string='') {
        if (self.noline)
            return '';
        var olnum = lnum;
        if (str !== '') {
            var sstr = str.substr(0, 100);
            var d = self.indata, l1 = d.indexOf(sstr), l2 = d.lastIndexOf(sstr);
            if (l1>=0 && l1===l2) {
                lnum = CountNL(d.substr(0, l1));
                if (lnum != olnum) {
                    LogTest('ADJ: ', lnum, ' != ', olnum);
                }
            }
        };
        return '#line '+lnum+' "'+self.infile+'" /* jsi_CData.jsi */\n';
    }

    function GenType(def) {
        // TODO
        //self.types += "  { \""+name+"\", \""+label+"\", 0, sizeof(name), \""+fmt+"\", "+cformat+", },\n";
    };
    
    // Define an enum
    function GenEnum(def) {
        // TODO: generate lookup string table. Also enhance Jsi_Opt_SwitchEnum to support more than just 0,1,2...
        LogDebug("def=",def);
        var flags = 0;
        with (def) {
            self.portlst.push(name);
            self.statlst.push(name);
            if (label)
                self.pre0 += "/* "+label+" */\n";
            var flnhash = HashLine(lnum);
            self.pre0 += flnhash+"typedef enum "+name+" {\n";
            //self.pre += "  ";
            var eName = name+"_Enum"; "jsi_csitems_"+name;
            var evDef = {name:name}, evItems = [];
            self.enummap[name] = eName;
            self.enums += "    {.sig=JSI_SIG_OPTS_ENUM, .id=JSI_OPTION_CUSTOM, .name=\""+name+"\""
                +", .offset="+flds.length+", .size=sizeof(enum "+name+"), .init={}"
                + ", .help=\""+(label?label:'')+"\""
................................................................................
            self.pre0 += "} "+name+";\n\n";
            EV.enum.push([evDef, evItems]);
        }
    }
    
    // Define a struct
    function GenStruct(def) {
        var sc = '', fieldstr = '', name = def.name, definit = def.init, sig = 0, cnt = 0, aspre = '', lnum=def.lnum;
        var hassig = false;
        if (!def.Array)
            def.Array = 0;
        var evDef = {name:name}, evItems = [];
         if (def.label) {
            sc += "/* "+def.label+" */\n";
            evDef.help = def.label;
        } else {
            def.label = '';
        }
        var flnhash = HashLine(lnum);
        sc += flnhash+"typedef struct "+name+" {\n";
        var bsgets=[], bscnt = 0, inits = [], hasinit = 0, fcnt = 0, flags = 0, bsget = 0,
            crc = 0, scrc = '', port=1, stat=1, portconds='';
        // self.out( [subst -novariables fields]
        for (var ii in def.flds) {
            var f = def.flds[ii];
            if (!f)
                continue;
            LogTrace("f:",f);
            var type = f.id, fname = f.name, ofname = fname, fflags = f.flags,
                st = GetBaseType(type), isval = (st == null && valuePTypes.indexOf(type)>=0),
                evIt = {name:fname, type:f.id}, rotype=type, isunder = (fname.substr(0,1)=='_' || fname=="interp");
            if (isval)
                rotype = 'Jsi_Value*';
            //if (fflags)
            //    evIt.flags=fflags;
            if (f.label)
                evIt.help = f.label;
            //if (f.flags)
            //    evIt.flags = f.flags;
            if (type == 'Jsi_Sig')
                st = 'UINT32';
            if (scrc === '')
                scrc += ',';
            scrc += rotype;
            var des = '',
                fdescr = (f.label?f.label:'');
            if (!cnt++ && fname == 'sig') {
                fflags += '|JSI_OPT_FMT_HEX';
                if (!f.bit && !f.asize) {
                    hassig = true; sig = f.init;
                }
................................................................................
                option = bscnt++;
                bitsiz = f.bit;
                bsgets.push([f.name, type+" "+f.name+":"+bitsiz,type, f.idx]);
                bsiz = Math.floor((f.bit+7)/8);
                bsizstr = ':'+f.bit;
            } else {
                offset = "Jsi_Offset("+name+","+fname+")";
                bsiz = "sizeof("+rotype+")";
                bitsiz = "8*"+bsiz;
                if (stat) {
                    if ((!st || staticTypes.indexOf(st)<0) && self.statlst.indexOf(type)<0)
                        stat = 0;
                }
                if (!stat)
                    port =0;
                else if (port) {
                    if ((!st || portableTypes.indexOf(st)<0) && self.portlst.indexOf(type)<0)
                        port = 0;
                }
            }
            /*if (!f.bit && !f.asize && st != null) {
                fieldstr += '    JSI_OPT('+st+", "+name+", "+fname+", .help=\""+fdescr+"\", .flags="+fflags+" ),\n";
                continue;
            }*/
            if (f.asize) {
                bsizstr = '['+f.asize+']';
                scrc += bsizstr;
            }
            var sinit = 0, csinit = 0;
            if (self.enumIni[type] !== undefined)
                sinit = self.enumIni[type];
................................................................................
            var otype = st;
            
            var issubopt = (self.structmap[type] !== undefined);
            var isenum = (self.enummap[type] !== undefined);
            if (isenum && !self.enumzero[type])
                LogWarn(name, '.', fname, ': enum ', type, "does not define a zero value");
            var bdata = 0;
            var rest = ', .custom=0, .data=' + (f.data? ('(void*)"'+f.data+'"'):'0');
            if (isunder) {
            } else if (isval) {
                otype = type;
                st = 'Jsi_Value*';
                
            } else if (!st && !isval) {
                otype = st = 'CUSTOM';
                if (issubopt) {
                    LogTest("SUB:", type);
                    rest = ', .custom=Jsi_Opt_SwitchSuboption, .data=(void*)'+self.structmap[type];
                } else if (isenum) {
                    rest = ', .custom=Jsi_Opt_Switch'+(f.bitset?'Bitset':'Enum')+', .data=(void*)'+self.enummap[type];
                    fflags += '|JSI_OPT_ENUM_SPEC';
................................................................................
                    if (self.unkType && !f.nowarn && type !== "Jsi_Interp*" && type !== "void*") {
                        var tvlen = type.length;
                        if (type[tvlen-1] !== '*' || type[tvlen-2] !== '_' || !self.structmap[type.substr(0,tvlen-2)])
                            puts('ignoring unknown type "'+type+'": ' +name+'.'+fname);
                    }
                }
            }
            if (isunder) {
            } else if (f.asize) {
                evIt.size = f.asize;
                if (f.bit)
                    throw("array of bits unsupported: "+name+'.'+fname);
                if (isenum)
                    throw("array of enums unsupported: "+name+'.'+fname);
                if (self.structmap[type]) {
                    csinit = "(uchar*)&jsi_csini_data_"+type;
................................................................................
                if (isenum)
                    bdata = '&'+self.enummap[type];
                fieldstr += '    JSI_OPT_BITS_(JSI_SIG_OPTS_FIELD, '+type+', '+fname+', "'+fdescr+'", '+fflags+', '+bsget+', '+f.idx+', "'+type+'", '+bdata+'),\n';
            } else {
                fieldstr += "    JSI_OPT_(JSI_SIG_OPTS_FIELD, "+otype+", "+name+", "+fname+", .help=\""+fdescr+"\", .flags="+fflags+rest
                    +", .info=0, .tname=\""+type+"\""+", .value=0, .bits="+option+",.boffset="+bitsiz+" ),\n";
            }
            sc += "  "+rotype+" "+ofname+bsizstr+";"+des+"\n";
            inits.push(sinit);
            evItems.push(evIt);
        }
        crc = 0;
        if (!port) // Non-portable fields add platform crc.
            crc = Info.platform().crc;
        else
................................................................................
        }
    }

    // Define a command extern/extension
    function GenCmd(def) {
        LogDebug("def=",def);
        var hasconstr = 0, hastilde = 0;
        var ind='  ', sc = '', fldini = '', name = def.name, definit = def.init, lnum = def.lnum;
        var reg = /^function\s*(~|[a-zA-Z0-9_]*)\s*\(([^)]*)\)(:[\|a-z]+|)\s*\{(.*)$/;
        var rega = /^([a-zA-Z0-9_]+)(:[|a-z]+|)(=.+|)$/;
        var keys = Info.keywords();
        var fnames = def.fnames;
        var isObj = (fnames.indexOf(name)>=0);
        var intData = (!isObj && self.varnames.indexOf(name+self.varSuffix)<0);
        keys.push('length', 'constructor','prototype');
        if (def.label)
            sc += "/* "+def.label+" */\n";
        else
            def.label = '';
        self.icode[name+'_'] = '';
        self.icode[name+'~'] = '';
        var fcnt = 0;
        var otyp = name+self.confSuffix;
        var ifpre = def.preface, ipre = '', ffpre = '\nstatic Jsi_CmdSpec '+name+'Cmds[] = {\n';
        if (self.structmap[name+'_']) {
            if (self.varnames.indexOf(name+'_Data')>=0)
                self.out += '\n#define CDATA_CODE_GLOB_VAR_'+name+' 1\n';
            else
                self.out += '\n#define CDATA_CODE_PER_INTERP_'+name+' 1\n';
        }
        // Process functions
        for (var ff of def.flds) {
            var f = ff[0];
            var flnof = ff[1];
            LogTrace("ff=",ff);
            var fre = reg.exec(f.trim());
            if (!fre)
                throw "invalid function: "+f;
            var fflags = 0, finfo = 0, fopts = 0, fretType = 0;
            var fbody = fre[4];
            var fhelp = ''; // TODO: pull out of comment.
            var fhnl = fbody.indexOf('\n');
            var fhcm = fbody.indexOf('//');
            if (fhnl>0 && fhcm>=0 && fhcm<fhnl)
                fhelp = fbody.substr(fhcm+2, fhnl-3);//.trim();
            var fname = fre[1];
            var fconstr = (fname === name);
            if (fconstr)
                hasconstr = 1;
            var isinitdel = (fname === '_' || fname === '~');
            var flnhash = HashLine(lnum, fbody);
            if (isinitdel) {
                if (fname === '~')
                    hastilde = 1;

                if (fre[3] || fre[2])  throw('function '+fname+' may not have args or return type');
                //var fff = (fname==='_'?'INIT_DONE':'OBJ_FREE');
                //self.out += '\n#define CDATA_CODE_'+fff+'_'+name+' {\\\n'+fbody.trim().map(['\n', '\\\n'])+'\n\n';
                self.icode[name+fname] = '{\n'+flnhash+fbody+'\n';
                continue;
            }
            if (keys.indexOf(fname)>=0)
                throw("function name can not be a keyword: "+fname);
            if (!fre[3] || fre[3] == ':')
                throw "must specify a return type for function: "+fname;
            var fcmdName = name+fname+'Cmd';
            ifpre += '\n// function '+fre[1]+'('+fre[2]+')'+fre[3];
            var ifprecc = '\nstatic Jsi_RC '+fcmdName+'(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret, Jsi_Func *funcPtr';
            var isObjNew = (isObj && name === fname);
            if (isObjNew) {
                ifprecc += ', '+otyp+' *cmdPtr';
            }
            ifprecc += ')';
            ifpre += ifprecc +' {\n';
            if (isObj && !fconstr) {
                if (!self.setCons)
                    self.out += '#define CDATA_CONSTRUCTOR 1\n';
                self.setCons=1;
                ifpre += '  '+otyp+' *cmdPtr = ('+otyp+' *)Jsi_UserObjGetData(interp, _this, funcPtr);\n'
                    + '  if (!cmdPtr) { Jsi_LogError("Apply in a non object"); return JSI_ERROR; }\n';
            } else if (intData) {
                ifpre += '#ifdef JSI_INI_DEFN_'+otyp+'\n  '+otyp+' *cmdPtr = ('+otyp+' *)Jsi_InterpGetData(interp, "'+name+'", NULL);\n'
                    + '  if (!cmdPtr) { Jsi_LogError("Missing interp data"); return JSI_ERROR; }\n#endif\n';
            }
            var rettyp = typeValidate('return', fre[3].substr(1));
................................................................................
                for (var rti of rettyp) {
                    rtvl.push('JSI_TT_'+rti.toUpperCase());
                    
                }
                fflags = '(uint)('+rtvl.join('|')+')';
            }
            var args = fre[2].trim();
            var alst = (args===''?[]:args.split(','));

            var minargs = alst.length, maxargs = minargs;
            var last = alst.length-1;
            // Process parameters
            for (var i = 0; args !== '' && i<=last; i++) {
                var aval = alst[i].trim();
                if (aval === '...') {
................................................................................
                    ifpre += ind + vget;

                //var voao = afnam+'_value';
                //ifpre += ind+'Jsi_Value *'+voao+' = Jsi_ValueArrayIndex(interp, args, '+i+');\n';
                    
                if (!isObjNew && i === last && afnam === 'options' && tvlst.indexOf('object')>=0) {
                    var iopnam = name;
                    if (fname === 'idconf' && !fconstr)
                        iopnam += '_id';
                    else if (fname !== 'conf' && !fconstr)
                        iopnam += '_'+fname;
                    iopnam +=  self.confSuffix;
                    if (!self.structmap[iopnam])
                        throw('Can not find struct "'+iopnam+'" for cmd '+fname);
                    var iopnamS = iopnam+'_Specs';
                    var iodnam, iott = self.structmap[iopnam];
                    LogDebug('NAM:', iopnamS);
                    if (fname === 'conf') {
                        if (isObj || intData)
                            iodnam = 'cmdPtr';
                        else
                            iodnam = '&'+name+self.varSuffix;
                    } else if (fname === 'idconf') {
                        // Cmd-local options.
                        iodnam = 'dPtr';
                        ifpre += '  '+iopnam + ' *dPtr = '+name+'_IdGet(cmdPtr, id, 0);\n';
                    } else {
                        // Cmd-local options.
                        iodnam = '&data';
                        ifpre += '  '+iopnam + ' data = {};\n';
                    }
                    if (fname === 'conf') {
                        if (i>0) throw("Conf command takes only a single argument");
                        ifpre += '  return Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0);\n';
                    } else if (fname === 'idconf') {
                        ifpre += '  if (!dPtr || Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0) < 0) return JSI_ERROR;\n';
                    } else {
                        ifpre += '  if ('+voao+' && Jsi_OptionsProcess(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', 0) < 0) return JSI_ERROR;\n';
                    }
                }

            }
            var fcmdNameI =  (isObj && fconstr ? name+'Constructor': fcmdName);
            ffpre += ind+'{ "'+fname+'",\t'+fcmdNameI+',\t'+minargs+','+maxargs+',"'+args+'", .help="'+fhelp
                +'", .retType='+fretType+', .flags='+fflags+', .info='+finfo+', .opts='+fopts+' },\n';
            var ofbody = flnhash;
            for (i of fbody.split('\n')) {
                ipre = i.trim();
                if (ipre.substr(0,6) === 'RETURN') {
                    var retre = ipre.match(/^RETURN\s*\(([a-zA-Z0-9_]*)\);/);
                    if (!retre)
                        throw('return format must be "RETURN(x);" : '+ipre);
                    var coffs = ipre.indexOf('//:');
                    var ctyp;
                    if (coffs<0) {
                        if (rettyp.length!=1)
                            throw("return missing type comment '//:TYPE': "+i);
                        ctyp = rettyp[0];
                    } else {
................................................................................
                    }
                    i = '        '+i;
                }
                ofbody += i + '\n';
            }
            ifpre += ofbody+'\n';
            if (fconstr)
                ifpre += format(self.objCmdStr.replace(/Demo/g, name), self.icode[name+'~'], self.icode[name+'_']);
        }
        if (hastilde && !hasconstr)
            throw('defined "function ~" without constructor');
        ffpre += ind+'{ NULL, .help="'+def.label+'" }\n  };\n';
        self.cmddef += '\n' + ifpre + ffpre;
        if (isObj)
            self.cmddefs += ''; //'\n  if (Jsi_Init'+name+'(interp, 0) != JSI_OK) return NULL;\n';
................................................................................
    
    function GenAllItems(items:object)
    {
        for (var i of items.enums) {
            LogTrace("enum:", i);
            GenEnum(i);
        }
        for (i of items.structs) {
            LogDebug("struct:", i);
            GenStruct(i);
        }
        for (i of items.types) {
            LogDebug("types:", i);
            GenType(i);
        }
        for (i of items.vars) {
            LogDebug("var:", i);
            GenVars(i);
        }
        for (i of items.cmds) {
            LogDebug("cmd:", i);
            GenCmd(i);
        }
        return;
    };

    self.jscHeaderStr = '
................................................................................
#endif
#endif
#endif
';

    function CDataFinalize () {
        var name = self.name;

        var scnm = self.icode[name+'_'];
        if (!scnm) scnm = '';
        self.out = '// DO NOT EDIT: file generated by Jsi_CData.jsi from: '+self.infile+'\n\n'
            + self.jscHeaderStr.replace(/Demo/g, name) + self.outcode
        /*+ "#ifndef _JSI_CDEFS_"+name+"_H_\n"
        + "#define _JSI_CDEFS_"+name+"_H_\n\n"
        + '#define _GNU_SOURCE\n#include <string.h>\n#ifdef JSI_CDATA_MAIN\n#define JSI_CDATA_IMPL\n\n'
        + '#ifdef JSI_CDATA_SHARED\n#define JSI_USE_STUBS 1\n#include "jsi.h"\n#else\n#include "jsi.c"\n#endif\n#endif\n\n' */
        + self.pre0 + '\n' + self.pre + "\n#ifdef JSI_CDATA_IMPL\n\nJSI_EXTENSION_INI\n#undef JSI_EXTENSION_INI\n#define JSI_EXTENSION_INI\n"
        + self.out0 + self.out + self.out1
        + self.pre1 + '\n' + self.iout
................................................................................
        + '  if (interp && (Jsi_PkgRequire(interp, "CData", 0)<0 || \n'
        + "      JSI_OK != Jsi_CDataRegister(interp, &CS_STATICS_"+name+"))) return NULL;\n\n"

        + self.cmddefs 

        + "\n  return &CS_STATICS_"+name+";\n}\n\n"
        + "\n#endif\n#endif\n"
        + format(self.selfSuffix.replace(/Demo/g, name), scnm);
        if (self.outFile) {
            if (File.exists(self.outFile)) {
                var ofpre = File.read(self.outFile),
                    ofpp1 = '// DO NOT EDIT: file generated by Jsi_CData.jsi from';
                if (ofpre && ofpre.substr(0, ofpp1.length) != ofpp1)
                    throw('can not overwrite non-generated file: '+self.outFile);
            }
            File.write(self.outFile, self.out);
        } else
            return(self.out);
    }
    
    function StrGetEnum(str:string, lnum:number) {
        LogDebug("DO:", str);
        var top = -1;
        var flds = [];
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad def: " + str);
        var name = ina[2];
        var def = {name:name, type:ina[1], lnum:lnum};
        var vli;
        var l = str.trim().split('\n'), li;
        if ((li=l[0].indexOf('//'))>0) {
            label = l[0].substr(li+2).trim();
            def.label = label;
        }
        l = l.splice(1, l.length-2);
        var lastv = -1;
        for (var i in l) {
            //var res = {};
            var s, label = '', v = l[i].trim();
            LogDebug("v:", v);








            vli = v.indexOf('//');
            var reslabel;
            if (vli>0) {
                reslabel = v.substr(vli+2);
                v = v.substr(0,vli).trim();
            }
            if (v === '') continue;
................................................................................
        }
        LogTrace("AAAA:", top, flds);
        def.flds = flds;
        self.enumIni[name] = flds[0].name;
        return def;
    };

    function StrGetCode(str:string, lnum:number) {
        LogDebug("DO:", str);
        var stp = str.indexOf('{');
        if (stp>=0)
            str = str.substr(stp+1, str.length-stp-3);
        var flnhash = HashLine(lnum, str);
        self.outcode += flnhash+str+'\n';
    };

    self.parmFlags = ("isSpecified,IO,RO,noDupValue,noClear,pass2,dbDirty,dbIgnore,dbRowid,"
        +"nocase,forceInt,bitsetBool,dateOnly,timeOnly,isBits,fmtString,fmtNumber,fmtTime,fmtHex,strict,fieldSetup,"

        +"coerce,noSig,enumSpec,enumUnsigned,enumExact").split(',');

    function ParseFlags(rest:string) {
        debugger;
        if (rest.substr(0,1) !== '<')
            return;
        var ext = null, ree = rest.indexOf('>');
        if (ree<0)
            throw("expected end bracket: "+rest);
        debugger;
        var parms = rest.substr(1, ree-1);
        rest = rest.substr(ree+1).trim();
        LogTrace('parms:', parms);
        var pf = self.parmFlags;
        var f = 0;
        for (var o of parms.split(';')) {
            o = o.trim();
            var oi = pf.indexOf(o);
            if (oi<0) {
                if (o.substr(0,5) === 'FUNC(' && o.substr(o.length-1,1) === ')') {
                    ext = o.substr(5, o.length-6);
                    continue;
                } else
                    throw("unknown flag '"+o+"' expected on of: FUNC() ,"+pf.join(', '));
            }
            f |= (1<<oi);
        }
        return [f, rest, ext];
    }

    function StrGetStruct(str:string, lnum:number) {
        LogDebug("DO: "+str);
        var flds = [], fcnt = 0;
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad def: " + str);
        var label, def = {name:ina[2], type:ina[1], opts:null, label:null, init:true, lnum:lnum};
        var li, l = str.trim().split('\n');
        if ((li=l[0].indexOf('//'))>0) {
            label = l[0].substr(li+2).trim();
            def.label = label;
        }
        l = l.splice(1, l.length-2);
        var dfn = def.name+'_Specs';
        if (self.structmap[dfn])
            throw("duplicate struct name");
        self.structmap[def.name] = dfn;
        for (var i in l) {
            var res = {label:'', bit:0, bitset:0, asize:0, flags:0, isstr:false, nowarn:false, data:null};
            var v = l[i].trim();
            LogTrace("v:". v);
            if (v.match(/^<.*>$/)) {
                if (def.opts) throw("multiple opts");
                LogDebug("OPTS:", v);
                def.opts = v.substr(1,v.length-2);
                continue;
................................................................................
            var s = v.match(/^\s*(\S+)\s+([^;]+)\s*;\s*(.*)$/);
            LogTrace('SS:', v);
            if (s === null || s.length < 2)
                throw('invalid field: "'+v+'"');
            res.id = spref + s[1];
            var namval = s[2].trim();
            var rest = s[3].trim();





            label = rest;
            if (label !== "") {
                if (label.substr(0,2) !== '//')
                    throw('expected // after definition: '+label);
                label = label.substr(2).trim();
                if (label.substr(0, 7) === 'NOWARN:') {
                    res.nowarn = true;
                    label = label.substr(7).trim();
                }
            }
            var pfi = ParseFlags(label);
            if (pfi) {
                res.flags = pfi[0].toString(16);
                res.data = pfi[2];
                label = pfi[1];
            }
            res.label = label.trim();
            var nam = namval, val = null, nn;
            if (nam.indexOf('=')>=0)
            {
                nn = nam.split('=');
                if (nn.length != 2)
................................................................................
            LogTrace('res:', res);
            flds.push(res);
        }
        def.flds = flds;
        return def;
    }
    
    function StrGetVars(str:string, lnum:number) {
        LogDebug("DO: "+str);
        var flds = [];
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad vars def: " + str);
        var label, def = {name:ina[2], type:ina[1]};
        var l = str.trim().split('\n');
        l = l.splice(1, l.length-2);
        for (var i in l) {
            var res = {label:'', asize:0, opts:'', ismap:false, ktype:null, varParam:'', lnum:lnum};
            var v = l[i].trim();
            LogTrace("v:", v);
            if (v === '') continue;
            if (flds.length == 0 && v.substr(0,2) === '//') {
                label = v.substr(2).trim();
                if (!def.label)
                    def.label = label;
................................................................................
            LogTrace('res:', res);
            flds.push(res);
        }
        def.flds = flds;
        return def;
    }

    function StrGetCmd(str:string, lnum:number) {
        LogDebug("DO:", str);
        var ina = str.match(/^([a-zA-Z0-9_]+)\s+([a-zA-Z0-9_]+)\s*=\s*\{/);
        if (!ina)
            throw("bad cmds def: " + str);
        var preface = '';;
        var label, sdefs=[], def = {name:ina[2], type:ina[1], fnames:[], lnum:lnum};
        var curdef = '', fcnt = 0;
        var l = str.split('\n'), li;
        if ((li=l[0].indexOf('//'))>0) {
            label = l[0].substr(li+2).trim();
            def.label = label;
        }
        l = l.splice(1, l.length-2);
        var nam = def.name, clnofs = -1;

        for (var i of l) {
            clnofs++;
            var ipre = i.trim();
            /*if (curdef == '' && ipre.substr(0,2) === '//') {
                label = ipre.substr(2).trim();
                if (!def.label)
                    def.label = label;
                else
                    throw("multiline label not allowed: "+ipre);
                continue;
            }*/
            var reg;
            if ((reg=ipre.match(/^function\s*(~|[a-zA-Z0-9_]*)/))) {
                fcnt++;
                def.fnames.push(reg[1]);
                if (curdef !== '') {
                    sdefs.push([curdef, clnofs]);
                    curdef = '';
                }
            } else if (curdef === '') {
                if (fcnt === 0) {
                    preface += i + '\n';
                    continue;
                }
                throw("expected function: "+i);
            }
            curdef += i + '\n';
        }
        if (curdef != '') {
            sdefs.push([curdef, clnofs]);
            curdef = '';
        }
        LogTrace("sdefs:", sdefs.join(','));
        def.flds = sdefs;
        def.preface = preface;
        return def;
    }

    function GetIncludeReg(match, file) {
        str = File.read(file);
        return GetInclude(str);
    }
    
    /*function GetInclude(str:string) {
        if (str.indexOf('include')<0)
            return str;
        return str.replace(/^include\s*=\s*([a-zA-Z0-9_.]+)\s*;$/gm, GetIncludeReg);
    }*/
    
    // Gather all the definitions 
    function GetDefs(str) {
        var curdef = '', gdefs = [], slst, cnt = 0, lcnt = 1;
        //str = GetInclude(str);
        slst = str.split('\n');
        for (var i of slst) {
            cnt++;
            var ipre = i.trim().substr(0,2);
            //if (ipre === '//' || ipre == '') { continue; }
            if (i.trimRight() === '};') {
                //if (curdef === '') throw("extraextra end found at line "+cnt);
                curdef += i;
                gdefs.push([curdef.trim(), lcnt+self.lnstart+1]);
                lcnt = cnt;
                curdef = '';
                continue;
            }
            if (curdef.trim() === ''  && i.indexOf('//')<0 && i.indexOf(';')>=0)
                throw("defn can not be all on one line: "+i);
            curdef += i + '\n';
        }
        if (curdef.trim() !== '') throw("extra input found at end");
        return gdefs;
    }
    
    function mainSub() {
        if (typeof args !== 'array' || !args.length)
            throw "expected 1 or more args";
        
        if (self.cflags)
            return GetCflags();
    
        if (args.length)
            self.rootname = File.rootname(File.tail(args[0]));
        if (self.O !== '-') {
            if (self.O !== '')
                self.outFile = self.O;
            else if (self.rootname)
                self.outFile = self.rootname+'.c';
        }
        if (!self.name)
            if (self.rootname)
                self.name = self.rootname;
            else
                self.name = 'main';
        if (args.length != 1)
            throw('expected a single file arg');
        var fname = args[0];
        self.infile = fname;
        var inp = self.indata = File.read(fname);
        if (inp.substr(0,2) === '#!') {

            self.lnstart++;
            inp = inp.substr(inp.indexOf('\n')+1);
        }
        while (inp.substr(0,2) === '//') {
            self.lnstart++;
            inp = inp.substr(inp.indexOf('\n')+1);
        }

        var ina = GetDefs(inp);
        //var ina = inp.match(/([a-zA-Z0-9_]+\s+\S+\s*\{[^\}]+\};)/g);
        LogTrace('INA:', ina);
        for (var j of ina) {
            var i = j[0];
            var ln = j[1];
            LogTrace("i:", i);

            var in1 = i.match(/^([a-zA-Z0-9_]+)\s+[a-zA-Z0-9_]+\s*=\s*\{/);
            if (!in1)
                throw("unknown input: "+i);
            var nam = in1[1];
            switch (nam) {
                case 'code':    StrGetCode(i, ln); break;
                case 'enum':    defs.enums.push(StrGetEnum(i, ln)); break;
                case 'struct':  defs.structs.push(StrGetStruct(i, ln)); break;
                //case 'types':    defs.types.push(StrGetTypes(i)); break;
                case 'vars':    defs.vars.push(StrGetVars(i, ln)); break;
                case 'extension':  defs.cmds.push(StrGetCmd(i, ln)); break;
                default: throw("unknown defn ' "+nam+"' expected: output, struct, enum, vars, extension");
            }
        }
        if (self.json)
            return JSON.stringify(defs);
        GenAllItems(defs);
        if (self.eval) {
            puts(EV);
................................................................................
    Jsi_OptionsFree(cmdPtr->interp, Demo_Specs, cmdPtr, 0);
    memset(cmdPtr, 0, sizeof(*cmdPtr));;
}

static Jsi_RC DemoObjFree(Jsi_Interp *interp, void *data)
{
    Demo *cmdPtr = (Demo *)data;
    %s /* FREE_OBJ */


    DemoObjErase(cmdPtr);
    Jsi_Free(cmdPtr);
    return JSI_OK;
}

static bool DemoObjIsTrue(void *data)
{
................................................................................
        _ = (Demo_ *)Jsi_InterpGetData(interp, "Demo_InterpData", NULL);
    else {
        _ = (Demo_ *)Jsi_Calloc(1, sizeof(Demo_));
        Jsi_InterpSetData(interp, "Demo_InterpData", _, Jsi_DeleteData);
    }
    ddPtr = (void*)_;
#endif

    %s /* INIT_DONE */

#ifdef CDATA_CODE_PER_INTERP_Demo
    if (isRelease)
        Jsi_InterpFreeData(interp, "Demo_InterpData");
#endif
    if (!isRelease) {
        Jsi_VarRef vr = {};
#if (defined(CDATA_CODE_GLOB_VAR_Demo) || defined(CDATA_CODE_PER_INTERP_Demo))

lib/Jsi_Csspp.jsi became executable.

Changes to lib/Jsi_Debug.jsi.

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            nlev = 1;
        else if (nlev>self.toplev)
            nlev = self.toplev;
        self.curlev = nlev;
        var val = self.interp.eval('Info.level('+nlev+')');
        self.curfile = val.fileName;
        self.curline = val.line;
        self.curfunc = funcName;
        //puts("UP: "+amt+' = '+nlev+' top='+self.toplev);
        //puts("VAL: "+val.toString());
        showPos(val.fileName, val.line, val.funcName);
    }

    // Show current position.
    function showPos(file:string, line:number, func:string) {







|







316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            nlev = 1;
        else if (nlev>self.toplev)
            nlev = self.toplev;
        self.curlev = nlev;
        var val = self.interp.eval('Info.level('+nlev+')');
        self.curfile = val.fileName;
        self.curline = val.line;
        self.curfunc = val.funcName;
        //puts("UP: "+amt+' = '+nlev+' top='+self.toplev);
        //puts("VAL: "+val.toString());
        showPos(val.fileName, val.line, val.funcName);
    }

    // Show current position.
    function showPos(file:string, line:number, func:string) {

lib/Jsi_GenDeep.jsi became executable.

Changes to lib/Jsi_Help.jsi.

1

2
3
4
5
6
7
8
...
194
195
196
197
198
199
200
201

202
203
204
205
206
207
208
209
210
211
212
213
214
...
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/local/bin/jsish %s -Debug true Socket.conf


require('Jsish');

function Jsi_Help(args:array, conf:object=void) {

    var options = { // Provide help for Jsi commands.
        max         :32,        // Max lines to output, if not web
................................................................................
                if (tinf.options)
                    aastr = LinkOpts(aastr, "new "+cnam);
                rv += "<tr><td>"+cnam+"</td><td>new "+cnam+"("+aastr+")"+tret+" </td><td>"+conhelp+'</td></tr>\n';
            }
        }
        if (cmds !== undefined) {
            for (var cmd of cmds) {
                var namspl = cmd.split('.'), nam = namspl[namspl.length-1], tret = '';

                if (nam == cnam)
                    continue;
                ci = Info.cmds(cnam+'.'+nam);
                if (ci.retType !== "any")
                    tret = ':'+ci.retType;
                var conhelp = (ci.help?ci.help+'.':'');
                if (ci.info) conhelp += ' '+ci.info;
                if (ci.options) {
                    if (!clnknam) clnknam=nam;
                    if (!tinf.constructor || nam !== 'conf')
                        ro += DumpOpts(ci.options, ci.optHelp, cnam+'.'+nam, cnam+'.conf');
                    aastr = LinkOpts(ci.args, cnam+'.'+nam);
                } else {
................................................................................
        if (tinf.options && nam !== 'conf')
            rv += DumpOpts(tinf.options, tinf.optHelp, 'new '+cnam, cnam+'.'+'conf');
        rv += ro;
        if (web) {
            rv += '<a name="'+tinf.name+'end"></a>\n';
            rv += '<p><a href="#TOC">Return to top</a>\n';
        }
        for (var ci of subs)
            rv += DumpObj(ci);
        return rv;
    }
    
    function dumpWeb() {
    
        var rv = '<title>Reference</title>\n<p>', tinf, lst = Info.cmds();

>







 







|
>





|







 







|







1
2
3
4
5
6
7
8
9
...
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
...
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/local/bin/jsish %s -Debug true Socket.conf
"use strict";

require('Jsish');

function Jsi_Help(args:array, conf:object=void) {

    var options = { // Provide help for Jsi commands.
        max         :32,        // Max lines to output, if not web
................................................................................
                if (tinf.options)
                    aastr = LinkOpts(aastr, "new "+cnam);
                rv += "<tr><td>"+cnam+"</td><td>new "+cnam+"("+aastr+")"+tret+" </td><td>"+conhelp+'</td></tr>\n';
            }
        }
        if (cmds !== undefined) {
            for (var cmd of cmds) {
                var namspl = cmd.split('.'), nam = namspl[namspl.length-1];
                tret = '';
                if (nam == cnam)
                    continue;
                ci = Info.cmds(cnam+'.'+nam);
                if (ci.retType !== "any")
                    tret = ':'+ci.retType;
                conhelp = (ci.help?ci.help+'.':'');
                if (ci.info) conhelp += ' '+ci.info;
                if (ci.options) {
                    if (!clnknam) clnknam=nam;
                    if (!tinf.constructor || nam !== 'conf')
                        ro += DumpOpts(ci.options, ci.optHelp, cnam+'.'+nam, cnam+'.conf');
                    aastr = LinkOpts(ci.args, cnam+'.'+nam);
                } else {
................................................................................
        if (tinf.options && nam !== 'conf')
            rv += DumpOpts(tinf.options, tinf.optHelp, 'new '+cnam, cnam+'.'+'conf');
        rv += ro;
        if (web) {
            rv += '<a name="'+tinf.name+'end"></a>\n';
            rv += '<p><a href="#TOC">Return to top</a>\n';
        }
        for (ci of subs)
            rv += DumpObj(ci);
        return rv;
    }
    
    function dumpWeb() {
    
        var rv = '<title>Reference</title>\n<p>', tinf, lst = Info.cmds();

Changes to lib/Jsi_Htmlpp.jsi.

1

2
3
4
5
6
7
8
#!/usr/bin/env jsish


require('Jsish');

/*
 * Preprocess html, css and js within the webserver. Evaluates javascript between  <? ?> tags (like php).
 * Evaluation occurs within a subinterp to which defines 2 new commands: include(file,...) and echo(str).
 */

>







1
2
3
4
5
6
7
8
9
#!/usr/bin/env jsish
"use strict";

require('Jsish');

/*
 * Preprocess html, css and js within the webserver. Evaluates javascript between  <? ?> tags (like php).
 * Evaluation occurs within a subinterp to which defines 2 new commands: include(file,...) and echo(str).
 */

Changes to lib/Jsi_Jspp.jsi.

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            self.tail = File.tail(File.rootname(self.curFile));
            var s = File.read(self.curFile);
            rc += s.replace(reg, reMethod);
        }
        if (self.listFuncs) {
            rc = '';
            var n = 0;
            for (var i of self.funcLst.sort())
                rc += i + ':' + i + (++n === self.funcLst.length ? '' : ',') + '\n';
        }
        return rc;
    }
    if (files)
        return parse(files);








|







131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            self.tail = File.tail(File.rootname(self.curFile));
            var s = File.read(self.curFile);
            rc += s.replace(reg, reMethod);
        }
        if (self.listFuncs) {
            rc = '';
            var n = 0;
            for (i of self.funcLst.sort())
                rc += i + ':' + i + (++n === self.funcLst.length ? '' : ',') + '\n';
        }
        return rc;
    }
    if (files)
        return parse(files);

Changes to lib/Jsi_Make.jsi.

1

2
3
4
5
6
7
8
...
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
#!/usr/local/bin/jsish


function Jsi_Make(files:array|string=null, opts:object=undefined):number
{
    var options = {
        debug:false,     // Debugging level.
        file:'Make.jsi', // File to use as the make file.
        nocache:false,   // Disable caching of dependancies.
................................................................................
        var rule = RULE[tdeps];
        
        if (rule) {
            if (RULESDONE[tdeps] !== undefined && !that.nocache)
                return true;
            RULESDONE[tdeps] = target;
        } else if (!DEP[tdeps]) { // Implicits
            var next = File.extension(target), bn = File.rootname(target), text, iext;
            if (text=EXTMAP[next]) {
                for (var ifnam of text) {
                    if (File.exists(bn+ifnam)) {
                        iext=ifnam;
                        break;
                    }
                }

>







 







|







1
2
3
4
5
6
7
8
9
...
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/local/bin/jsish
"use strict";

function Jsi_Make(files:array|string=null, opts:object=undefined):number
{
    var options = {
        debug:false,     // Debugging level.
        file:'Make.jsi', // File to use as the make file.
        nocache:false,   // Disable caching of dependancies.
................................................................................
        var rule = RULE[tdeps];
        
        if (rule) {
            if (RULESDONE[tdeps] !== undefined && !that.nocache)
                return true;
            RULESDONE[tdeps] = target;
        } else if (!DEP[tdeps]) { // Implicits
            next = File.extension(target), bn = File.rootname(target), text, iext;
            if (text=EXTMAP[next]) {
                for (var ifnam of text) {
                    if (File.exists(bn+ifnam)) {
                        iext=ifnam;
                        break;
                    }
                }

lib/Jsi_Markdown.jsi became executable.

Changes to lib/Jsi_Module.jsi.

1

2
3
4
5
6
7
8
#! /usr/bin/env jsish


require('Jsi', '2.4');

function Jsi_Module(args:array, conf:object=void) {

    var options = { // Run or create a Jsi module.
        create  :'',        // Create a Jsi module template with this name.

>







1
2
3
4
5
6
7
8
9
#! /usr/bin/env jsish
"use strict";

require('Jsi', '2.4');

function Jsi_Module(args:array, conf:object=void) {

    var options = { // Run or create a Jsi module.
        create  :'',        // Create a Jsi module template with this name.

Changes to lib/Jsi_Proxy.jsi.

1

2
3
4
5
6
7
8
...
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env jsish


require('Jsish');

// Create a websocket-capabled proxy web server.(UNFINISHED)

require('WebSocket');
require('Jsi_Vfs');
................................................................................
        puts('OPEN:', url);
        switch (u[2]) {
            case 'sqliteui':
                var nobj = Jsi_SqliteUI("~/tmp/test2.db", {wsObj:self.ws, wsId:id, Debug:true});
                break;
            case 'jsifs':
                require('Ledger');
                var nobj = Ledger([], {wsObj:self.ws, wsId:id, Debug:true});
                break;
            default:
                puts("UNKNOWN WSOPEN "+u[2]);
        }
    }
    
    function onFilter(id:number, urlprot:string, ishttp:boolean) {

>







 







|







1
2
3
4
5
6
7
8
9
...
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env jsish
"use strict";

require('Jsish');

// Create a websocket-capabled proxy web server.(UNFINISHED)

require('WebSocket');
require('Jsi_Vfs');
................................................................................
        puts('OPEN:', url);
        switch (u[2]) {
            case 'sqliteui':
                var nobj = Jsi_SqliteUI("~/tmp/test2.db", {wsObj:self.ws, wsId:id, Debug:true});
                break;
            case 'jsifs':
                require('Ledger');
                nobj = Ledger([], {wsObj:self.ws, wsId:id, Debug:true});
                break;
            default:
                puts("UNKNOWN WSOPEN "+u[2]);
        }
    }
    
    function onFilter(id:number, urlprot:string, ishttp:boolean) {

Changes to lib/Jsi_Safe.jsi.

1

2
3
4
5
6
7
8
#! /usr/bin/env jsish


require('Jsish');

function Jsi_Safe(fileargs:array, conf:object=void) {

    var options = { // Run script in safe interpreter and return value. With a dir or no arg runs interactively.
        evalStr     :'',        // Code-string to eval instead of sourcing filearg.

>







1
2
3
4
5
6
7
8
9
#! /usr/bin/env jsish
"use strict";

require('Jsish');

function Jsi_Safe(fileargs:array, conf:object=void) {

    var options = { // Run script in safe interpreter and return value. With a dir or no arg runs interactively.
        evalStr     :'',        // Code-string to eval instead of sourcing filearg.

Changes to lib/Jsi_SqliteUI/Jsi_SqliteUI.jsi.

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
...
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
                case 'Add':
                case 'Duplicate':
                    for (var i in res) {
                        if (cols != '') { cols += ','; vals += ','; }
                        cols += '"'+i+'"';
                        vals += "$res("+i+")";
                    }
                    var q = 'INSERT INTO "'+ d.table+'" ('+cols+") VALUES("+vals+");";
                    db.query(q);
                    break;
                    
                case 'Update':
                    for (var i in res) {
                        if (vals != '') { vals += ','; }
                        vals += i+" = $res("+i+")";
                    }
                    var q = "UPDATE "+d.table+" SET "+vals+" WHERE rowid = "+d.id+";";
                    db.query(q);
                    break;
                default:
                    LogDebug("WTF: tvalsSubmit: "+d.tag);
            }
            WsSend(id,"tvalsSubmitAck",{result:true, tag:d.tag, table:d.table, from:'tvalsSubmit'});
        }
................................................................................
            self.wsopts.noCompress = true;
        if (self.server) {
            self.closeTimeout = 0;
            self.noGui = true;
        }
        self.cleanup = cleanup;
        /* Open websockets on first available port. */
        var i, emsg = '';
        if (self.wsObj && self.wsId) {
            // External proxy
            self.ws = self.wsObj;
            self.wsObj.idconf(self.wsId, {onRecv:WsRecv, rootdir:self.rootdir});
            self.noUpdate = 1;
            self.noGui = 1;
            return self;







|




|



|







 







|







120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
...
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
                case 'Add':
                case 'Duplicate':
                    for (var i in res) {
                        if (cols != '') { cols += ','; vals += ','; }
                        cols += '"'+i+'"';
                        vals += "$res("+i+")";
                    }
                    q = 'INSERT INTO "'+ d.table+'" ('+cols+") VALUES("+vals+");";
                    db.query(q);
                    break;
                    
                case 'Update':
                    for (i in res) {
                        if (vals != '') { vals += ','; }
                        vals += i+" = $res("+i+")";
                    }
                    q = "UPDATE "+d.table+" SET "+vals+" WHERE rowid = "+d.id+";";
                    db.query(q);
                    break;
                default:
                    LogDebug("WTF: tvalsSubmit: "+d.tag);
            }
            WsSend(id,"tvalsSubmitAck",{result:true, tag:d.tag, table:d.table, from:'tvalsSubmit'});
        }
................................................................................
            self.wsopts.noCompress = true;
        if (self.server) {
            self.closeTimeout = 0;
            self.noGui = true;
        }
        self.cleanup = cleanup;
        /* Open websockets on first available port. */
        var emsg = '';
        if (self.wsObj && self.wsId) {
            // External proxy
            self.ws = self.wsObj;
            self.wsObj.idconf(self.wsId, {onRecv:WsRecv, rootdir:self.rootdir});
            self.noUpdate = 1;
            self.noGui = 1;
            return self;

Changes to lib/Jsi_UnitTest.jsi.

1

2
3
4
5
6
7
8
...
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#! /usr/bin/env jsish


require('Jsish');

function Jsi_UnitTest(fileargs:array, conf:object=void):number {

    var options = { // Run script(s) as unit-tests; return code is the number of failed tests.
        args        :'',        // Argument string to call script with
................................................................................
            printf('Test '+fn+' ');
       if (self.times)
            puts("");
         var eopts = {};
        if (input!=='')
            eopts.input = input;
        var res = null;
        var fail = false;
        var emsg = "ERROR: ";
        var etime, stime = strptime();
        try {
            if (!self.exec) {
                siargs.stdoutStr = '';
                //siargs.scriptFile = fn;
                siargs.args = self.args.split(' ');

>







 







|







1
2
3
4
5
6
7
8
9
...
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#! /usr/bin/env jsish
"use strict";

require('Jsish');

function Jsi_UnitTest(fileargs:array, conf:object=void):number {

    var options = { // Run script(s) as unit-tests; return code is the number of failed tests.
        args        :'',        // Argument string to call script with
................................................................................
            printf('Test '+fn+' ');
       if (self.times)
            puts("");
         var eopts = {};
        if (input!=='')
            eopts.input = input;
        var res = null;
        fail = false;
        var emsg = "ERROR: ";
        var etime, stime = strptime();
        try {
            if (!self.exec) {
                siargs.stdoutStr = '';
                //siargs.scriptFile = fn;
                siargs.args = self.args.split(' ');

Changes to lib/Jsi_Vfs.jsi.

1

2
3
4
5
6
7
8
#!/usr/bin/env jsish


function Jsi_Vfs(args:array=void, conf:object=void):void
{
    var options = { // Mount a zip, sqlar, or fossil repository as Virtual File System
        dumpVers    :false,     // Dump version info.
        quiet       :false,     // Suppress info msgs.
        safe        :false,     // Forces use of Vfs.exec (which is always used by Safe-interps).

>







1
2
3
4
5
6
7
8
9
#!/usr/bin/env jsish
"use strict";

function Jsi_Vfs(args:array=void, conf:object=void):void
{
    var options = { // Mount a zip, sqlar, or fossil repository as Virtual File System
        dumpVers    :false,     // Dump version info.
        quiet       :false,     // Suppress info msgs.
        safe        :false,     // Forces use of Vfs.exec (which is always used by Safe-interps).

Changes to lib/Jsi_Websrv.jsi.

1

2
3
4
5
6
7
8
#!/usr/bin/env jsish


require('Jsish');
require('WebSocket', '2');

function Jsi_Websrv(args:string|array, conf:object=void):void
{
    var self = {

>







1
2
3
4
5
6
7
8
9
#!/usr/bin/env jsish
"use strict";

require('Jsish');
require('WebSocket', '2');

function Jsi_Websrv(args:string|array, conf:object=void):void
{
    var self = {

Changes to lib/Jsi_Wget.jsi.

1

2
3
4
5
6
7
8
#!/usr/bin/env jsish


function Jsi_Wget(fileargs:array|string, conf:object=void) {
    
    var options = { // Web client for downloading files from url
        force       : false,        // Overwrite output file, if exists.
        headers     : [],           // Header fields to send.
        nowait      : false,        // Just return object: caller will call update.

>







1
2
3
4
5
6
7
8
9
#!/usr/bin/env jsish
"use strict";

function Jsi_Wget(fileargs:array|string, conf:object=void) {
    
    var options = { // Web client for downloading files from url
        force       : false,        // Overwrite output file, if exists.
        headers     : [],           // Header fields to send.
        nowait      : false,        // Just return object: caller will call update.

Changes to lib/Jsi_Zip.jsi.

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        for (var i of cmdList) {
            if (i[0] == args[0]) {
                return i[1].apply(null, args.slice(1));
            }
        }
    }
    var emsg = 'Arg 1 must be one of:\n';
    for (var i of cmdList) {
        emsg += '  ' + i[0] + '      \t: ' + i[2] + '\n';
    }
    throw(emsg); 
}

provide("Jsi_Zip", 1.0);

if (Info.isMain()) {
    //exit(Jsi_Zip(console.args));
    runModule(Jsi_Zip);
}







|











149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
        for (var i of cmdList) {
            if (i[0] == args[0]) {
                return i[1].apply(null, args.slice(1));
            }
        }
    }
    var emsg = 'Arg 1 must be one of:\n';
    for (i of cmdList) {
        emsg += '  ' + i[0] + '      \t: ' + i[2] + '\n';
    }
    throw(emsg); 
}

provide("Jsi_Zip", 1.0);

if (Info.isMain()) {
    //exit(Jsi_Zip(console.args));
    runModule(Jsi_Zip);
}

Changes to lib/Jsish.jsi.



1
2
3
4
5
6
7
..
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
...
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
...
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181


// Parse command line options and other utilities.
source('autoload.jsi', {once:true}); // Chains autoload to provide Jsish.

/*
=!EXPECTSTART!=
RC=1 { a:2, b:1, c:2 }
RC=1 { a:3, b:1, c:2 }
................................................................................
        var fn = Info.argv0();
        if (fn)
            pkg = File.rootname(File.tail(fn));
    }
    if (pkg) {
        // Pull comments from options object, if possible
        try {
            var pkg = require(pkg, 0);
            if (pkg && pkg.loadFile) {
                var fdat = File.read(pkg.loadFile);
                var re = fdat.match(/var options\s*=\s*\{([^\}]+)/);
                if (re) {
                    var st, sc, sd, sn, si = re[1].split('\n');
                    for (var i in si) {
                        if (!si[i]) continue;
................................................................................
                        help[sn] = st.substr(sc).trim();
                    }
                }
            }
        } catch (e) {}
    }
    rc += '\nOptions/defaults:\n';
    for (var i in options) {
        var ost = options[i];
        if (typeof ost === 'string')
            ost = '"'+ost+'"';
        else if (ost === null)
            ost = 'null';
        else
            ost = ost.toString();
................................................................................
function Jsi_Conf (self:object, options:object, opts:object|null=undefined):object {
    puts("NOTE: Jsi_Conf has been deprecated by parseOpts");
    var i, isarr, len, topts = {};
    for (i in options)
        self[i] = options[i];
    if (!opts)
        return self;
    var isarr = (typeof(opts) !== 'object');
    if (isarr) {
        // Convert array to object.
        if (opts.length%2) {
            if (opts[0] == '-h')
                Jsi_ThrowHelp(self, options);
            throw("Odd opts length: "+opts.toString());
        }
................................................................................
            dst = dst.substr(1);
            topts[dst] = opts[i+1];
        }
    } else
        for (i in opts)
            topts[i] = opts[i];
    i = 0;
    for (var dst in topts) {
        if (options && options[dst] === undefined) {
            if (dst == 'h')
                Jsi_ThrowHelp(self, options);
            var ret = "unknown option: '"+dst+"' not one of:\n  ";
            for (var i in options)
                if (i !== 'Jsi_Auto')
                    ret += i + ' ';
            throw(ret);
        }
        if (!isarr)
            switch (typeof self[dst]) {
            case "number":
>
>







 







|







 







|







 







|







 







|




|







1
2
3
4
5
6
7
8
9
..
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
...
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
...
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#! /usr/bin/env jsish
"use strict";
// Parse command line options and other utilities.
source('autoload.jsi', {once:true}); // Chains autoload to provide Jsish.

/*
=!EXPECTSTART!=
RC=1 { a:2, b:1, c:2 }
RC=1 { a:3, b:1, c:2 }
................................................................................
        var fn = Info.argv0();
        if (fn)
            pkg = File.rootname(File.tail(fn));
    }
    if (pkg) {
        // Pull comments from options object, if possible
        try {
            pkg = require(pkg, 0);
            if (pkg && pkg.loadFile) {
                var fdat = File.read(pkg.loadFile);
                var re = fdat.match(/var options\s*=\s*\{([^\}]+)/);
                if (re) {
                    var st, sc, sd, sn, si = re[1].split('\n');
                    for (var i in si) {
                        if (!si[i]) continue;
................................................................................
                        help[sn] = st.substr(sc).trim();
                    }
                }
            }
        } catch (e) {}
    }
    rc += '\nOptions/defaults:\n';
    for (i in options) {
        var ost = options[i];
        if (typeof ost === 'string')
            ost = '"'+ost+'"';
        else if (ost === null)
            ost = 'null';
        else
            ost = ost.toString();
................................................................................
function Jsi_Conf (self:object, options:object, opts:object|null=undefined):object {
    puts("NOTE: Jsi_Conf has been deprecated by parseOpts");
    var i, isarr, len, topts = {};
    for (i in options)
        self[i] = options[i];
    if (!opts)
        return self;
    isarr = (typeof(opts) !== 'object');
    if (isarr) {
        // Convert array to object.
        if (opts.length%2) {
            if (opts[0] == '-h')
                Jsi_ThrowHelp(self, options);
            throw("Odd opts length: "+opts.toString());
        }
................................................................................
            dst = dst.substr(1);
            topts[dst] = opts[i+1];
        }
    } else
        for (i in opts)
            topts[i] = opts[i];
    i = 0;
    for (dst in topts) {
        if (options && options[dst] === undefined) {
            if (dst == 'h')
                Jsi_ThrowHelp(self, options);
            var ret = "unknown option: '"+dst+"' not one of:\n  ";
            for (i in options)
                if (i !== 'Jsi_Auto')
                    ret += i + ' ';
            throw(ret);
        }
        if (!isarr)
            switch (typeof self[dst]) {
            case "number":

lib/autoload.jsi became executable.

Changes to src/jsi.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
.....
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712








19713
19714
19715
19716
19717
19718
19719
.....
65969
65970
65971
65972
65973
65974
65975
65976
65977
65978
65979
65980
65981
65982
65983
.....
66148
66149
66150
66151
66152
66153
66154
66155
66156
66157
66158
66159
66160
66161
66162
66163
66164
66165
66166
66167
66168
66169
66170
66171
66172
66173
66174
.....
66228
66229
66230
66231
66232
66233
66234
66235
66236
66237
66238
66239
66240
66241
66242
.....
66251
66252
66253
66254
66255
66256
66257
66258
66259
66260
66261
66262
66263
66264
66265
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 16

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
Jsi_ScopeStrs *jsi_ScopeStrsNew(void);
void jsi_ScopeStrsPush(Jsi_Interp *interp, Jsi_ScopeStrs *ss, const char *string, int argType);
void jsi_ScopeStrsFree(Jsi_Interp *interp, Jsi_ScopeStrs *ss);
const char *jsi_ScopeStrsGet(Jsi_ScopeStrs *ss, int i);

void jsi_PstatePush(jsi_Pstate *ps);
void jsi_PstatePop(jsi_Pstate *ps);
void jsi_PstateAddVar(jsi_Pstate *ps, const char *str);
Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps);

void jsi_PstateFree(jsi_Pstate *ps);
jsi_Pstate *jsi_PstateNew(Jsi_Interp *interp);
void jsi_PstateClear(jsi_Pstate *ps);
const char * jsi_PstateGetFilename(jsi_Pstate *ps);
int jsi_PstateSetFile(jsi_Pstate *ps, Jsi_Channel fp, int skipbang);
................................................................................
        return;
    }
    jsi_ScopeStrsFree(interp, interp->scopes[interp->cur_scope]);
    interp->scopes[interp->cur_scope] = NULL;
    interp->cur_scope--;
}

void jsi_PstateAddVar(jsi_Pstate *ps, const char *str)
{
    Jsi_Interp *interp = ps->interp;
    int i;
    if (interp->scopes[interp->cur_scope] == NULL)
        interp->scopes[interp->cur_scope] = (Jsi_ScopeStrs *)jsi_ScopeStrsNew();
    
    for (i = 0; i < interp->scopes[interp->cur_scope]->count; ++i) {
        if (Jsi_Strcmp(str, interp->scopes[interp->cur_scope]->args[i].name) == 0) return;








    }
    jsi_ScopeStrsPush(ps->interp, interp->scopes[interp->cur_scope], str, JSI_VT_UNDEF);
}

Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps)
{
    Jsi_Interp *interp = ps->interp;
................................................................................
        (yyval.opcodes) = ret;
    }
    break;

  case 27:
    {
        if (!pstate->eval_flag) {
            jsi_PstateAddVar(pstate, (yyvsp[0].str));
        }
        (yyval.str) = (yyvsp[0].str);
    }
    break;

  case 28:
    { (yyval.opcodes) = (yyvsp[0].opcodes); }
................................................................................

  case 52:
    {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &(yylsp[0]), (yyvsp[0].str), 1),
                            code_push_undef(),
                            code_assign(pstate, &(yylsp[0]), 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, (yyvsp[0].str));
        else ret = codes_join(code_local(pstate, &(yylsp[0]), (yyvsp[0].str)), ret);
        (yyval.opcodes) = ret;
    }
    break;

  case 53:
    {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &(yylsp[-2]), (yyvsp[-2].str), 1),
                            (yyvsp[0].opcodes),
                            code_assign(pstate, &(yylsp[-2]), 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, (yyvsp[-2].str));
        else ret = codes_join(code_local(pstate, &(yylsp[-2]), (yyvsp[-2].str)), ret);
        (yyval.opcodes) = ret;
    }
    break;

  case 54:
    {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &(yylsp[-7]), fv->varname, 1);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &(yylsp[-7]), (yyvsp[-2].opcodes), (yyvsp[0].opcodes), (yyvsp[-8].str), (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate,fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        (yyval.opcodes) = ret;
    }
    break;
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &(yylsp[-7]), fv->varname, 0);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &(yylsp[-6]), (yyvsp[-2].opcodes), (yyvsp[0].opcodes), (yyvsp[-7].str), (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate,fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        (yyval.opcodes) = ret;
    }
    break;






|







 







|







 







|







|
>
>
>
>
>
>
>
>







 







|







 







|











|







 







|







 







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
.....
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
.....
65977
65978
65979
65980
65981
65982
65983
65984
65985
65986
65987
65988
65989
65990
65991
.....
66156
66157
66158
66159
66160
66161
66162
66163
66164
66165
66166
66167
66168
66169
66170
66171
66172
66173
66174
66175
66176
66177
66178
66179
66180
66181
66182
.....
66236
66237
66238
66239
66240
66241
66242
66243
66244
66245
66246
66247
66248
66249
66250
.....
66259
66260
66261
66262
66263
66264
66265
66266
66267
66268
66269
66270
66271
66272
66273
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 17

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
Jsi_ScopeStrs *jsi_ScopeStrsNew(void);
void jsi_ScopeStrsPush(Jsi_Interp *interp, Jsi_ScopeStrs *ss, const char *string, int argType);
void jsi_ScopeStrsFree(Jsi_Interp *interp, Jsi_ScopeStrs *ss);
const char *jsi_ScopeStrsGet(Jsi_ScopeStrs *ss, int i);

void jsi_PstatePush(jsi_Pstate *ps);
void jsi_PstatePop(jsi_Pstate *ps);
void jsi_PstateAddVar(jsi_Pstate *ps, jsi_Pline *line, const char *str);
Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps);

void jsi_PstateFree(jsi_Pstate *ps);
jsi_Pstate *jsi_PstateNew(Jsi_Interp *interp);
void jsi_PstateClear(jsi_Pstate *ps);
const char * jsi_PstateGetFilename(jsi_Pstate *ps);
int jsi_PstateSetFile(jsi_Pstate *ps, Jsi_Channel fp, int skipbang);
................................................................................
        return;
    }
    jsi_ScopeStrsFree(interp, interp->scopes[interp->cur_scope]);
    interp->scopes[interp->cur_scope] = NULL;
    interp->cur_scope--;
}

void jsi_PstateAddVar(jsi_Pstate *ps, jsi_Pline *line, const char *str)
{
    Jsi_Interp *interp = ps->interp;
    int i;
    if (interp->scopes[interp->cur_scope] == NULL)
        interp->scopes[interp->cur_scope] = (Jsi_ScopeStrs *)jsi_ScopeStrsNew();
    
    for (i = 0; i < interp->scopes[interp->cur_scope]->count; ++i) {
        if (Jsi_Strcmp(str, interp->scopes[interp->cur_scope]->args[i].name) == 0) {
            Jsi_Interp *interp = ps->interp;
            if (interp && jsi_IsStrictMode(interp)) {
                interp->parseLine = line;
                Jsi_LogType("duplicate var: %s", str);
                interp->parseLine = NULL;
            }
            return;
        }
    }
    jsi_ScopeStrsPush(ps->interp, interp->scopes[interp->cur_scope], str, JSI_VT_UNDEF);
}

Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps)
{
    Jsi_Interp *interp = ps->interp;
................................................................................
        (yyval.opcodes) = ret;
    }
    break;

  case 27:
    {
        if (!pstate->eval_flag) {
            jsi_PstateAddVar(pstate, &(yylsp[0]), (yyvsp[0].str));
        }
        (yyval.str) = (yyvsp[0].str);
    }
    break;

  case 28:
    { (yyval.opcodes) = (yyvsp[0].opcodes); }
................................................................................

  case 52:
    {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &(yylsp[0]), (yyvsp[0].str), 1),
                            code_push_undef(),
                            code_assign(pstate, &(yylsp[0]), 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, &(yylsp[0]), (yyvsp[0].str));
        else ret = codes_join(code_local(pstate, &(yylsp[0]), (yyvsp[0].str)), ret);
        (yyval.opcodes) = ret;
    }
    break;

  case 53:
    {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &(yylsp[-2]), (yyvsp[-2].str), 1),
                            (yyvsp[0].opcodes),
                            code_assign(pstate, &(yylsp[-2]), 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, &(yylsp[-2]), (yyvsp[-2].str));
        else ret = codes_join(code_local(pstate, &(yylsp[-2]), (yyvsp[-2].str)), ret);
        (yyval.opcodes) = ret;
    }
    break;

  case 54:
    {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &(yylsp[-7]), fv->varname, 1);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &(yylsp[-7]), (yyvsp[-2].opcodes), (yyvsp[0].opcodes), (yyvsp[-8].str), (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate, &(yylsp[-4]), fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        (yyval.opcodes) = ret;
    }
    break;
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &(yylsp[-7]), fv->varname, 0);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &(yylsp[-6]), (yyvsp[-2].opcodes), (yyvsp[0].opcodes), (yyvsp[-7].str), (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate, &(yylsp[-4]), fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        (yyval.opcodes) = ret;
    }
    break;

Changes to src/jsi.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 16

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 17

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

Changes to src/jsiInt.h.

742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
Jsi_ScopeStrs *jsi_ScopeStrsNew(void);
void jsi_ScopeStrsPush(Jsi_Interp *interp, Jsi_ScopeStrs *ss, const char *string, int argType);
void jsi_ScopeStrsFree(Jsi_Interp *interp, Jsi_ScopeStrs *ss);
const char *jsi_ScopeStrsGet(Jsi_ScopeStrs *ss, int i);

void jsi_PstatePush(jsi_Pstate *ps);
void jsi_PstatePop(jsi_Pstate *ps);
void jsi_PstateAddVar(jsi_Pstate *ps, const char *str);
Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps);

void jsi_PstateFree(jsi_Pstate *ps);
jsi_Pstate *jsi_PstateNew(Jsi_Interp *interp);
void jsi_PstateClear(jsi_Pstate *ps);
const char * jsi_PstateGetFilename(jsi_Pstate *ps);
int jsi_PstateSetFile(jsi_Pstate *ps, Jsi_Channel fp, int skipbang);







|







742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
Jsi_ScopeStrs *jsi_ScopeStrsNew(void);
void jsi_ScopeStrsPush(Jsi_Interp *interp, Jsi_ScopeStrs *ss, const char *string, int argType);
void jsi_ScopeStrsFree(Jsi_Interp *interp, Jsi_ScopeStrs *ss);
const char *jsi_ScopeStrsGet(Jsi_ScopeStrs *ss, int i);

void jsi_PstatePush(jsi_Pstate *ps);
void jsi_PstatePop(jsi_Pstate *ps);
void jsi_PstateAddVar(jsi_Pstate *ps, jsi_Pline *line, const char *str);
Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps);

void jsi_PstateFree(jsi_Pstate *ps);
jsi_Pstate *jsi_PstateNew(Jsi_Interp *interp);
void jsi_PstateClear(jsi_Pstate *ps);
const char * jsi_PstateGetFilename(jsi_Pstate *ps);
int jsi_PstateSetFile(jsi_Pstate *ps, Jsi_Channel fp, int skipbang);

Changes to src/jsiPstate.c.

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145








146
147
148
149
150
151
152
        return;
    }
    jsi_ScopeStrsFree(interp, interp->scopes[interp->cur_scope]);
    interp->scopes[interp->cur_scope] = NULL;
    interp->cur_scope--;
}

void jsi_PstateAddVar(jsi_Pstate *ps, const char *str)
{
    Jsi_Interp *interp = ps->interp;
    int i;
    if (interp->scopes[interp->cur_scope] == NULL)
        interp->scopes[interp->cur_scope] = (Jsi_ScopeStrs *)jsi_ScopeStrsNew();
    
    for (i = 0; i < interp->scopes[interp->cur_scope]->count; ++i) {
        if (Jsi_Strcmp(str, interp->scopes[interp->cur_scope]->args[i].name) == 0) return;








    }
    jsi_ScopeStrsPush(ps->interp, interp->scopes[interp->cur_scope], str, JSI_VT_UNDEF);
}

Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps)
{
    Jsi_Interp *interp = ps->interp;







|







|
>
>
>
>
>
>
>
>







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
        return;
    }
    jsi_ScopeStrsFree(interp, interp->scopes[interp->cur_scope]);
    interp->scopes[interp->cur_scope] = NULL;
    interp->cur_scope--;
}

void jsi_PstateAddVar(jsi_Pstate *ps, jsi_Pline *line, const char *str)
{
    Jsi_Interp *interp = ps->interp;
    int i;
    if (interp->scopes[interp->cur_scope] == NULL)
        interp->scopes[interp->cur_scope] = (Jsi_ScopeStrs *)jsi_ScopeStrsNew();
    
    for (i = 0; i < interp->scopes[interp->cur_scope]->count; ++i) {
        if (Jsi_Strcmp(str, interp->scopes[interp->cur_scope]->args[i].name) == 0) {
            Jsi_Interp *interp = ps->interp;
            if (interp && jsi_IsStrictMode(interp)) {
                interp->parseLine = line;
                Jsi_LogType("duplicate var: %s", str);
                interp->parseLine = NULL;
            }
            return;
        }
    }
    jsi_ScopeStrsPush(ps->interp, interp->scopes[interp->cur_scope], str, JSI_VT_UNDEF);
}

Jsi_ScopeStrs *jsi_ScopeGetVarlist(jsi_Pstate *ps)
{
    Jsi_Interp *interp = ps->interp;

Changes to src/parser.y.

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
        $$ = ret;
    }
;

func_prefix:
    FUNC IDENTIFIER %prec MAX_PRI {
        if (!pstate->eval_flag) {
            jsi_PstateAddVar(pstate, $2);
        }
        $$ = $2;
    }
;

iterstatement:
    for_statement   { $$ = $1; }
................................................................................

vardec:
    IDENTIFIER              {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &@1, $1, 1),
                            code_push_undef(),
                            code_assign(pstate, &@1, 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, $1);
        else ret = codes_join(code_local(pstate, &@1, $1), ret);
        $$ = ret;
    }
    | IDENTIFIER '=' expr   {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &@1, $1, 1),
                            $3,
                            code_assign(pstate, &@1, 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, $1);
        else ret = codes_join(code_local(pstate, &@1, $1), ret);
        $$ = ret;
    }
;

delete_statement:
    DELETE lvalue ';'           {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &@2, fv->varname, 1);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &@2, $7, $9, $1, (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate,fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        $$ = ret;
    }
    | label_opt FOR '(' lvalue inof expr ')' statement_or_empty {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &@1, fv->varname, 0);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &@2, $6, $8, $1, (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate,fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        $$ = ret;
    }
;







|







 







|








|







 







|







 







|







179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
...
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
        $$ = ret;
    }
;

func_prefix:
    FUNC IDENTIFIER %prec MAX_PRI {
        if (!pstate->eval_flag) {
            jsi_PstateAddVar(pstate, &@2, $2);
        }
        $$ = $2;
    }
;

iterstatement:
    for_statement   { $$ = $1; }
................................................................................

vardec:
    IDENTIFIER              {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &@1, $1, 1),
                            code_push_undef(),
                            code_assign(pstate, &@1, 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, &@1, $1);
        else ret = codes_join(code_local(pstate, &@1, $1), ret);
        $$ = ret;
    }
    | IDENTIFIER '=' expr   {
        Jsi_OpCodes *ret = codes_join4(code_push_index(pstate, &@1, $1, 1),
                            $3,
                            code_assign(pstate, &@1, 1),
                            code_pop(1));
        if (!pstate->eval_flag) jsi_PstateAddVar(pstate, &@1, $1);
        else ret = codes_join(code_local(pstate, &@1, $1), ret);
        $$ = ret;
    }
;

delete_statement:
    DELETE lvalue ';'           {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &@2, fv->varname, 1);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &@2, $7, $9, $1, (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate, &@5, fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        $$ = ret;
    }
    | label_opt FOR '(' lvalue inof expr ')' statement_or_empty {
................................................................................
        Jsi_OpCodes *lval;
        if (fv->varname) lval = code_push_index(pstate, &@1, fv->varname, 0);
        else lval = fv->lval;
        
        Jsi_OpCodes *ret = make_forin(lval, &@2, $6, $8, $1, (inof!=0));
        if (fv->varname && fv->local) {
            if (!pstate->eval_flag) {
                jsi_PstateAddVar(pstate, &@4, fv->varname);
                jsi_FreeOpcodes(fv->local);
            } else ret = codes_join(fv->local, ret);
        }
        Jsi_Free(fv);
        $$ = ret;
    }
;

Changes to tests/array.jsi.

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

//var q = new Array(5,4,2,3,1;
var q = new Array('Aaa','aAb','AAc','Bba','bBb');
var qq = q.sort();

;'Q: '+qq.join(',');

var t = [ 5, 4, 3, 2, 1];
function mysort(a,b) { return (a-b); }
;t;
;t.sort(mysort);

var x;
;x = [0, 2, 3 ];
;x.map(function (el,idx,obj) { return el+idx+obj[idx]; });
;x.some(function (el) { return (el%5)==4; });
;x.some(function (el) { return (el%3)==2; });
;x.find(function (el) { return (el%3)==2; });
;x.find(function (el) { return (el%5)==4; });
;x.every(function (el) { return (el%3)==2; });







|




<







34
35
36
37
38
39
40
41
42
43
44
45

46
47
48
49
50
51
52

//var q = new Array(5,4,2,3,1;
var q = new Array('Aaa','aAb','AAc','Bba','bBb');
var qq = q.sort();

;'Q: '+qq.join(',');

t = [ 5, 4, 3, 2, 1];
function mysort(a,b) { return (a-b); }
;t;
;t.sort(mysort);


;x = [0, 2, 3 ];
;x.map(function (el,idx,obj) { return el+idx+obj[idx]; });
;x.some(function (el) { return (el%5)==4; });
;x.some(function (el) { return (el%3)==2; });
;x.find(function (el) { return (el%3)==2; });
;x.find(function (el) { return (el%5)==4; });
;x.every(function (el) { return (el%3)==2; });

Changes to tests/ffi.jsi.

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

puts("================");
for(var s in a) { puts(s + ":" + a[s]); }

a.shite = "fock";

puts("================");
for(var s in a) { a.fock = "shite"; puts(s + ":" + a[s]); }

puts("================");
for(var s in a) { 
    puts(s + ":" + a[s]);
    delete a.shite; 
}

/*
=!EXPECTSTART!=
undefined







|


|







5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

puts("================");
for(var s in a) { puts(s + ":" + a[s]); }

a.shite = "fock";

puts("================");
for(s in a) { a.fock = "shite"; puts(s + ":" + a[s]); }

puts("================");
for(s in a) { 
    puts(s + ":" + a[s]);
    delete a.shite; 
}

/*
=!EXPECTSTART!=
undefined

Changes to tests/foreach.jsi.

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = a.reverse();
for (var i in a) {
    puts(a[i]);
}
var b = a.filter(function(x) { return (x != 'b'); });
puts(b);
var c = [];
for (var i in a) {
  var x = a[i];
  if (x != 'b') c.push(x);
}
puts(c);

/*
=!EXPECTSTART!=







|







7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = a.reverse();
for (var i in a) {
    puts(a[i]);
}
var b = a.filter(function(x) { return (x != 'b'); });
puts(b);
var c = [];
for (i in a) {
  var x = a[i];
  if (x != 'b') c.push(x);
}
puts(c);

/*
=!EXPECTSTART!=

Changes to tests/forin.jsi.

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

var obj = { a: 1, b:2, c:3, d:[4,3,2,1], e:{x:"x", y:"y", z:"z"}};
for (i in obj) {
    puts(i + ":");
    puts( obj[i]);
}

for (var i of [6,7,8])
    puts(i);

/*
=!EXPECTSTART!=
0:1
1:2
2:3







|







9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

var obj = { a: 1, b:2, c:3, d:[4,3,2,1], e:{x:"x", y:"y", z:"z"}};
for (i in obj) {
    puts(i + ":");
    puts( obj[i]);
}

for (i of [6,7,8])
    puts(i);

/*
=!EXPECTSTART!=
0:1
1:2
2:3

Changes to tests/interp2.jsi.

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var ii = new Interp();
puts(Info.named('Interp'));
puts (ii.eval('3+4'));
ii.eval('exit(0)');
delete ii;

if (!File.isdir('/tmp')) File.mkdir('/tmp');
var ii = new Interp({isSafe:true, safeWriteDirs:['/tmp/xx.txt'], safeReadDirs:['/tmp/']});
ii.eval("File.write('/tmp/xx.txt','hi');");
var s = ii.eval("return File.read('/tmp/xx.txt');");
;s;
ii.eval("File.remove('/tmp/xx.txt')");
try {
  ii.eval("File.write('~/xx.txt','bye');");
} catch (e) {







|







3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var ii = new Interp();
puts(Info.named('Interp'));
puts (ii.eval('3+4'));
ii.eval('exit(0)');
delete ii;

if (!File.isdir('/tmp')) File.mkdir('/tmp');
ii = new Interp({isSafe:true, safeWriteDirs:['/tmp/xx.txt'], safeReadDirs:['/tmp/']});
ii.eval("File.write('/tmp/xx.txt','hi');");
var s = ii.eval("return File.read('/tmp/xx.txt');");
;s;
ii.eval("File.remove('/tmp/xx.txt')");
try {
  ii.eval("File.write('~/xx.txt','bye');");
} catch (e) {

Changes to tests/json2.jsi.

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var dat = { able:1, baker:undefined };
;JSON.stringify(dat);

x = JSON.parse('["ABC",1]');
;x.toString();

JSON.parse('{ "Columns": [ 1, 2], "A" : 1 }');
var x = JSON.parse('{ "Columns": [ 1, 2, {"ABC":1, "B":[2,3]}, 2], "A" : 1 }');
;x.toString();

/*
=!EXPECTSTART!=
JSON.check(x,false) ==> true
JSON.check(x) ==> true
JSON.check(x2,false) ==> true







|







18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var dat = { able:1, baker:undefined };
;JSON.stringify(dat);

x = JSON.parse('["ABC",1]');
;x.toString();

JSON.parse('{ "Columns": [ 1, 2], "A" : 1 }');
x = JSON.parse('{ "Columns": [ 1, 2, {"ABC":1, "B":[2,3]}, 2], "A" : 1 }');
;x.toString();

/*
=!EXPECTSTART!=
JSON.check(x,false) ==> true
JSON.check(x) ==> true
JSON.check(x2,false) ==> true

Changes to tests/ref.jsi.

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

var a, b;
;a = { 'x':[4,5,6], 'y':{a:1, b:2}};
;b = { n:a, m:a.y };
;b.n;
;b.m;

function a() { return {x:1, y:{a:1,b:[]}}; };
;a().y.a;

/*
=!EXPECTSTART!=
a = { 'x':[4,5,6], 'y':{a:1, b:2}} ==> { x:[ 4, 5, 6 ], y:{ a:1, b:2 } }
b = { n:a, m:a.y } ==> { m:{ a:1, b:2 }, n:{ x:[ 4, 5, 6 ], y:{ a:1, b:2 } } }
b.n ==> { x:[ 4, 5, 6 ], y:{ a:1, b:2 } }
b.m ==> { a:1, b:2 }
a().y.a ==> 1
=!EXPECTEND!=
*/







|
|







|


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

var a, b;
;a = { 'x':[4,5,6], 'y':{a:1, b:2}};
;b = { n:a, m:a.y };
;b.n;
;b.m;

function c() { return {x:1, y:{a:1,b:[]}}; };
;c().y.a;

/*
=!EXPECTSTART!=
a = { 'x':[4,5,6], 'y':{a:1, b:2}} ==> { x:[ 4, 5, 6 ], y:{ a:1, b:2 } }
b = { n:a, m:a.y } ==> { m:{ a:1, b:2 }, n:{ x:[ 4, 5, 6 ], y:{ a:1, b:2 } } }
b.n ==> { x:[ 4, 5, 6 ], y:{ a:1, b:2 } }
b.m ==> { a:1, b:2 }
c().y.a ==> 1
=!EXPECTEND!=
*/

tools/env.jsi became executable.

Changes to tools/mkindex.jsi.

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
        jlst.push(lst[i]);
    else flst.push(lst[i]);
}
puts("<title>Index</title>");
puts("<table><tr><td valign=top>\n\n");
puts("<h4 style='text-align:center'>General</h4>\n");
var dat,title;
for (var i in flst.sort()) {
      if (flst[i] == "jsindex.wiki") continue;
      if (flst[i] == "index.wiki") continue;
      dat = File.read(flst[i]);
      title = dat.match('<title>([^>]+)</title>');
      if (!title)
            console.log("failed on "+flst[i]+"\n");
      puts('  *  <a href='+flst[i]+'>'+title[1]+'</a>');
}
puts("</td><td valign=top>");
puts("\n<h4 style='text-align:center'>Javascript</h4>");
var dat,title, ttl;
for (var i in jlst.sort()) {
    dat = File.read(jlst[i]);
    title = dat.match('<title>([^>]+)</title>');
    if (!title)
    console.log("failed on "+flst[i]);
    puts('  *  <a href='+jlst[i]+'>'+title[1]+'</a>');
}
puts("</td><td valign=top>");
puts("\n<h4 style='text-align:center'>C-API</h4>");
for (var i in clst.sort()) {
    dat = File.read(clst[i]);
    title = dat.match('<title>([^>]+)</title>');
    if (!title)
        console.log("failed on "+flst[i]);
    ttl = title[1]; 
    if (ttl.substr(0,6) == 'C-API:')
        ttl = ttl.substr(6);
    puts('  *  <a href='+clst[i]+'>'+ttl+'</a>');
}
puts("</td></tr></table>");







|










|
|








|










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
        jlst.push(lst[i]);
    else flst.push(lst[i]);
}
puts("<title>Index</title>");
puts("<table><tr><td valign=top>\n\n");
puts("<h4 style='text-align:center'>General</h4>\n");
var dat,title;
for (i in flst.sort()) {
      if (flst[i] == "jsindex.wiki") continue;
      if (flst[i] == "index.wiki") continue;
      dat = File.read(flst[i]);
      title = dat.match('<title>([^>]+)</title>');
      if (!title)
            console.log("failed on "+flst[i]+"\n");
      puts('  *  <a href='+flst[i]+'>'+title[1]+'</a>');
}
puts("</td><td valign=top>");
puts("\n<h4 style='text-align:center'>Javascript</h4>");
var ttl;
for (i in jlst.sort()) {
    dat = File.read(jlst[i]);
    title = dat.match('<title>([^>]+)</title>');
    if (!title)
    console.log("failed on "+flst[i]);
    puts('  *  <a href='+jlst[i]+'>'+title[1]+'</a>');
}
puts("</td><td valign=top>");
puts("\n<h4 style='text-align:center'>C-API</h4>");
for (i in clst.sort()) {
    dat = File.read(clst[i]);
    title = dat.match('<title>([^>]+)</title>');
    if (!title)
        console.log("failed on "+flst[i]);
    ttl = title[1]; 
    if (ttl.substr(0,6) == 'C-API:')
        ttl = ttl.substr(6);
    puts('  *  <a href='+clst[i]+'>'+ttl+'</a>');
}
puts("</td></tr></table>");

tools/mkproto.jsi became executable.

Changes to tools/mkref.jsi.

140
141
142
143
144
145
146
147

148
149
150
151
152
153
154
155
156
157
158
159
160
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
            aastr = tinf.args;
            if (tinf.options)
                aastr = LinkOpts(aastr, "new "+cnam);
            rv += "<tr><td>"+cnam+"</td><td>new "+cnam+"("+aastr+")"+tret+" </td><td>"+conhelp+'</td></tr>\n';
        }
        if (cmds !== undefined) {
            for (var cmd of cmds) {
                var namspl = cmd.split('.'), nam = namspl[namspl.length-1], tret = '';

                if (nam == cnam)
                    continue;
                ci = Info.cmds(cnam+'.'+nam);
                if (ci.retType !== "any")
                    tret = ':'+ci.retType;
                var conhelp = (ci.help?ci.help+'.':'');
                if (ci.info) conhelp += ' '+ci.info;
                if (ci.options) {
                    if (!clnknam) clnknam=nam;
                    if (!tinf.constructor || nam !== 'conf')
                        ro += DumpOpts(ci.options, ci.optHelp, cnam+'.'+nam, cnam+'.conf');
                    aastr = LinkOpts(ci.args, cnam+'.'+nam);
                } else {
................................................................................
        }
        rv += "</table>\n";
        if (tinf.options && nam !== 'conf')
            rv += DumpOpts(tinf.options, tinf.optHelp, 'new '+cnam, cnam+'.'+'conf');
        rv += ro;
        rv += '<a name="'+tinf.name+'end"></a>\n';
        rv += '<p><a href="#TOC">Return to top</a>\n';
        for (var ci of subs)
            rv += DumpObj(ci);
        return rv;
    }
    
    
    //*************** BEGIN MAIN **************
    var extlst = ['Sqlite', 'WebSocket', 'MySql', 'Socket'];
................................................................................
    var rv = '', tinf, lst = Info.cmds();
    var vv = Info.version(true);
    var ver = vv.major+'.'+vv.minor+'.'+vv.release;

    puts("<title>Reference</title>\n<p>");
    var index = "";

    for (var i in lst) {
        tinf = Info.cmds(lst[i]);
        switch (tinf.type) {
        case 'object':
            rv += DumpObj(tinf);
            break;
        case 'command':
            //rv += DumpCmd(tinf);







|
>





|







 







|







 







|







140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
...
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
...
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
            aastr = tinf.args;
            if (tinf.options)
                aastr = LinkOpts(aastr, "new "+cnam);
            rv += "<tr><td>"+cnam+"</td><td>new "+cnam+"("+aastr+")"+tret+" </td><td>"+conhelp+'</td></tr>\n';
        }
        if (cmds !== undefined) {
            for (var cmd of cmds) {
                var namspl = cmd.split('.'), nam = namspl[namspl.length-1];
                tret = '';
                if (nam == cnam)
                    continue;
                ci = Info.cmds(cnam+'.'+nam);
                if (ci.retType !== "any")
                    tret = ':'+ci.retType;
                conhelp = (ci.help?ci.help+'.':'');
                if (ci.info) conhelp += ' '+ci.info;
                if (ci.options) {
                    if (!clnknam) clnknam=nam;
                    if (!tinf.constructor || nam !== 'conf')
                        ro += DumpOpts(ci.options, ci.optHelp, cnam+'.'+nam, cnam+'.conf');
                    aastr = LinkOpts(ci.args, cnam+'.'+nam);
                } else {
................................................................................
        }
        rv += "</table>\n";
        if (tinf.options && nam !== 'conf')
            rv += DumpOpts(tinf.options, tinf.optHelp, 'new '+cnam, cnam+'.'+'conf');
        rv += ro;
        rv += '<a name="'+tinf.name+'end"></a>\n';
        rv += '<p><a href="#TOC">Return to top</a>\n';
        for (ci of subs)
            rv += DumpObj(ci);
        return rv;
    }
    
    
    //*************** BEGIN MAIN **************
    var extlst = ['Sqlite', 'WebSocket', 'MySql', 'Socket'];
................................................................................
    var rv = '', tinf, lst = Info.cmds();
    var vv = Info.version(true);
    var ver = vv.major+'.'+vv.minor+'.'+vv.release;

    puts("<title>Reference</title>\n<p>");
    var index = "";

    for (i in lst) {
        tinf = Info.cmds(lst[i]);
        switch (tinf.type) {
        case 'object':
            rv += DumpObj(tinf);
            break;
        case 'command':
            //rv += DumpCmd(tinf);

Changes to tools/mkstubs.jsi.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
..
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var stubs = [];
var d = '';
d += 'JSI_EXTERN int '+opts.pret+'_Stubs__initialize(Jsi_Interp *interp, double version, const char* name, int flags, const char *md5, int bldFlags, int stubSize, int structSizes, void **ptr); /*STUB = 0*/\n';
d += File.read(opts.inFile);
d = d.split('\n');
var l = d.length;
var im;
for (var i = 0; i<l; i++) {
    im = d[i].match(/^JSI_EXTERN (.[^\/]*)\/\*STUB = ([0-9]+)\*\//);
    if (!im || im.length != 3) continue;
    var ipos = parseInt(im[2]);
    if (ipos<0) continue;
    if (stubs[ipos]) {
        console.log("DUPLICATE JSI_EXTERN: ipos="+ipos+' = '+im[1]+' OLD='+stubs[ipos]);
        continue;
................................................................................
        console.log("EMPTY JSI_EXTERN: ipos="+ipos+' = '+im[1]);
        continue;
    }
    stubs[ipos] = im[1];
    
}

var l = stubs.length;
var iret, iopts, ipre, iname, lopts, nopts, mopts, topts, mtopts;
var fstub = 'typedef struct '+opts.pret+'_Stubs {\n    uint sig;\n    const char* name;\n    int size;\n    int bldFlags;\n';
fstub +='    const char* md5;\n    void *hook;\n';
var fdefs = '';
var finit = '    JSI_STUBS_SIG,    "'+opts.prefix+'",    sizeof('+opts.pret+'_Stubs),     '+opts.preu+'_STUBS_BLDFLAGS,    '+opts.preu+'_STUBS_MD5,    NULL,\\\n';
for (var i = 0; i<l; i++) {
    var x = stubs[i];
    if (!x) throw("missing index: "+i);
    im = x.match(/([^\(]+)\(([^\)]*)\)/);
    if (!im || im.length != 3) throw('bad stub: '+im.toString());
    iopts = im[2];
    ipre = im[1];
    var ii = ipre.lastIndexOf(' '+opts.pret+'_');







|







 







|





|







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
..
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var stubs = [];
var d = '';
d += 'JSI_EXTERN int '+opts.pret+'_Stubs__initialize(Jsi_Interp *interp, double version, const char* name, int flags, const char *md5, int bldFlags, int stubSize, int structSizes, void **ptr); /*STUB = 0*/\n';
d += File.read(opts.inFile);
d = d.split('\n');
var l = d.length;
var im;
for (i = 0; i<l; i++) {
    im = d[i].match(/^JSI_EXTERN (.[^\/]*)\/\*STUB = ([0-9]+)\*\//);
    if (!im || im.length != 3) continue;
    var ipos = parseInt(im[2]);
    if (ipos<0) continue;
    if (stubs[ipos]) {
        console.log("DUPLICATE JSI_EXTERN: ipos="+ipos+' = '+im[1]+' OLD='+stubs[ipos]);
        continue;
................................................................................
        console.log("EMPTY JSI_EXTERN: ipos="+ipos+' = '+im[1]);
        continue;
    }
    stubs[ipos] = im[1];
    
}

l = stubs.length;
var iret, iopts, ipre, iname, lopts, nopts, mopts, topts, mtopts;
var fstub = 'typedef struct '+opts.pret+'_Stubs {\n    uint sig;\n    const char* name;\n    int size;\n    int bldFlags;\n';
fstub +='    const char* md5;\n    void *hook;\n';
var fdefs = '';
var finit = '    JSI_STUBS_SIG,    "'+opts.prefix+'",    sizeof('+opts.pret+'_Stubs),     '+opts.preu+'_STUBS_BLDFLAGS,    '+opts.preu+'_STUBS_MD5,    NULL,\\\n';
for (i = 0; i<l; i++) {
    var x = stubs[i];
    if (!x) throw("missing index: "+i);
    im = x.match(/([^\(]+)\(([^\)]*)\)/);
    if (!im || im.length != 3) throw('bad stub: '+im.toString());
    iopts = im[2];
    ipre = im[1];
    var ii = ipre.lastIndexOf(' '+opts.pret+'_');

tools/mktestcode.jsi became executable.

tools/mktoc.jsi became executable.

Changes to tools/protos.jsi.

1
2
3
4
5
6
7
8
//JSI Command Prototypes: version 2.8.16
throw("NOT EXECUTABLE: USE FILE IN GEANY EDITOR FOR CMD LINE COMPLETION + GOTO TAG");

var Array = function(cmd,args) {};
Array.prototype.concat = function(...):array {};
Array.prototype.every = function(callback:function):any {};
Array.prototype.fill = function(value:any, start:number=0, end:number=-1):array {};
Array.prototype.filter = function(callback:function, this:object=void):array {};
|







1
2
3
4
5
6
7
8
//JSI Command Prototypes: version 2.8.17
throw("NOT EXECUTABLE: USE FILE IN GEANY EDITOR FOR CMD LINE COMPLETION + GOTO TAG");

var Array = function(cmd,args) {};
Array.prototype.concat = function(...):array {};
Array.prototype.every = function(callback:function):any {};
Array.prototype.fill = function(value:any, start:number=0, end:number=-1):array {};
Array.prototype.filter = function(callback:function, this:object=void):array {};

tools/randtest.jsi became executable.

tools/structpp.jsi became executable.

tools/stubrenumber.jsi became executable.

tools/syntaxjs.jsi became executable.