ExtFmt.rs 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* The 'fmt' extension is modeled on the posix printf system.
 *
 * A posix conversion ostensibly looks like this:
 *
 * %[parameter][flags][width][.precision][length]type
 *
 * Given the different numeric type bestiary we have, we omit the 'length'
 * parameter and support slightly different conversions for 'type':
 *
 * %[parameter][flags][width][.precision]type
 *
 * we also only support translating-to-rust a tiny subset of the possible
 * combinations at the moment.
 */

16 17 18
import option.none;
import option.some;

19 20 21 22 23 24 25 26 27 28 29
/*
 * We have a CT (compile-time) module that parses format strings into a
 * sequence of conversions. From those conversions AST fragments are built
 * that call into properly-typed functions in the RT (run-time) module.  Each
 * of those run-time conversion functions accepts another conversion
 * description that specifies how to format its output.
 *
 * The building of the AST is currently done in a module inside the compiler,
 * but should migrate over here as the plugin interface is defined.
 */

30 31 32 33 34 35
// Functions used by the fmt extension at compile time
mod CT {
    tag signedness {
        signed;
        unsigned;
    }
36

37 38 39 40
    tag caseness {
        case_upper;
        case_lower;
    }
41

42 43 44 45 46 47 48 49 50
    tag ty {
        ty_bool;
        ty_str;
        ty_char;
        ty_int(signedness);
        ty_bits;
        ty_hex(caseness);
        // FIXME: More types
    }
51

52 53 54 55 56 57 58
    tag flag {
        flag_left_justify;
        flag_left_zero_pad;
        flag_left_space_pad;
        flag_plus_if_positive;
        flag_alternate;
    }
59

60 61 62 63 64 65
    tag count {
        count_is(int);
        count_is_param(int);
        count_is_next_param;
        count_implied;
    }
66

67 68 69 70 71 72
    // A formatted conversion from an expression to a string
    type conv = rec(option.t[int] param,
                    vec[flag] flags,
                    count width,
                    count precision,
                    ty ty);
73

74 75 76 77 78
    // A fragment of the output sequence
    tag piece {
        piece_string(str);
        piece_conv(conv);
    }
79

80 81 82 83 84 85 86 87 88 89 90
    fn parse_fmt_string(str s) -> vec[piece] {
        let vec[piece] pieces = vec();
        auto lim = _str.byte_len(s);
        auto buf = "";

        fn flush_buf(str buf, &vec[piece] pieces) -> str {
            if (_str.byte_len(buf) > 0u) {
                auto piece = piece_string(buf);
                pieces += vec(piece);
            }
            ret "";
91 92
        }

93 94 95 96
        auto i = 0u;
        while (i < lim) {
            auto curr = _str.substr(s, i, 1u);
            if (_str.eq(curr, "%")) {
97
                i += 1u;
98 99 100 101 102 103 104 105 106 107 108 109 110
                if (i >= lim) {
                    log "unterminated conversion at end of string";
                    fail;
                }
                auto curr2 = _str.substr(s, i, 1u);
                if (_str.eq(curr2, "%")) {
                    i += 1u;
                } else {
                    buf = flush_buf(buf, pieces);
                    auto res = parse_conversion(s, i, lim);
                    pieces += vec(res._0);
                    i = res._1;
                }
111
            } else {
112 113
                buf += curr;
                i += 1u;
114 115
            }
        }
116 117
        buf = flush_buf(buf, pieces);
        ret pieces;
118 119
    }

120 121 122
    fn peek_num(str s, uint i, uint lim) -> option.t[tup(uint, uint)] {
        if (i >= lim) {
            ret none[tup(uint, uint)];
123
        }
124 125 126 127

        auto c = s.(i);
        if (!('0' as u8 <= c && c <= '9' as u8)) {
            ret option.none[tup(uint, uint)];
128 129
        }

130 131 132 133 134 135 136 137 138 139 140
        auto n = (c - ('0' as u8)) as uint;
        alt (peek_num(s, i + 1u, lim)) {
            case (none[tup(uint, uint)]) {
                ret some[tup(uint, uint)](tup(n, i + 1u));
            }
            case (some[tup(uint, uint)](?next)) {
                auto m = next._0;
                auto j = next._1;
                ret some[tup(uint, uint)](tup(n * 10u + m, j));
            }
        }
141

142
    }
143

144 145 146 147 148 149 150 151 152 153 154 155
    fn parse_conversion(str s, uint i, uint lim) -> tup(piece, uint) {
        auto parm = parse_parameter(s, i, lim);
        auto flags = parse_flags(s, parm._1, lim);
        auto width = parse_count(s, flags._1, lim);
        auto prec = parse_precision(s, width._1, lim);
        auto ty = parse_type(s, prec._1, lim);
        ret tup(piece_conv(rec(param = parm._0,
                               flags = flags._0,
                               width = width._0,
                               precision = prec._0,
                               ty = ty._0)),
                ty._1);
156 157
    }

158 159
    fn parse_parameter(str s, uint i, uint lim) -> tup(option.t[int], uint) {
        if (i >= lim) {
160 161
            ret tup(none[int], i);
        }
162 163 164 165

        auto num = peek_num(s, i, lim);
        alt (num) {
            case (none[tup(uint, uint)]) {
166 167
                ret tup(none[int], i);
            }
168 169 170 171 172 173 174 175 176 177
            case (some[tup(uint, uint)](?t)) {
                auto n = t._0;
                auto j = t._1;
                if (j < lim && s.(j) == '$' as u8) {
                    ret tup(some[int](n as int), j + 1u);
                }
                else {
                    ret tup(none[int], i);
                }
            }
178 179 180
        }
    }

181 182
    fn parse_flags(str s, uint i, uint lim) -> tup(vec[flag], uint) {
        let vec[flag] noflags = vec();
183

184 185 186
        if (i >= lim) {
            ret tup(noflags, i);
        }
187

188 189 190 191 192 193 194
        fn more_(flag f, str s, uint i, uint lim) -> tup(vec[flag], uint) {
            auto next = parse_flags(s, i + 1u, lim);
            auto rest = next._0;
            auto j = next._1;
            let vec[flag] curr = vec(f);
            ret tup(curr + rest, j);
        }
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        auto more = bind more_(_, s, i, lim);

        auto f = s.(i);
        if (f == ('-' as u8)) {
            ret more(flag_left_justify);
        } else if (f == ('0' as u8)) {
            ret more(flag_left_zero_pad);
        } else if (f == (' ' as u8)) {
            ret more(flag_left_space_pad);
        } else if (f == ('+' as u8)) {
            ret more(flag_plus_if_positive);
        } else if (f == ('#' as u8)) {
            ret more(flag_alternate);
        } else {
            ret tup(noflags, i);
        }
212 213
    }

214 215 216
    fn parse_count(str s, uint i, uint lim) -> tup(count, uint) {
        if (i >= lim) {
            ret tup(count_implied, i);
217
        }
218 219 220 221 222 223 224 225 226 227 228

        if (s.(i) == ('*' as u8)) {
            auto param = parse_parameter(s, i + 1u, lim);
            auto j = param._1;
            alt (param._0) {
                case (none[int]) {
                    ret tup(count_is_next_param, j);
                }
                case (some[int](?n)) {
                    ret tup(count_is_param(n), j);
                }
229
            }
230 231 232 233 234 235 236 237 238
        } else {
            auto num = peek_num(s, i, lim);
            alt (num) {
                case (none[tup(uint, uint)]) {
                    ret tup(count_implied, i);
                }
                case (some[tup(uint, uint)](?num)) {
                    ret tup(count_is(num._0 as int), num._1);
                }
239 240 241 242
            }
        }
    }

243 244 245 246
    fn parse_precision(str s, uint i, uint lim) -> tup(count, uint) {
        if (i >= lim) {
            ret tup(count_implied, i);
        }
247

248
        if (s.(i) == '.' as u8) {
249 250 251 252 253 254 255 256 257 258 259
            auto count = parse_count(s, i + 1u, lim);
            // If there were no digits specified, i.e. the precision
            // was ".", then the precision is 0
            alt (count._0) {
                case (count_implied) {
                    ret tup(count_is(0), count._1);
                }
                case (_) {
                    ret count;
                }
            }
260 261 262
        } else {
            ret tup(count_implied, i);
        }
263 264
    }

265 266 267 268 269
    fn parse_type(str s, uint i, uint lim) -> tup(ty, uint) {
        if (i >= lim) {
            log "missing type in conversion";
            fail;
        }
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
        auto t;
        auto tstr = _str.substr(s, i, 1u);
        if (_str.eq(tstr, "b")) {
            t = ty_bool;
        } else if (_str.eq(tstr, "s")) {
            t = ty_str;
        } else if (_str.eq(tstr, "c")) {
            t = ty_char;
        } else if (_str.eq(tstr, "d")
                   || _str.eq(tstr, "i")) {
            // TODO: Do we really want two signed types here?
            // How important is it to be printf compatible?
            t = ty_int(signed);
        } else if (_str.eq(tstr, "u")) {
            t = ty_int(unsigned);
        } else if (_str.eq(tstr, "x")) {
            t = ty_hex(case_lower);
        } else if (_str.eq(tstr, "X")) {
            t = ty_hex(case_upper);
        } else if (_str.eq(tstr, "t")) {
            t = ty_bits;
        } else {
            log "unknown type in conversion";
            fail;
        }
296

297 298
        ret tup(t, i + 1u);
    }
299
}
300

301 302 303 304
// Functions used by the fmt extension at runtime. For now there are a lot of
// decisions made a runtime. If it proves worthwhile then some of these
// conditions can be evaluated at compile-time. For now though it's cleaner to
// implement it this way, I think.
305
mod RT {
306

307 308 309 310 311 312 313 314
    tag flag {
        flag_left_justify;
        // FIXME: This is a hack to avoid creating 0-length vec exprs,
        // which have some difficulty typechecking currently. See
        // comments in front.extfmt.make_flags
        flag_none;
    }

315 316 317 318 319
    tag count {
        count_is(int);
        count_implied;
    }

320 321 322 323 324 325 326
    tag ty {
        ty_default;
        ty_bits;
        ty_hex_upper;
        ty_hex_lower;
    }

327 328 329 330
    // FIXME: May not want to use a vector here for flags;
    // instead just use a bool per flag
    type conv = rec(vec[flag] flags,
                    count width,
331
                    count precision,
332
                    ty ty);
333 334

    fn conv_int(&conv cv, int i) -> str {
335
        ret pad(cv, _int.to_str(i, 10u));
336
    }
337

338
    fn conv_uint(&conv cv, uint u) -> str {
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

        // Convert a uint to string with a minimum number of digits.  If
        // precision is 0 and num is 0 then the result is the empty
        // string. Could move this to _str, but it doesn't seem all that
        // useful.
        fn uint_to_str_prec(uint num, uint radix, uint prec) -> str {
            auto s;

            if (prec == 0u && num == 0u) {
                s = "";
            } else {
                s = _uint.to_str(num, radix);
                auto len = _str.char_len(s);
                if (len < prec) {
                    auto diff = prec - len;
                    auto pad = str_init_elt('0', diff);
                    s = pad + s;
                }
            }

            ret s;
        }

        fn get_precision(&conv cv) -> uint {
            alt (cv.precision) {
                case (count_is(?c)) {
                    ret c as uint;
                }
                case (count_implied) {
                    ret 1u;
                }
            }
        }

        auto prec = get_precision(cv);

375
        auto res;
376 377
        alt (cv.ty) {
            case (ty_default) {
378
                res = uint_to_str_prec(u, 10u, prec);
379 380
            }
            case (ty_hex_lower) {
381
                res = uint_to_str_prec(u, 16u, prec);
382
            }
383
            case (ty_hex_upper) {
384
                res = _str.to_upper(uint_to_str_prec(u, 16u, prec));
385 386
            }
            case (ty_bits) {
387
                res = uint_to_str_prec(u, 2u, prec);
388
            }
389
        }
390
        ret pad(cv, res);
391
    }
392

393
    fn conv_bool(&conv cv, bool b) -> str {
394
        if (b) {
395
            ret pad(cv, "true");
396
        } else {
397
            ret pad(cv, "false");
398 399 400
        }
    }

401
    fn conv_char(&conv cv, char c) -> str {
402 403 404 405
        ret pad(cv, _str.from_char(c));
    }

    fn conv_str(&conv cv, str s) -> str {
406 407 408 409 410 411 412 413 414 415 416 417 418
        auto unpadded = s;
        alt (cv.precision) {
            case (count_implied) {
            }
            case (count_is(?max)) {
                // For strings, precision is the maximum characters displayed
                if (max as uint < _str.char_len(s)) {
                    // FIXME: substr works on bytes, not chars!
                    unpadded = _str.substr(s, 0u, max as uint);
                }
            }
        }
        ret pad(cv, unpadded);
419 420
    }

421 422 423 424 425 426 427 428
    // FIXME: This might be useful in _str, but needs to be utf8 safe first
    fn str_init_elt(char c, uint n_elts) -> str {
        auto svec = _vec.init_elt[u8](c as u8, n_elts);
        // FIXME: Using unsafe_from_bytes because rustboot
        // can't figure out the is_utf8 predicate on from_bytes?
        ret _str.unsafe_from_bytes(svec);
    }

429 430 431 432 433 434 435 436 437 438 439
    fn pad(&conv cv, str s) -> str {
        alt (cv.width) {
            case (count_implied) {
                ret s;
            }
            case (count_is(?width)) {
                // FIXME: Maybe width should be uint
                auto uwidth = width as uint;
                auto strlen = _str.char_len(s);
                if (strlen < uwidth) {
                    auto diff = uwidth - strlen;
440
                    auto padstr = str_init_elt(' ', diff);
441 442 443 444 445
                    if (have_flag(cv.flags, flag_left_justify)) {
                        ret s + padstr;
                    } else {
                        ret padstr + s;
                    }
446 447 448 449 450
                } else {
                    ret s;
                }
            }
        }
451
    }
452 453 454 455 456 457 458 459 460

    fn have_flag(vec[flag] flags, flag f) -> bool {
        for (flag candidate in flags) {
            if (candidate == f) {
                ret true;
            }
        }
        ret false;
    }
461
}
462 463 464 465 466 467 468 469 470

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C .. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End: