本文を読み飛ばす

nim: Parses an input `sed expression` with nim-lang

  • Normal case: parses an input by the characters
  • Failure case: splits by delimiters
  • Regex case: ?

Normal case: parses an input by the characters

  • this is a simple way to parse, but it is a repeated pattern, not fun...
block:
    var (f_del, f_rep, f_opt) = (false, true, false)
    for ch in input:
        if f_del:
            if ch == delimiter:
                if f_rep:   f_rep = false
                else:       f_opt = treu
                continue
            if f_rep: (f_del, rep) = (false, rep & ch)
            else:     (f_del, sub) = (false, sub & ch)
            continue
        elif ch == delimiter:
            f_del = true
        elif f_opt:
            opt &= ch
        elif f_rep:
            rep &= ch
        else:
            sub &= ch

Failure case: split by delimiters

  • We can easily split the input by delimiter with strutils.split.
  • But it is difficult to determine the escaped delimiter character in this method.

    • The escaped delimiters can be determined with the null string in splitted sequence.
    • I can't implement the head and tail delimiters
block:
    let tmp = try: fmt[1 ..^ f_rep].split(pfx)
              except IndexDefect: return fallback1
    if len(tmp) < 2 or len(tmp[0]) < 1:
        return fallback1
    let (pat, ret) =
        if len(tmp) == 2:
            (tmp[0], tmp[1])
        else:
            (tmp[0], tmp[1])


    var (pat, rep, f_esc) = (tmp[0], "", false)
    # escaped: "abc", "", "efg"  => abc%efg
    # NG: "abc", "bcd" => abc%bcd
    for i in tmp:
        if len(pat) < 1 and len(rep) < 1:
            if f_esc:         # escape: a%%b => ["a", "", "b"] => a%b
                (f_esc, pat) = (false, pat & pfx & i)
            elif len(i) > 0:  # found separater
                rep = i
            elif len(i) < 1:  # found escaping
                f_esc = true
            continue
        if f_esc:
            (f_esc, rep) = (false, rep & pfx & i)
            continue
        if len(i) < 1:
            f_esc = true; continue
        # found extra parameter => error
        return fallback1
    return (pat, rep, f_rep == 2)

Regex case: ?

コメント

Comments powered by Disqus
宣伝: