diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/compiler/compiler.zc | 231 | ||||
| -rw-r--r-- | src/lib/std.zc | 128 | ||||
| -rw-r--r-- | src/lsp/server.zc | 50 |
3 files changed, 343 insertions, 66 deletions
diff --git a/src/compiler/compiler.zc b/src/compiler/compiler.zc index 86e00c5..ac504d7 100644 --- a/src/compiler/compiler.zc +++ b/src/compiler/compiler.zc @@ -285,8 +285,12 @@ int fldst, fldi; // the one struct a bare address's field name resolved to char*[8] tpn; int ntp; // type parameters in scope // reading a return type: unknown names are type parameters declared after the function's name int tvauto; +// the typedefs of the blocks being compiled: three words each (the symbol, the block depth and the +// compile context it was made in), newest last. a block's end unlinks them from their names. +word tdstk; int ntd, tdcap; word readonly_types; int dty, dtag; // result of dtype() +int s_typedef; int s_lt, s_gt, s_shr, s_le, s_ge, s_eqeq, s_ne, s_plus, s_struct, s_type, s_typecheck, s_docs, s_small, s_std, s_icon, s_on, s_off, s_new, s_new_t; int s_o3, s_lfa, s_outside, s_new_raw, s_new_oz, s_oob; int s_ld8, s_st8, s_ld16, s_st16, s_ld32, s_st32; @@ -1102,6 +1106,7 @@ int source_lookup(char* name) { // drop the symbols above index to, which ends a scope. int popsyms(int to) { while (nsym > to) { nsym--; sname[nsym][-1] = snext[nsym]; } + while (ntd && tdstk[ntd * 3 - 3] >= to) ntd--; // local typedefs made above to went with them return 0; } // look a name up from a plain string. @@ -2952,6 +2957,7 @@ int block_close(int save) { while (i < save) { if (lhome[i] >= fdepth) { lstate[i] = S_DEAD; lhome[i] = fdepth - 1; } i++; } local_drop(save); fdrop(save); + td_end(fdepth); return 0; } @@ -3981,6 +3987,44 @@ int dtype() { } return 0; } +// the struct whose body or methods are being compiled, when it declares constants: a bare +// name there is looked up as Struct.name before the global scope +char* mstruct; +// does a constant declaration start in a struct body? const NAME = e; const T NAME = e; +// (a field of a const type has no initializer, so the = tells them apart) +int struct_const_start() { + if (!is_id(s_const)) return 0; + peekat(0); if (pk_tk != T_ID) return 0; + peekat(1); + if (pk_tk == T_OP && pk_tv == s_eq) return 1; + if (pk_tk == T_ID) { peekat(2); return pk_tk == T_OP && pk_tv == s_eq; } + if (pk_tk == T_OP && pk_tv == s_star) { peekat(2); if (pk_tk != T_ID) return 0; peekat(3); return pk_tk == T_OP && pk_tv == s_eq; } + return 0; +} +// const NAME = e, NAME = e; inside struct sn: a compile-time constant named Struct.NAME that takes no +// space in the layout. the optional type is read and dropped, as in gconst. +int struct_const(char* sn) { + int off, s; char* cn; + next(); + if (tk == T_ID) { peekat(0); if (pk_tk == T_ID || (pk_tk == T_OP && pk_tv == s_star)) ptype(); } + mstruct = sn; + while (1) { + off = toff; cn = name(); + s = lookup(methname(sn, cn)); + if (s >= ubase && s >= 0) serrn(cn, "is defined twice in this struct"); + expect(s_eq); + s = addsym(methname(sn, cn), K_CONST, cexpr()); + rs_put(off, RS_SYM, rs_sym(s), s); + if (!is_op(s_comma) && !is_op(s_semi)) { // a call or a variable's value follows what cprim could read + serr("a struct constant must be a constant expression"); + while (!is_op(s_semi) && !is_op(s_rb) && tk != T_EOF) next(); + break; + } + if (!accept(s_comma)) break; + } + accept(s_semi); + return 0; +} // struct name { type field, ... } or struct name<A, B> { ... } // the struct keyword. fields go in a scratch buffer first (name, type pairs), // then are laid out: each field takes tsz(type) words, so offsets are words. @@ -3989,7 +4033,7 @@ int dtype() { // and call its siblings. a generic struct keeps its fields unresolved and // can't have methods; each instance is laid out later by tresolve. int kw_struct() { - char* n; word t; int s, nf = 0; word buf = chk_resize(0, 0, 64); int bufcap = 64, i; word fs; int off = 0, gen = 0, ft, nm = 0, mcap = STRUCT_METHODS; char** mn = chk_resize(0, 0, mcap); word mq = chk_resize(0, 0, mcap), mst = chk_resize(0, 0, mcap), mty = chk_resize(0, 0, mcap), mrt = chk_resize(0, 0, mcap), mrg = chk_resize(0, 0, mcap); int bo, k, stat = 0; char* fname = 0; + char* n; word t; int s, nf = 0; word buf = chk_resize(0, 0, 64); int bufcap = 64, i; word fs; int off = 0, gen = 0, ft, nm = 0, mcap = STRUCT_METHODS; char** mn = chk_resize(0, 0, mcap); word mq = chk_resize(0, 0, mcap), mst = chk_resize(0, 0, mcap), mty = chk_resize(0, 0, mcap), mrt = chk_resize(0, 0, mcap), mrg = chk_resize(0, 0, mcap); int bo, k, stat = 0; char* fname = 0; char* msv = mstruct; next(); n = module_symbol(name()); if (is_op(s_lt)) { // generic @@ -4011,6 +4055,7 @@ int kw_struct() { while (!is_op(s_rb)) { if (tk == T_EOF) { die("missing }"); break; } stat = 0; + if (struct_const_start()) { struct_const(n); continue; } if (is_id(s_unchecked)) { next(); stat = 2; } if (is_id(s_static)) { // static fn name(params) { body }, or static T name(params) { body }: a function of the struct, called as Struct.name(args), with no this next(); @@ -4099,6 +4144,7 @@ int kw_struct() { i = 0; while (i < nm) { fn_method_compile = 1; methdef(n, mn[i], mq[i], mst[i], mty[i], mrt[i], mrg[i]); fn_method_compile = 0; i++; } mdg = 0; + mstruct = msv; return s; } // ---- methods ---- @@ -4348,6 +4394,89 @@ int kw_type() { expect(s_semi); return 0; } +// does a parameter start with a type? a type name straight before , or ) is the parameter's +// own name (fn f(string)), not a type, since a typed parameter always has a name after it. +int paramstart() { + if (tk == T_OP) return tv == s_lk; + if (tk != T_ID) return 0; + if (tv == s_fn) return 1; + if (!istypename(tv)) return 0; + peek(); + return !(pk_tk == T_OP && (pk_tv == s_comma || pk_tv == s_rp)); +} +// does a typedef start here? typedef followed by a name is one, so typedef can still be +// a variable or a function's name. +int typedef_ahead() { + if (tk != T_ID || tv != s_typedef) return 0; + peekat(0); + return pk_tk == T_ID; +} +// unlink the symbol s from its name, leaving the rest of the name's chain as it was. +int td_unlink(int s) { + char* nm = sname[s]; int i = nm[-1] - 1; + if (i == s) { nm[-1] = snext[s]; return 0; } + while (i >= 0 && snext[i] - 1 != s) i = snext[i] - 1; + if (i >= 0) snext[i] = snext[s]; + return 0; +} +// end the scope of the local typedefs made at block depth depth or deeper in this +// compile context (and of any made in a context nested inside it). +int td_end(int depth) { + int k; + while (ntd) { + k = ntd * 3 - 3; + if (tdstk[k + 2] < ctxsp || (tdstk[k + 2] == ctxsp && tdstk[k + 1] < depth)) break; + td_unlink(tdstk[k]); + ntd--; + } + return 0; +} +// is the name q (as a symbol is named) already a typedef of the block being compiled? +int td_here(char* q) { + int k = ntd; + while (k) { + k--; + if (tdstk[k * 3 + 2] != ctxsp || tdstk[k * 3 + 1] != fdepth) break; + if (sname[tdstk[k * 3]] == q) return 1; + } + return 0; +} +// typedef T name; +// the C spelling of type name = T;. name becomes another way to write T: the very same +// type record, so the two are interchangeable everywhere. at the top level the name is +// global; in a function it lasts to the end of its block, like a local. a name that is +// already in use is an error, except the same type under the same name again. a tag +// (.u, .m, .d) belongs to a declaration, not to a type, so a typedef has none. +int kw_typedef() { + char* n; char* q; word t; int s, at, clash = 0, local = infn; + next(); + t = ptype(); + if (panic) return 0; + if (is_op(s_dot)) { die("a typedef names a type, which has no tag: .u, .m and .d go on a declaration"); return 0; } + at = toff; n = name(); + if (panic) return 0; + q = module_symbol(n); + if (local) { + s = findloc(n); + if ((s >= 0 && lhome[s] >= fdepth) || td_here(q)) clash = 1; + } else { + s = lookup_raw(q); + if (s < 0 && module_name) { s = lookup_raw(n); if (s >= 0 && skind[s] != K_TYPE && skind[s] != K_KW) s = 0 - 1; } + if (s >= 0 && skind[s] == K_TYPE && sval[s] == t) return expect(s_semi); // the same typedef again + if (s >= 0) clash = 1; + } + if (clash) serrn(n, "already defined"); + else { + s = addsym(n, K_TYPE, t); + rs_put(at, RS_SYM, rs_sym(s), s); + if (local) { + if (ntd == tdcap) { if (tdcap) tdcap = tdcap * 2; else tdcap = 16; tdstk = chk_resize(tdstk, ntd * 3, tdcap * 3); } + tdstk[ntd * 3] = s; tdstk[ntd * 3 + 1] = fdepth; tdstk[ntd * 3 + 2] = ctxsp; ntd++; + } + } + expect(s_semi); + return 0; +} // (T) or (T*) ahead of the current '(', within the lookahead we have // the parser sees ( and has to decide between a parenthesized expression and a // cast. a cast is ( type stars ) so peek ahead through the stars to the ). @@ -5516,6 +5645,7 @@ int types_init() { addsym(tword[2], K_TYPE, tword); addsym(tint[2], K_TYPE, tint); addsym(tchar[2], K_TYPE, tchar); addsym(tbool[2], K_TYPE, tbool); addsym(tvoid[2], K_TYPE, tvoid); addsym(tfloat[2], K_TYPE, tfloat); addsym(intern("f64"), K_TYPE, tfloat); + addsym(intern("string"), K_TYPE, tptr(tchar)); // string is char*, as if by typedef char* string; // f32: single precision. a variable holds the rounded value as a double; an element // of an array or pointer of f32 is packed two to a word, like the sized integers f32p = tnew(TY_FLOAT, 1, intern("f32"), 0); @@ -5530,7 +5660,7 @@ int types_init() { s_le = intern("<="); s_ge = intern(">="); s_eqeq = intern("=="); s_ne = intern("!="); s_plus = intern("+"); - s_struct = intern("struct"); s_type = intern("type"); s_typecheck = intern("typecheck"); s_docs = intern("docs"); s_std = intern("std"); s_icon = intern("icon"); s_small = intern("small"); + s_struct = intern("struct"); s_type = intern("type"); s_typedef = intern("typedef"); s_typecheck = intern("typecheck"); s_docs = intern("docs"); s_std = intern("std"); s_icon = intern("icon"); s_small = intern("small"); s_on = intern("on"); s_off = intern("off"); s_new = intern("rt.new"); @@ -6445,7 +6575,7 @@ int closure() { while (1) { pty[np] = tword; if (expected && expected[0] == TY_FN && np < expected[3]) pty[np] = expected[7 + np]; - if (!is_op(s_dot) && ((tk == T_OP && tv == s_lk) || (tk == T_ID && (tv == s_fn || istypename(tv))))) { + if (!is_op(s_dot) && paramstart()) { pty[np] = ptype(); if (pty[np][0] == TY_ARR) pty[np] = decay(pty[np]); } tag = 0; @@ -6800,6 +6930,7 @@ int primary() { return C_PLAIN; } s = source_lookup(n); + if (mstruct && !ginst) { ms = lookup(methname(mstruct, n)); if (ms >= 0 && skind[ms] == K_CONST) s = ms; } if (s < 0 && rt.eq_w(n, "new")) s = source_lookup(s_new); if (s >= 0) rs_put(toff, RS_SYM, rs_sym(s), s); if (s >= 0 && skind[s] == K_KW) { @@ -6812,8 +6943,8 @@ int primary() { c = toff + toklen; next(); if (probe_off >= 0 && cmode && !dry && !ginst && incdepth == 0 && probe_off >= c && ((tk == T_ID && probe_off <= toff + toklen) || (tk != T_ID && probe_off <= toff))) { probe_static = n; probe_has = 3; chkabort = 1; } - k = toff; mn = name(); - ms = lookup(methname(n, mn)); + k = toff; sv = tpack(); mn = name(); + ms = lookup(methname(sname[s], mn)); if (ms >= 0) rs_put(k, RS_SYM, rs_sym(ms), ms); if (ms >= 0 && skind[ms] == K_CONST) { // Enum.MEMBER xvk = 1; xvv = sval[ms]; @@ -6829,7 +6960,11 @@ int primary() { if (!is_op(s_lp)) die("a static function is called with ( after its name"); return call(ms); } - serrn(mn, "is not a static function of this struct"); + if (!panic && !dry) { + c = tpack(); tunpack(sv); // the error sits on the member name, where the quick fix replaces it + errat(); rt.put_s(mn); rt.put_s(": is not a static function of this struct"); suggest_member(sname[s], 0, mn, 1); errend(); + tunpack(c); + } lit(0); xty = tword; return C_PLAIN; @@ -6949,7 +7084,7 @@ int incdec(int post, int dlt) { word field(int c) { int readonly = treadonly(xty); if_value = 0; - int n, fieldoff; word st; + int n, fieldoff, fieldpos, sv; word st; word borrowed = xaf, base_mask = effect_mask(c); af_use(xaf, tpack(), c); xaf = 0; xvk = 0; int i, b = xbor, k = 0, scanned = 0, ms, de, pmatch = 0; de = toff + toklen; next(); @@ -6958,7 +7093,7 @@ word field(int c) { if (tk == T_ID) { if (probe_off <= toff + toklen) pmatch = 1; } else if (probe_off <= toff) pmatch = 1; } - n = name(); fieldoff = nameoff; + fieldpos = tpack(); n = name(); fieldoff = nameoff; st = xty; if (st[0] == TY_ARR || st[0] == TY_DYN) { if (pmatch) probe_member(st); @@ -7023,7 +7158,11 @@ word field(int c) { } if (scanned) i = fldi; else i = tfindfield(st, n); if (i < 0) { - if (!panic && !dry) { errat(); tprint(st); rt.put_s(" has no field "); rt.put_s(n); errend(); } + if (!panic && !dry) { + sv = tpack(); tunpack(fieldpos); // the error sits on the field name, where the quick fix replaces it + errat(); tprint(st); rt.put_s(" has no field "); rt.put_s(n); suggest_member(st[2], st, n, 0); errend(); + tunpack(sv); + } xty = tword; lv = 1; lvk = LV_OTHER; xbor = -1; return C_PLAIN; } rs_put(fieldoff, RS_FIELD, field_decl(st, n), st[4][i * 3 + 1]); @@ -7611,7 +7750,7 @@ word stmtstart() { int s; if (tk == T_OP) return tv == s_semi || tv == s_lb || tstart(); if (tk != T_ID || findloc(tv) >= 0) return 0; - if (tstart()) return 1; + if (tstart() || typedef_ahead()) return 1; s = lookup(tv); return s >= 0 && skind[s] == K_KW && !(sflag[s] & F_EXPR); } @@ -7651,6 +7790,7 @@ word cprim() { if (accept(s_lp)) { v = cexpr(); expect(s_rp); return v; } if (tk == T_ID) { s = lookup(tv); + if (mstruct && !ginst) { mc = lookup(methname(mstruct, tv)); if (mc >= 0 && skind[mc] == K_CONST) s = mc; } if (s >= 0 && (skind[s] == K_CONST || skind[s] == K_GARR || (skind[s] == K_FN && (sflag[s] & F_DEF)) || skind[s] == K_GVAR)) { next(); return sval[s]; @@ -7712,6 +7852,7 @@ int stmt_inner() { if (s >= 0 && skind[s] == K_KW && (sflag[s] & F_STMT)) { kwcall(s, 0); return 0; } } if (untyped_const()) { next(); localdecl(2); return 0; } + if (typedef_ahead() && findloc(tv) < 0) return kw_typedef(); if (tstart()) { localdecl(1); return 0; } if (tk == T_OP) { if (tv == s_semi) { next(); return 0; } @@ -8596,7 +8737,7 @@ int prescan(int kind, int obj) { if (is_op(s_lb)) depth++; else if (is_op(s_rb)) { depth--; pend = 0; po3 = 0; } else if (depth <= 0) { - if (is_id(s_type)) { while (tk != T_EOF && !is_op(s_semi)) next(); if (is_op(s_semi)) next(); pend = 0; po3 = 0; continue; } + if (is_id(s_type) || typedef_ahead()) { while (tk != T_EOF && !is_op(s_semi)) next(); if (is_op(s_semi)) next(); pend = 0; po3 = 0; continue; } if (tk == T_ID && rt.eq_w(tv, "namespace")) { kw_namespace(); continue; } if (is_op(s_semi)) { pend = 0; po3 = 0; } else if (is_op(s_dot)) { peek(); if (pk_tk == T_ID && pk_tv == s_u) pend = 1; } @@ -8745,6 +8886,7 @@ int epilogue() { infn = 0; local_drop(lbase); fdrop(lbase); + td_end(0); return 0; } // the statements of a function between its braces, then the end-of-function @@ -8800,7 +8942,7 @@ int fndef(int chk, int rty, int ret, int n) { t = 0; pty[np] = tword; pk = 0; - if (!is_op(s_dot) && ((tk == T_OP && tv == s_lk) || (tk == T_ID && (tv == s_fn || istypename(tv))))) { + if (!is_op(s_dot) && paramstart()) { pty[np] = ptype(); typed = 1; pk = 1; if (pty[np][0] == TY_ARR) pty[np] = decay(pty[np]); if (isagg(pty[np])) { @@ -9065,7 +9207,7 @@ int topsync() { while (tk != T_EOF) { if (is_op(s_lb)) depth++; else if (is_op(s_rb)) { depth--; if (depth < 0) depth = 0; } - else if (!depth && tk == T_ID && (tv == s_fn || tv == s_var || tv == s_const || tv == s_struct || tv == s_type + else if (!depth && tk == T_ID && (tv == s_fn || tv == s_var || tv == s_const || tv == s_struct || tv == s_type || tv == s_typedef || tv == s_enhance || tv == s_typecheck || tv == s_docs || tv == s_unchecked || tv == s_immediate || tv == s_o3 || tv == s_memdebug || tv == s_enum || tv == s_include)) break; next(); @@ -9175,6 +9317,7 @@ int topitem1() { if (is_id(s_var)) return gdecl(0); if (is_id(s_struct)) { kw_struct(); return 0; } if (is_id(s_type)) return kw_type(); + if (typedef_ahead()) return kw_typedef(); if (is_id(s_typecheck)) return kw_typecheck(); if (is_id(s_docs)) return kw_docs(); if (is_id(s_memdebug)) return kw_memdebug(); @@ -9572,6 +9715,66 @@ int similar(int n) { if (bd > lim) return 0; return best; } +// the field or method of struct sn closest to n (statics is 0), or the static function or constant +// (statics is 1), when it is close enough to be a likely typo. the limits are those of similar. +char* similar_member(char* sn, word st, char* n, int statics) { + int j, bd = 99, dist, k, ln = rt.len_w(sn), lim = rt.len_w(n) / 3, nf; char* best = 0; char* tail; + if (rt.len_w(n) < 3) return 0; + if (lim < 1) lim = 1; + if (lim > 3) lim = 3; + if (!statics && st && st[0] == TY_STRUCT) { + nf = st[3]; k = 0; + while (k < nf) { + tail = st[4][k * 3]; dist = editdist(n, tail); + if (dist == 2 && swapped(n, tail)) dist = 1; + if (dist > 0 && dist < bd) { bd = dist; best = tail; } + k++; + } + } + j = 0; + while (j < nsym) { + k = skind[j]; + if (((k == K_FN && ((sflag[j] & F_STATIC) != 0) == statics) || (statics && k == K_CONST)) && rt.len_w(sname[j]) > ln + 1 && sname[j][ln] == '.') { + tail = sname[j] + ln + 1; + if (has_prefix(sname[j], sn, ln) && !has_dot(tail)) { + dist = editdist(n, tail); + if (dist == 2 && swapped(n, tail)) dist = 1; + if (dist > 0 && dist < bd) { bd = dist; best = tail; } + } + } + j++; + } + if (bd > lim) return 0; + return best; +} +// are a and b the same but for two neighbouring chars swapped (itao for itoa)? a swap counts as one typo. +int swapped(char* a, char* b) { + int i = 0, la = rt.len_w(a); + if (la != rt.len_w(b)) return 0; + while (a[i] && a[i] == b[i]) i++; + if (!a[i] || !a[i + 1] || a[i] != b[i + 1] || a[i + 1] != b[i]) return 0; + i = i + 2; + while (a[i] && a[i] == b[i]) i++; + return !a[i]; +} +// does s start with the first n chars of p? +int has_prefix(char* s, char* p, int n) { + int i = 0; + while (i < n && s[i] == p[i]) i++; + return i == n; +} +// does the string contain a dot? +int has_dot(char* s) { + int i = 0; + while (s[i]) { if (s[i] == '.') return 1; i++; } + return 0; +} +// ends an error message with "; did you mean 'x'?" when a member of struct sn is close to n +int suggest_member(char* sn, word st, char* n, int statics) { + char* best = similar_member(sn, st, n, statics); + if (best) { rt.put_s("; did you mean '"); rt.put_s(best); rt.put_s("'?"); } + return 0; +} // a copy of s[a..e) as a string char* lib_copy(char* s, int a, int e) { char* b = chk_resize(0, 0, e - a + 1); rt.copy_w(b, s + a, e - a); b[e - a] = 0; @@ -9978,7 +10181,7 @@ int zc_init() { poolend = R_POOLEND; poolblocks = 0; namecount = 0; rt.fill_w(namehash, 0, hashcap); nsym = 0; nfixu = 0; fixfree = 0; nbin = 0; nun = 0; nasg = 0; nkop = 0; seqtop = 0; - lsp = 0; ctxsp = 0; snaptop = 0; nloc = 0; lbase = 0; npm = 0; npe = 0; rt.fill_w(lkeys, 0, lkeycap); lkeyn = 0; + lsp = 0; ctxsp = 0; ntd = 0; snaptop = 0; nloc = 0; lbase = 0; npm = 0; npe = 0; rt.fill_w(lkeys, 0, lkeycap); lkeyn = 0; s_lp = intern("("); s_rp = intern(")"); s_lb = intern("{"); s_rb = intern("}"); s_lk = intern("["); s_rk = intern("]"); s_comma = intern(","); s_semi = intern(";"); s_eq = intern("="); s_arrow = intern("->"); s_inc = intern("++"); s_dec = intern("--"); diff --git a/src/lib/std.zc b/src/lib/std.zc index f0bc390..33ab1e9 100644 --- a/src/lib/std.zc +++ b/src/lib/std.zc @@ -20,9 +20,14 @@ include rt, run; // these and the runtime calls it before main, if the program has one (an // image built by build_image, or a check-mode document, does not). +// the number of command line arguments, set by libinit(). int argc; +// the command line arguments, one string each. argv[0] is the program path, +// or <eval> when the source came from stdin. char*[?] argv; +// the number of environment entries, set by libinit(). int envc; +// the environment, one NAME=value string per entry, set by libinit(). char*[?] envp; // one entry of a vector syscall, as a fresh string, or 0 past the end. @@ -64,25 +69,24 @@ int libinit() { // capture.start() redirects everything the program writes into a string and // returns it. writes go to the buffer instead of the terminal until end() // stops it, so the buffer is a string once end() has run: -// let buf = capture.start(); +// let buf = std.capture.start(); // rt.put_s("hello world!"); // nothing on the terminal -// capture.end(buf); -// rt.put_s(buf); // hello world +// std.capture.end(buf); +// rt.put_s(buf); // hello world! +// the buffer holds 256 characters, and output past that is dropped. // one capture at a time, and the buffer belongs to whoever holds it. - struct capture { - // redirects program output into a collector-managed character buffer. - // returns the buffer; call end(buffer) before reading its terminator. - // returns: the buffer used for this capture + // starts a capture: output goes into a new buffer instead of the terminal. + // returns: the buffer, managed by the collector; read it after end(buffer) static char* start() { int cap = 256; rt.outmode = 2; rt.outn = 0; rt.outcap = cap; rt.outbuf = rt.new(cap); return rt.outbuf; } - // stops output capture, terminates the buffer, and returns the collected text. - // buffer: the buffer returned by start - // returns: the same buffer, now terminated + // stops the capture and ends the buffer with a 0. + // buffer: the buffer that start returned + // returns: the same buffer, now a string static char* end(char* buffer) { rt.outbuf[rt.outn] = 0; rt.outmode = 0; rt.outbuf = 0; rt.outn = 0; rt.outcap = 0; @@ -92,6 +96,8 @@ struct capture { // ---- character strings ---- +// helpers for char* strings: one character per word, ended by a 0 word. +// called as std.Text.name(args). struct Text { // the number written in decimal at the start of s. a leading '-' makes it // negative and the first character that is not a digit ends it. @@ -106,7 +112,7 @@ struct Text { // writes n in decimal into dst, with a 0 after it. // n: the number - // dst: where the text goes; 24 words is always enough + // dst: where the text goes; 21 words is always enough (20 characters and the 0) // returns: how many characters were written, not counting the 0 static int itoa(int n, char* dst) { int b[24], i = 0, j = 0, neg = 0; @@ -120,7 +126,7 @@ struct Text { return j; } - // joins two strings. + // joins two strings into dst. // dst: where the result goes, with room for both and a 0; not a or b // a: the first string // b: the second string @@ -248,9 +254,8 @@ struct Text { // ---- numbers ---- -// plain integer helpers. none of them can fail: an out of range result wraps -// the same way the arithmetic does. - +// plain integer helpers, called as std.Num.name(args). none of them can fail: +// an out of range result wraps the same way the arithmetic does. struct Num { // the absolute value of n, using wrapping word arithmetic. the minimum // word remains negative because its positive value cannot fit in a word. @@ -298,7 +303,8 @@ struct Num { return a; } - // b raised to the power e. e below 0 gives 1; the result wraps as a word. + // b raised to the power e, by one multiply per step of e, so a large e is slow. + // e below 0 gives 1, and the result wraps as a word. // b: the base // e: the exponent // returns: b to the power e, or 1 when e is negative @@ -333,18 +339,18 @@ struct Num { // ---- the host ---- -// the argument block for Host.raw: the number, then its six arguments. +// the argument block for Host.raw: word 0 is the syscall number, words 1 to 6 +// are its arguments. Host.raw fills it on each call. int rawblk[7]; +// calls into the host that runs the vm: the environment, the clock, files and +// raw system calls. called as std.Host.name(args). struct Host { // calls any linux system call on the host. this is the escape hatch below // the named helpers: the number is the kernel's, so the meaning of each - // argument depends on the call. a pointer argument is an address in the - // program's memory, and only the host reads it, so a string or buffer has - // to be passed as its address. - // it runs the call on the real machine, not inside the vm, so a program - // that uses it can do whatever the process can do. only use it where that - // is wanted. + // argument depends on the call. the words reach the kernel unchanged, so a + // pointer is a host address to it, not a place in the vm's memory. the call + // runs on the real machine, so only use it where that is wanted. // nr: the syscall number (x86-64 and arm64 numbers differ, so check the host) // a..f: the six arguments, unused ones 0 // returns: the kernel's result, -errno on failure, or -1 on unsupported hosts @@ -354,18 +360,20 @@ struct Host { return rt.syscall(rt.SYS_RAW, rawblk, 0, 0); } - // the value of an environment variable. + // copies the value of an environment variable into dst, as a 0-terminated string. // name: the variable's name - // dst: where the value goes, a zero-terminated character string - // n: how many words dst has - // returns: the length of the value, -1 if the variable is not set + // dst: where the value goes + // n: the size of dst in words, the 0 included + // returns: how many characters were copied, at most n - 1, so a longer value + // is cut short; -1 if the variable is not set or n is below 1 static int env(char* name, char* dst, int n) { return rt.syscall(rt.SYS_GETENV, name, dst, n); } // the clock. // returns: the time in seconds since 1970 static int now() { return rt.syscall(rt.SYS_TIME, 0, 0, 0); } - // writes a string to a file, replacing what was there. + // writes a string to a file, replacing what was there. the file is created if + // it is missing. // path: the file's name // s: the text to write // returns: how many bytes were written, -1 if the file could not be opened @@ -380,9 +388,8 @@ struct Host { // ---- byte strings ---- -// the same helpers for packed byte strings. character-string helpers above are unchanged. -// a packed byte string has type bstr; len_s reads its stored byte length. - +// the same helpers as Text, for packed byte strings of type bstr (b"..." +// literals). len reads the stored byte length. called as std.Bytes.name(args). struct Bytes { // reads a decimal number at the start of s; a leading '-' makes it // negative, and the first non-digit ends the number. @@ -392,7 +399,7 @@ struct Bytes { // like Text.itoa, but the text is made fresh. // n: the number - // returns: a new byte string + // returns: a new byte string, managed by the collector; the caller does not free it static bstr itoa(int n) { return rt.n_to_s(n); } // like Text.starts, for byte strings. @@ -448,14 +455,15 @@ struct Bytes { return 1; } - // like Host.env, for byte strings. + // like Host.env, for byte strings. the value is written into the bytes of dst, + // and the length of dst is not changed, so make dst big enough first. // name: the variable's name, a byte string - // dst: the packed byte string whose payload receives the value - // n: the maximum number of bytes to write - // returns: the length of the value, -1 if the variable is not set + // dst: the byte string that receives the value + // n: the most bytes dst may use, the 0 after the value included + // returns: how many bytes were copied, at most n - 1; -1 if the variable is not set or n is below 1 static int env(bstr name, bstr dst, int n) { return rt.bgetenv(name, dst, n); } - // like Host.writefile, for a byte string. + // like Host.writefile, for a byte string. the file is replaced, or created. // path: the file's name, a byte string // s: the bytes to write // returns: how many bytes were written, -1 if the file could not be opened @@ -470,16 +478,17 @@ struct Bytes { // ---- arenas ---- -// a region that is freed all at once. +// a region of n words that Arena.alloc hands out and Arena.reset frees all at once. // n: its capacity in words; values below 1 allocate one word // returns: the arena, owned by the caller int .u arena(int n) { return rt.arena_new(n); } +// helpers for an arena made by std.arena. called as std.Arena.name(args). struct Arena { // takes n zeroed words from an arena. // a: the arena // n: how many words - // returns: the first word, or 0 when n words do not fit + // returns: the first word; 0 when n words do not fit, or n is negative static int alloc(word a, int n) { return rt.arena_alloc(a, n); } // gives every block of an arena back at once. pointers returned by alloc @@ -491,10 +500,10 @@ struct Arena { // ---- growable byte buffers ---- -// a byte buffer stores its length and capacity in two words, followed by the -// bytes, packed. +// makes an empty byte buffer with room for n bytes. the buffer keeps its length +// and capacity in two words, followed by the bytes, packed. // n: the capacity in bytes; a negative value is treated as 0 -// returns: an empty buffer with that capacity, owned by the caller +// returns: the buffer, owned by the caller word .u bnew(int n) { int words; word p; @@ -506,25 +515,27 @@ word .u bnew(int n) { return u*p; } +// byte buffers made by bnew. the length grows as bytes are set, up to the +// capacity, which is fixed. called as std.Buf.name(args). struct Buf { // how many bytes a buffer holds. - // b: the buffer + // b: the buffer, from bnew // returns: its length static int length(word b) { return b[0]; } // how many bytes a buffer can hold. - // b: the buffer + // b: the buffer, from bnew // returns: its capacity static int capacity(word b) { return b[1]; } // one byte of a buffer. // b: the buffer // i: the position - // returns: the byte, 0 when i is outside the buffer + // returns: the byte, 0 when i is outside the buffer (below 0, or at or past the length) static int get(word b, int i) { if (i < 0 || i >= b[0]) return 0; return rt.ld8(rt.addr_b(b + 2) + i); } - // sets one byte of a buffer. setting the byte at the current length makes the - // buffer one longer. + // sets one byte of a buffer. a write at or past the length makes the length + // i + 1, and the bytes skipped over are left at 0. // b: the buffer // i: the position, below the capacity // v: the value; only its low 8 bits are kept @@ -542,28 +553,41 @@ struct Buf { // with the collector, so freeing the input does not invalidate the result. // the first index equal to value, or -1 when no element matches. +// source: the array, only read +// value: the element to find int array_find<T>(fixed T[?].m source, T value) { int length = len(source); for (int i = 0; i < length; i++) if (source[i] == value) return i; return -1; } // true when an element equals value. +// source: the array, only read +// value: the element to find int array_contains<T>(fixed T[?].m source, T value) { return array_find(source, value) >= 0; } // the first index whose predicate is true, or -1 when none matches. +// source: the array, only read +// predicate: called on each element; nonzero means a match int array_find_if<T>(fixed T[?].m source, int(T).m predicate) { int length = len(source); for (int i = 0; i < length; i++) if (predicate(source[i])) return i; return -1; } // true when any element satisfies predicate; false for an empty array. +// source: the array, only read +// predicate: called on each element; nonzero means a match int array_any<T>(fixed T[?].m source, int(T).m predicate) { return array_find_if(source, predicate) >= 0; } // true when every element satisfies predicate, including an empty array. +// source: the array, only read +// predicate: called on each element; nonzero means a match +// returns: 1 or 0 int array_all<T>(fixed T[?].m source, int(T).m predicate) { int length = len(source); for (int i = 0; i < length; i++) if (!predicate(source[i])) return 0; return 1; } // the number of elements satisfying predicate. +// source: the array, only read +// predicate: called on each element; nonzero means a match int array_count<T>(fixed T[?].m source, int(T).m predicate) { int length = len(source); int count = 0; @@ -572,6 +596,9 @@ int array_count<T>(fixed T[?].m source, int(T).m predicate) { } // apply transform once to each element and return the transformed array. // the result element type follows the callback's return type. +// source: the array, only read +// transform: called once on each element, in order +// returns: a new array of the results, owned by the caller U[?].u array_map<T,U>(fixed T[?].m source, U(T).m transform) { int length = len(source); U[?] result = rt.new(U[?]); @@ -579,6 +606,9 @@ U[?].u array_map<T,U>(fixed T[?].m source, U(T).m transform) { return result; } // copy elements satisfying predicate into a new array, preserving order. +// source: the array, only read +// predicate: called on each element; nonzero keeps it +// returns: the new array, owned by the caller T[?].u array_filter<T>(fixed T[?].m source, int(T).m predicate) { int length = len(source); T[?] result = rt.new(T[?]); @@ -587,6 +617,10 @@ T[?].u array_filter<T>(fixed T[?].m source, int(T).m predicate) { } // fold elements from left to right, starting with initial; an empty array // returns initial without calling combine. +// source: the array, only read +// initial: the starting value +// combine: called as combine(total, element) for each element, in order +// returns: the folded value A array_reduce<T,A>(fixed T[?].m source, A initial, A(A,T).m combine) { int length = len(source); for (int i = 0; i < length; i++) initial = combine(initial, source[i]); diff --git a/src/lsp/server.zc b/src/lsp/server.zc index 1608c4c..3262e39 100644 --- a/src/lsp/server.zc +++ b/src/lsp/server.zc @@ -390,7 +390,7 @@ int isopc(int c) { int iskeyword(int n) { return n == run.s_fn || n == run.s_var || n == run.s_const || n == run.s_else || n == run.s_as || n == run.s_unchecked || n == run.s_immediate || n == run.s_case || n == run.s_default || n == run.s_do || n == run.s_while || n == run.s_enum || n == run.s_include || n == run.s_memdebug - || n == run.s_enhance || n == run.s_micro || n == run.s_vm || n == run.s_struct || n == run.s_type || n == run.s_typecheck || n == run.s_static; + || n == run.s_enhance || n == run.s_micro || n == run.s_vm || n == run.s_struct || n == run.s_type || n == run.s_typedef || n == run.s_typecheck || n == run.s_static; } // the record of the name at byte offset o (see rs_note in the compiler), or -1. // the records are sorted by offset, so this is a binary search. @@ -934,7 +934,7 @@ int reply_error(int code) { return 0; } -int hs_name = -1, hs_first = -1, hs_const; +int hs_name = -1, hs_first = -1, hs_const, hs_typedef, hs_tname; int bs_k, bs_off; // the embedded source and name offset found by bs_find // ---- hover ---- @@ -999,8 +999,8 @@ word hover_decl(int base, int ls, int le) { // it (hcs is -1 when none) which runs to the line at hdl. a declaration needs // no comment, so the signature still shows without one. int hover_scan(int i) { - hs_name = -1; hs_first = -1; hs_const = 0; - if (hover_source_decl(i) || hover_source_function(i)) return 1; + hs_name = -1; hs_first = -1; hs_const = 0; hs_typedef = 0; + if (hover_typedef(i) || hover_source_decl(i) || hover_source_function(i)) return 1; int base = doff[i], size = dsize[i], ls = 0, le, cs = 0 - 1, c0; while (ls < size) { le = ls; @@ -1182,6 +1182,12 @@ int hover_docs(int i, int head, int name, int length, int tail) { int hover_fill(int i) { int base = doff[i], o = hdl, c, cs, ls, typed = 0, k, run.start, end; hn = 0; + if (hs_typedef) { // typedef T name; as written, from its first word to its ; + hov_text("```zc\n"); c = hdl; + while (c < hdle) { hov_put(dc(base, c)); c++; } + hov_text("\n```"); hover_docs(i, hdl, hdl, 0 - 1, hdle); + return hn; + } if (hs_name >= 0) { hov_text("```zc\n"); c = hdl; while (c < hs_first) { hov_put(dc(base, c)); c++; } @@ -1624,9 +1630,11 @@ int hover_type_span(int i) { } if (best < 0) return 0; t = run.ht_type[best]; + // a typedef name is shown as its typedef, then the type it stands for + if (width == rt.len_w(hname) && run.ht_start[best] == hoff && hover_typedef(i)) { hover_fill(i); hover_type_info(t); return 1; } hov_text("```zc\n"); hov_type(t); hov_text("\n```"); hover_type_info(t); k = kwtext(); - if (k && (hname_is("word") || hname_is("int") || hname_is("char") || hname_is("bool") || hname_is("void") || hname_is("float") || hname_is("f32") || hname_is("f64") || hname_is("byte") || hname_is("u8") || hname_is("i8") || hname_is("u16") || hname_is("i16") || hname_is("u32") || hname_is("i32"))) { + if (k && (hname_is("word") || hname_is("int") || hname_is("char") || hname_is("bool") || hname_is("void") || hname_is("float") || hname_is("f32") || hname_is("f64") || hname_is("byte") || hname_is("string") || hname_is("u8") || hname_is("i8") || hname_is("u16") || hname_is("i16") || hname_is("u32") || hname_is("i32"))) { while (*k && *k != '~') k++; if (*k) { hov_text("\n\n"); hov_text(k + 1); } } @@ -1686,6 +1694,8 @@ char* kwtext() { if (hname_is("return")) return "return e; or return;~leaves the function with a value, or leaves a void function. returning an owned local transfers it to the caller automatically."; if (hname_is("enum")) return "enum name { A, B = 5 };~global constants. under typecheck on they are a type of their own, and a member can carry fields to make a constructor."; if (hname_is("struct")) return "struct name { fields };~a record type. struct name<T> { } makes it generic, one copy for each set of type arguments."; + if (hname_is("typedef")) return "typedef T name;~an alias for a type, the same as type name = T; but in C order. the name is another way to write T, not a new type. inside a function it lasts to the end of its block."; + if (hname_is("string")) return "string~a built-in alias for char*, a word string, as if typedef char* string; were written."; if (hname_is("type")) return "type name = T;~an alias for a type, such as type row = int[3]; for a pointer to an array."; if (hname_is("include")) return "include \"path\"; / include std;~compiles a file or the embedded standard library at that point, its signatures first."; if (hname_is("embed")) return "embed \"path\" as [type] name;~declares name with the bytes of the file at path, read when the unit is compiled. with no type, or bstr, name is a byte string; char* holds one character per word; a number type reads the bytes little-endian; T[] and T[n] lay them out as array elements."; @@ -2160,6 +2170,7 @@ int bs_name(char* path) { } // the offset of the name a declaration line declares: the word before its first delimiter int decl_off(int base, int ls, int le) { + if (hs_typedef) return hs_tname; if (hs_name >= 0) return hs_name; int dl = ls, e, b; while (dl < le && !hdelim(dc(base, dl))) dl++; @@ -2441,6 +2452,35 @@ int hover_source_function(int i) { } return 0; } +// the statement typedef T name; that declares hname, found by tokens, at the top level or in a block +// (the last such one before the cursor, else the first). hdl and hdle are the typedef word and the end +// of the ;, and hs_tname is where the name is. +int hover_typedef(int i) { + int t = 0, w, depth, last, found = -1, first = -1, fend, fname, hend, hname_at; + fm_lex(i); + while (t < fm_nt) { + if (fm_k[t] == 7) break; + if (!fm_is(i, t, "typedef")) { t++; continue; } + w = t + 1; depth = 0; last = -1; + while (w < fm_nt && fm_k[w] != 7) { + if (fm_k[w] == 6 && fm_o[w] == 2 && !depth) break; + if (fm_k[w] == 6 && (fm_o[w] == 5 || fm_o[w] == 6)) break; + if (fm_k[w] == 6 && fm_o[w] == 3) depth++; + else if (fm_k[w] == 6 && fm_o[w] == 4) depth--; + else if (fm_k[w] == 1 && !depth) last = w; + w++; + } + if (w < fm_nt && fm_k[w] == 6 && fm_o[w] == 2 && last > t && hs_match(i, last)) { + if (first < 0) { first = t; fend = fm_e[w]; fname = fm_s[last]; } + if (fm_s[t] <= hcursor) { found = t; hend = fm_e[w]; hname_at = fm_s[last]; } + } + t = w + 1; + } + if (first < 0) return 0; + if (found < 0) { found = first; hend = fend; hname_at = fname; } + hdl = fm_s[found]; hdle = hend; hs_tname = hname_at; hs_typedef = 1; hs_name = -1; hs_first = -1; hs_const = 0; hcs = -1; + return 1; +} int hover_source_decl(int i) { int t = 0, head = -1, first = -1, candidate = -1, depth = 0, brackets = 0, init = 0, constant = 0, matched = 0, tail, prev = -1; fm_lex(i); |
