コード例 #1
0
 public void Parse(string text)
 {
     this.contextlist = new Gen::Dictionary <string, Context>();
     this.original    = text;
     this.processed   = this.PreprocessDirectives(this.original);
     this.Read(this.processed);
 }
コード例 #2
0
 private static void EasyParse_addfactor(ref Rational r, Gen::Dictionary <string, int> dic, string w, char mode)
 {
     try{
         long val = long.Parse(w);
         if (mode == '/')
         {
             r /= val;
         }
         else
         {
             r *= val;
         }
     }catch {
         int exp = mode == '/'?-1:1;
         if (!dic.ContainsKey(w))
         {
             dic[w] = exp;
         }
         else
         {
             if ((dic[w] += exp) == 0)
             {
                 dic.Remove(w);
             }
         }
     }
 }
コード例 #3
0
 public ImageCollection(ThumbsFile root) : base()
 {
     this.count  = 0;
     this.root   = root;
     this.paths  = new Gen::Dictionary <string, Thumb>();
     this.sorted = new afh.Collections.SortedArrayP <Thumb>();
 }
コード例 #4
0
ファイル: [o]ScriptModel.cs プロジェクト: akinomyoga/mwg
        private object ToManaged(Gen::Dictionary <Array, object[]> nest)
        {
            if (this.isNull || this.isUndefined)
            {
                return(null);
            }
            if (this.GetType() == typeof(Array))
            {
                Array thisArr = (Array)this;

                // 自身を含むような配列で無限ループになるのを防ぐ
                if (nest.ContainsKey(thisArr))
                {
                    return(nest[thisArr]);
                }

                int      m      = thisArr.length;
                object[] retArr = new object[m];
                nest[thisArr] = retArr;
                for (int i = 0; i < m; i++)
                {
                    retArr[i] = thisArr[i].ToManaged(nest);
                }
                return(retArr);
            }
            return(this.obj);
        }
コード例 #5
0
 static Icons()
 {
     bmps         = new System.Collections.Generic.Dictionary <string, System.Drawing.Bitmap>();
     asms         = new System.Collections.Generic.Dictionary <string, System.Reflection.Assembly>();
     asms[FORMS]  = System.Reflection.Assembly.GetAssembly(typeof(System.Windows.Forms.Form));
     asms[DESIGN] = System.Reflection.Assembly.GetAssembly(typeof(System.ComponentModel.Design.CollectionEditor));
 }
コード例 #6
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
    /// <summary>
    /// 文字列をその頻度が多い順に列挙します。
    /// </summary>
    /// <param name="d_tok">文字列と頻度のペアを格納した Dictionary を返します。</param>
    /// <returns>文字列の列挙子を返します。</returns>
    static Gen::IEnumerable <string> EnumFreqOrder(Gen::Dictionary <string, int> d_tok)
    {
        // 頻度順に並び替え
        int c = d_tok.Count;

        string[] tokens = new string[c];
        int[]    freqs  = new int[c];
        int      j      = 0;

        foreach (string k in d_tok.Keys)
        {
            tokens[j] = k;
            freqs[j]  = d_tok[k];
            j++;
        }

        /*
         * for (j = 0; j < c; j++)
         * args.WriteLine("token pair({0}, {1})", freqs[j], tokens[j]);
         * args.WriteLine("---- sort ----");
         * //*/
        System.Array.Sort(freqs, tokens);

        /*
         * for (j = 0; j < c; j++)
         * args.WriteLine("token pair#{2}({0}, {1})", freqs[j], tokens[j], j);
         * //*/

        // 列挙
        for (int i = c - 1; i >= 0; i--)
        {
            yield return(tokens[i]);
        }
    }
コード例 #7
0
ファイル: Selector.cs プロジェクト: akinomyoga/afh
        public System.Collections.IEnumerable Enumerate(HTMLElement parent, Gen::Dictionary <string, string> dict)
        {
            System.Collections.IEnumerable @enum = this.getBaseEnum(parent);
            if (@enum == null)
            {
                yield break;
            }
            int  i;
            bool first = this.relation == '+' || this.relation == '-';
            int  stcC  = dict.Count;

            foreach (HTMLElement elem in @enum)
            {
                for (i = 0; i < this.len; i++)
                {
                    if (!this.testers[i].Test(elem, dict))
                    {
                        break;
                    }
                }
                if (i == this.len)
                {
                    yield return(elem);

                    if (first)
                    {
                        break;
                    }
                }
            }
        }
コード例 #8
0
            /// <summary>
            /// inline の template 参照を解決します。
            /// </summary>
            /// <param name="text">変換対象の文字列を指定します。</param>
            /// <param name="start">変換の開始点を指定します。</param>
            /// <returns>インスタンス化した関数のコードを返します。</returns>
            public string ApplyToInlineEntity(ref string text, int start)
            {
                int i = 0;
                Gen::Dictionary <string, string> instances = new Gen::Dictionary <string, string>();

                System.Text.StringBuilder build = new System.Text.StringBuilder();
                Template temp = this;

                string rp = string.Format(TMPL_INLN_ENTT, this.name + TMPL_ARGS(count));

                text = Rgx::Regex.Replace(text, rp, delegate(Rgx::Match m) {
                    // より後の物しか変換しない
                    if (m.Index < start)
                    {
                        return(m.Value);
                    }

                    string args = GetArgStamp(m.Groups["arg"].Captures);
                    if (!instances.ContainsKey(args))
                    {
                        instances[args] = temp.name + "_instance_" + i++.ToString();
                        build.AppendLine(temp.Instantiate(instances[args], m.Groups["arg"].Captures));
                    }
                    return(instances[args]);
                }, Rgx::RegexOptions.Multiline);

                return(build.ToString());
            }
コード例 #9
0
ファイル: Selector.cs プロジェクト: akinomyoga/afh
        public override bool Test(HTMLElement elem, Gen::Dictionary <string, string> dict)
        {
            this.var = null;
            bool r = base.Test(elem);

            if (this.var != null)
            {
                dict[this.value] = this.var;
            }
            return(r);
        }
コード例 #10
0
        /// <summary>
        /// 簡単な文字列読み取りを実行します。
        /// 正しくない文字列の読み取りを実行した場合の動作は未定です。
        /// </summary>
        /// <param name="str">各変数を空白、'*'、'/' で区切ったリストを項の表現として渡します。</param>
        /// <returns>読み取った結果生成した文字列を返します。</returns>
        public static Member EasyParse(string str)
        {
            int    i    = 0;
            char   mode = '*';
            string w    = "";

            Rational r = 1;
            Gen::Dictionary <string, int> dic = new Gen::Dictionary <string, int>();

            while (i < str.Length)
            {
                char c = str[i++];

                // 文字分類
                if (c <= ' ')
                {
                    c = '*';
                }
                else if (c == ':')
                {
                    c = '/';
                }

                // 読み取り
                if (c == '/' || c == '*')
                {
                    // 変数の登録
                    if (w != "")
                    {
                        EasyParse_addfactor(ref r, dic, w, mode);
                    }
                    mode = c; w = "";
                }
                else
                {
                    w += c;
                }
            }

            // 変数の登録
            if (w != "")
            {
                EasyParse_addfactor(ref r, dic, w, mode);
            }

            // Member 生成
            Variable[] vars = new Variable[dic.Count];
            i = 0;
            foreach (Gen::KeyValuePair <string, int> pair in dic)
            {
                vars[i++] = new Variable(pair.Key, pair.Value);
            }
            return(new Member(r, vars));
        }
コード例 #11
0
ファイル: Regex.cs プロジェクト: akinomyoga/afh
            /// <summary>
            /// 指定した番号の一致グループを取得します。
            /// </summary>
            /// <param name="index">取得するグループの番号を指定します。
            /// 番号は、現在のノードを基準にして付けられます。
            /// 則ち、現在のノードの子ノードの</param>
            /// <returns>指定した番号の一致グループを返します。</returns>
            public Group <TCapture> this[int index] {
                get{
                    Gen::Dictionary <int, Group <TCapture> > c = CacheI;
                    Group <TCapture> ret;
                    if (!c.TryGetValue(index, out ret))
                    {
                        c[index] = new Group <TCapture>(parent, index);
                    }

                    return(c[index]);
                }
            }
コード例 #12
0
ファイル: Regex.cs プロジェクト: akinomyoga/afh
            /// <summary>
            /// 指定した名前の一致グループを取得します。
            /// </summary>
            /// <param name="name">取得する一致グループの名前を指定します。</param>
            /// <returns>指定した名前の一致グループを返します。</returns>
            public Group <TCapture> this[string name] {
                get{
                    Gen::Dictionary <string, Group <TCapture> > c = CacheN;
                    Group <TCapture> ret;
                    if (!c.TryGetValue(name, out ret))
                    {
                        c[name] = new Group <TCapture>(parent, name);
                    }

                    return(c[name]);
                }
            }
コード例 #13
0
        private void SaveStatus()
        {
            Ref::BindingFlags BF = Ref::BindingFlags.Instance | Ref::BindingFlags.NonPublic;

            System.Type ptype = typeof(System.Windows.Forms.PictureBox);
            this.status = new Gen::Dictionary <Ref::FieldInfo, object>();

            foreach (Ref::FieldInfo finfo in ptype.GetFields(BF))
            {
                this.status.Add(finfo, finfo.GetValue(this));
            }
        }
コード例 #14
0
        //=================================================
        //		Preprocess Directives
        //=================================================
        private string PreprocessDirectives(string text)
        {
            Gen::Dictionary <int, string> errors = new Gen::Dictionary <int, string>();
            Gen::List <DefineMacro>       defs   = new Gen::List <DefineMacro>();

            DefineMacro def;
            string      text2 = reg_directive.Replace(text, delegate(System.Text.RegularExpressions.Match m){
                if (m.Groups["nspace"].Success)
                {
                    if (this.@namespace != null)
                    {
                        errors.Add(m.Index, "名前空間を複数指定する事は出来ません。");
                    }
                    this.@namespace = m.Groups["nspace"].Value;
                }
                else if (m.Groups["class"].Success)
                {
                    if (this.classname != null)
                    {
                        errors.Add(m.Index, "クラス名を複数指定する事は出来ません。");
                    }
                    this.classname = m.Groups["class"].Value;
                }
                else if (m.Groups["defname"].Success)
                {
                    def         = new DefineMacro();
                    def.name    = m.Groups["defname"].Value;
                    def.Content = m.Groups["defcontent"].Value;

                    // 引数リスト
                    System.Text.RegularExpressions.CaptureCollection capts = m.Groups["defarg"].Captures;
                    int iM   = capts.Count;
                    def.args = new string[capts.Count];
                    for (int i = 0; i < iM; i++)
                    {
                        def.args[i] = capts[i].Value;
                    }

                    defs.Add(def);
                }
                return(reg_remove.Replace(m.Value, ""));
            });

            foreach (DefineMacro define in defs)
            {
                define.Apply(ref text2);
            }

            return(text2);
        }
コード例 #15
0
ファイル: Selector.cs プロジェクト: akinomyoga/afh
        public override bool Test(HTMLElement elem, Gen::Dictionary <string, string> dict)
        {
            if (this.selector == null)
            {
                return(true);
            }
            Gen::Dictionary <string, string> d = selector.GetFirstDictionary(elem);

            if (d == null)
            {
                return(false);
            }
            foreach (Gen::KeyValuePair <string, string> p in d)
            {
                dict[p.Key] = p.Value;
            }
            return(true);
        }
コード例 #16
0
        public static Expression EasyParse(string str)
        {
            Expression x = new Expression();

            int    sign  = 1;
            int    i     = 0;
            int    start = i;
            string w;
            Gen::Dictionary <string, int> dic = new Gen::Dictionary <string, int>();

            while (i < str.Length)
            {
                char c = str[i];

                if (c == '+' || c == '-')
                {
                    w = str.Substring(start, i - start).Trim();
                    if (w != "")
                    {
                        Member m = Member.EasyParse(w);
                        x.AddMember(sign == 1?m:-m);
                        sign = 1;
                    }

                    if (c == '-')
                    {
                        sign = -sign;
                    }
                    start = i + 1;
                }

                i++;
            }

            w = str.Substring(start, i - start).Trim();
            if (w != "")
            {
                Member m = Member.EasyParse(w);
                x.AddMember(sign == 1?m:-m);
                sign = 1;
            }

            return(x);
        }
コード例 #17
0
        private static void ResolveTemplate(ref string text, ReportError report)
        {
            int i;

            // Entity に番号付け
            i = 0;
            Gen::Dictionary <string, int> indices = new Gen::Dictionary <string, int>();

            text = rx_entities_raw.Replace(text, delegate(Rgx::Match m){
                string key   = i++.ToString();
                int sharp    = m.Groups["sharp"].Index;
                indices[key] = sharp - 2;
                sharp       -= m.Index;
                return(m.Value.Substring(0, sharp) + "#" + key + m.Value.Substring(sharp));
            });

            // 一つずつ template を読込・適用
            Rgx::MatchCollection mc = rx_template_s.Matches(text);

            for (i = mc.Count - 1; i >= 0; i--)
            {
                ResolveTemplate(ref text, mc[i], report);
            }

            // #←template が残っていた場合
            foreach (Rgx::Match m in rx_template_e.Matches(text))
            {
                report("//#←template に対応する //#→template が存在しません。", m.Index);
            }

            // Entity が残っていた場合
            foreach (Rgx::Match m in rx_entities.Matches(text))
            {
                report("解決出来ない template 利用が存在します。", indices[m.Groups["num"].Value]);
            }
            // 方法
            // 1. ENTITY に数字を付け、元の位置との対応を記録
            // 2. ENTITY+数字 を検索し、数字部分から元の位置を取得
        }
コード例 #18
0
ファイル: Selector.cs プロジェクト: akinomyoga/afh
        public virtual System.Collections.Generic.IEnumerable <Gen::Dictionary <string, string> > EnumDictionary(HTMLElement parent)
        {
            int m = simpleEnums.Length;

            if (m == 0)
            {
                yield break;
            }
            System.Collections.IEnumerator[]       @enum = new System.Collections.IEnumerator[m];
            /*☆*/ Gen::Dictionary <string, string> dic   = new Gen::Dictionary <string, string>();
            HTMLElement e;
            bool        move; int i = 0, imax = m - 1;

            /*☆*/ @enum[0] = this.simpleEnums[0].Enumerate(parent, dic).GetEnumerator();
            while (i >= 0)
            {
                try{ move = @enum[i].MoveNext(); }catch (System.Exception exc) {
                    __dll__.log.WriteError(exc, "HTML 要素の列挙中にエラーが発生しました。(列挙に使用している Selector は " + this.ToString() + " )");
                    yield break;
                }
                if (move)
                {
                    e = (HTMLElement)@enum[i].Current;
                    if (i == imax)
                    {
                        yield return(dic);
                        /*☆*/ }
                    else
                    {
                        @enum[++i] = simpleEnums[i].Enumerate(e, dic).GetEnumerator();
                    }
                }
                else
                {
                    i--;
                }
            }
        }
コード例 #19
0
 static HTMLElement()
 {
     dictHtmlTagName = new Gen::Dictionary <string, bool>();
     string[] tagNames =
     {
         "a",        "abbr",      "acronym",    "address",  "applet",   "area",   "b",        "base",     "basefont", "bdo",
         "bgsound",  "big",       "blockquote", "body",     "br",       "button", "caption",  "center",   "cite",     "code",
         "col",      "colgroup",  "comment",    "dd",       "del",      "dfn",    "dir",      "div",      "dl",       "dt",
         "em",       "embed",     "fieldset",   "font",     "form",     "frame",  "frameset", "head",     "h1",       "h2",
         "h3",       "h4",        "h5",         "h6",       "hr",       "html",   "i",        "iframe",   "img",      "input",
         "ins",      "isindex",   "kbd",        "label",    "legend",   "li",     "link",     "listing",  "map",      "marquee",
         "menu",     "meta",      "nobr",       "noframes", "noscript", "object", "ol",       "optgroup", "option",   "p",
         "param",    "plaintext", "q",          "rt",       "ruby",     "rule",   "s",        "samp",     "script",   "select",
         "small",    "span",      "strike",     "strong",   "style",    "sub",    "sup",      "table",    "tbody",    "td",
         "textarea", "tfoot",     "th",         "thead",    "title",    "tr",     "tt",       "u",        "ul",       "var",
         "wbr",      "xmp",
         "blink",    "ilayer",    "layer",      "multicol", "nolayer",  "spacer"
     };
     foreach (string tagName in tagNames)
     {
         dictHtmlTagName.Add(tagName, true);
     }
 }
コード例 #20
0
ファイル: Parse-Scanner.cs プロジェクト: akinomyoga/afh
        //============================================================
        //		コマンド \* の読み取り
        //============================================================
        private void readCommand(Gen::Dictionary <string, CommandData> commands)
        {
            __debug__.RegexParserToDo("複数文字名のコマンド");

            if (!next)
            {
                error(@"\ の後にコマンド名が続いていません。");
                wtype = WordType.Text;
                return;
            }
            add; next;

            CommandData dat;

            if (!commands.TryGetValue(cword, out dat))
            {
                error(@"指定した名前のコマンドは登録されていません。");
                wtype = WordType.Text;
                return;
            }

            if (dat.ArgumentType == CommandArgumentType.Brace)
            {
                if ("not:{")
                {
                    value = null;
                }
                else
                {
                    string cmd = cword;
                    cword = "";
                    if (!next)
                    {
                        goto ERR_ARG;
                    }

                    int  iP     = 1;
                    bool escape = false;
                    while (true)
                    {
                        if (escape)
                        {
                            escape = false;
                        }
                        else
                        {
                            if ("is:{")
                            {
                                iP++;
                            }
                            else if ("is:}")
                            {
                                if (--iP == 0)
                                {
                                    lreader.MoveNext(); break;
                                }
                            }
                            else if ("is:\\")
                            {
                                escape = true;
                            }
                        }
                        add; if (!next)
                        {
                            goto ERR_ARG;
                        }
                    }
                    value = cword;
                    cword = cmd;
                    return;

ERR_ARG:
                    value = cword;
                    cword = cmd;
                    error("引数の終端が来ない内に、正規表現の末端に達しました。");
                }
            }
        }
コード例 #21
0
 private ImageCollection(int capacity) : base(capacity)
 {
     this.paths  = new Gen::Dictionary <string, Thumb>(capacity);
     this.sorted = new afh.Collections.SortedArrayP <Thumb>(capacity);
 }
コード例 #22
0
        public void dbg_NearImage()
        {
            ImageDirectory overlap = new ImageDirectory("<重複検索>", root);
            Gen::Dictionary <Image, ImageDirectory> groups = new Gen::Dictionary <Image, ImageDirectory>();

            afh.ImageArrange.ProgressDialog progress = new ProgressDialog();
            progress.Title       = "重複比較中 ...";
            progress.ProgressMax = this.sorted.Count;

            progress.Show();
            for (int i = 0; i < this.sorted.Count; i++)
            {
                Image img1 = new Image(this.root, this.sorted[i]);

                if (i % 50 == 0)
                {
                    progress.Description = "画像 '" + img1.thm.filepath + "' の類似画像を探索中 ...";
                    if (progress.IsCanceled)
                    {
                        return;
                    }
                }

                for (int j = i + 1; j < this.sorted.Count; j++)
                {
                    Image img2 = new Image(this.root, this.sorted[j]);
                    if (!Image.EqualAspect(img1, img2))
                    {
                        break;
                    }

                    if (Image.Resembles(img1, img2))
                    {
                        ImageDirectory group1 = null;
                        ImageDirectory group2 = null;
                        bool           b1     = groups.TryGetValue(img1, out group1);
                        bool           b2     = groups.TryGetValue(img2, out group2);
                        switch ((b1?1:0) | (b2?2:0))
                        {
                        case 3:                                 // 両方
                            if (group1 == group2)
                            {
                                break;
                            }
                            // 両グループの併合
                            overlap.dirs.Remove(group2);
                            foreach (Image img in group2.EnumImages())
                            {
                                group1.Add(img);
                                groups[img] = group1;
                            }
                            break;

                        case 1:                                 // group1 だけ
                            group1.Add(img2);
                            groups.Add(img2, group1);
                            break;

                        case 2:                                 // group2 だけ
                            group2.Add(img1);
                            groups.Add(img1, group2);
                            break;

                        case 0:                                 // 両者未登録
                            ImageDirectory group = new ImageDirectory("Group " + overlap.dirs.Count.ToString(), root);
                            group.Add(img1);
                            group.Add(img2);
                            groups.Add(img1, group);
                            groups.Add(img2, group);
                            overlap.Add(group);
                            break;

                        default:
                            throw new System.InvalidProgramException();
                        }
                        //System.Console.WriteLine("次の画像は似ています\r\n    {0}\r\n    {1}",thm1.filepath,thm2.filepath);
                    }
                }
                if (i % 10 == 0)
                {
                    progress.Progress = i;
                }
            }
            progress.Close();

            this.root.dirs.Add(overlap);
        }
コード例 #23
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
  public static string GenerateTokenReplacing(string input){
    // token 登場回数を計数
    Gen::Dictionary<string,int> d_tok=new Gen::Dictionary<string,int>();
    foreach(Rgx::Match m in reg_tok.Matches(input)){
      string k=m.Value;
      if(d_tok.ContainsKey(k))
        d_tok[k]++;
      else
        d_tok[k]=1;
    }

    // 各 token に対するコード減少量の概算
    /*
    Gen::Dictionary<string,int> d_tok2=new Gen::Dictionary<string,int>();
    foreach(string k in d_tok.Keys){
      int iReduce=(k.Length-2)*d_tok[k];
      iReduce-=k.Length+3; // "hoge",
      d_tok2[k]=iReduce;
    }
    /*/
    Gen::Dictionary<string,int> d_tok2=d_tok;
    //*/

    // token に対する代替番号の割り当て
    System.Text.StringBuilder b_tok=new System.Text.StringBuilder();
    Gen::Dictionary<string,int> d_map=new Gen::Dictionary<string,int>();
    int n=0;
    foreach(string k in EnumFreqOrder(d_tok2)){
#if REPL_INTEG
      // k が \d+ か否か
      bool isnum=true;
      for(int i=0;i<k.Length;i++){
        if('0'<=k[i]&&k[i]<='9')continue;
        isnum=false;
        break;
      }

      // k が非整数なら枝刈り判定
      if(!isnum){
        if(d_tok[k]<=1)continue;

        // コード減少量を計算
        int iReduce=(k.Length-n.ToString().Length)*d_tok[k];
        iReduce-=k.Length+3;// "hoge",
        if(iReduce<=0)continue;
      }
#else
      // コード減少量を計算
      int iReduce=(k.Length-1-n.ToString().Length)*d_tok[k];
      iReduce-=k.Length+3;// "hoge",
      if(iReduce<=0)continue;
#endif

      d_map[k]=n;
      if(n++>0)b_tok.Append('|');
      b_tok.Append(k);
    }

    // token の置換
    string replaced=reg_tok.Replace(input,delegate(Rgx::Match m){
      string k=m.Value;
#if REPL_INTEG
      if(d_map.ContainsKey(k))
        return d_map[k].ToString();
#else
      if(d_map.ContainsKey(k))
        return "_"+d_map[k].ToString();
#endif
      return k;
    });

    // 変換結果
#if REPL_INTEG
    return @"(function(){
var r="+Stringize(b_tok.ToString())+@".split('|');
var s="+Stringize(replaced)+@";
eval(s.replace(/\b\d+\b/g,function($){return r[$];}));
})();";
#else
    return @"(function(){
var r="+b_tok.ToString()+@";
var s="+Stringize(replaced)+@";
eval(s.replace(/\b_(\d+)\b/g,function($0,$1){return r[$1];}));
})();";
#endif
  }
コード例 #24
0
        static Rational()
        {
            operateNaN      = new Gen::Dictionary <int, Signature>();
            operateNaN_bool = new Gen::Dictionary <int, bool>();

            //
            //		共通
            //

            //	※ 現状では any 及び impossible は出現し得ない

            /*
             * operateNaN_Register(0,Signature.Impossible,Signature.Impossible,		Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.Any,				Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.Indefinite,		Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.PositiveInfinity,	Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.NegativeInfinity,	Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.Positive,			Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.Negative,			Signature.Impossible);
             * operateNaN_Register(0,Signature.Impossible,Signature.Zero,				Signature.Impossible);
             * operateNaN_Register(0,Signature.Indefinite,Signature.Impossible,		Signature.Impossible);
             * operateNaN_Register(0,Signature.Any,Signature.Impossible,			Signature.Impossible);
             * operateNaN_Register(0,Signature.PositiveInfinity,Signature.Impossible,	Signature.Impossible);
             * operateNaN_Register(0,Signature.NegativeInfinity,Signature.Impossible,	Signature.Impossible);
             * operateNaN_Register(0,Signature.Positive,Signature.Impossible,			Signature.Impossible);
             * operateNaN_Register(0,Signature.Negative,Signature.Impossible,			Signature.Impossible);
             * operateNaN_Register(0,Signature.Zero,Signature.Impossible,				Signature.Impossible);
             * //*/

#if USE_ANY
            operateNaN_Register(0, Signature.Any, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.Indefinite, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.PositiveInfinity, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.NegativeInfinity, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.Zero, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.Positive, Signature.Any);
            operateNaN_Register(0, Signature.Any, Signature.Negative, Signature.Any);
            operateNaN_Register(0, Signature.Indefinite, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.PositiveInfinity, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.NegativeInfinity, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.Zero, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.Positive, Signature.Any, Signature.Any);
            operateNaN_Register(0, Signature.Negative, Signature.Any, Signature.Any);

            operateNaN_Register(0, Signature.Any, Signature.Any, false);
            operateNaN_Register(0, Signature.Any, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.Any, Signature.PositiveInfinity, false);
            operateNaN_Register(0, Signature.Any, Signature.NegativeInfinity, false);
            operateNaN_Register(0, Signature.Any, Signature.Zero, false);
            operateNaN_Register(0, Signature.Any, Signature.Positive, false);
            operateNaN_Register(0, Signature.Any, Signature.Negative, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.Any, false);
            operateNaN_Register(0, Signature.PositiveInfinity, Signature.Any, false);
            operateNaN_Register(0, Signature.NegativeInfinity, Signature.Any, false);
            operateNaN_Register(0, Signature.Zero, Signature.Any, false);
            operateNaN_Register(0, Signature.Positive, Signature.Any, false);
            operateNaN_Register(0, Signature.Negative, Signature.Any, false);
#endif

            operateNaN_Register(0, Signature.Indefinite, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.NegativeInfinity, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.PositiveInfinity, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.Zero, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.Positive, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.Negative, Signature.Indefinite);
            operateNaN_Register(0, Signature.NegativeInfinity, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.PositiveInfinity, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.Zero, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.Positive, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.Negative, Signature.Indefinite, Signature.Indefinite);
            operateNaN_Register(0, Signature.Indefinite, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.NegativeInfinity, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.PositiveInfinity, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.Zero, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.Positive, false);
            operateNaN_Register(0, Signature.Indefinite, Signature.Negative, false);
            operateNaN_Register(0, Signature.NegativeInfinity, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.PositiveInfinity, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.Zero, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.Positive, Signature.Indefinite, false);
            operateNaN_Register(0, Signature.Negative, Signature.Indefinite, false);

            //
            //		加算
            //
            operateNaN_Register(OP_ADD, Signature.NegativeInfinity, Signature.NegativeInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.NegativeInfinity, Signature.PositiveInfinity, Signature.Indefinite);
            operateNaN_Register(OP_ADD, Signature.NegativeInfinity, Signature.Zero, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.NegativeInfinity, Signature.Negative, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.NegativeInfinity, Signature.Positive, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.Zero, Signature.NegativeInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.Negative, Signature.NegativeInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_ADD, Signature.Positive, Signature.NegativeInfinity, Signature.NegativeInfinity);

            operateNaN_Register(OP_ADD, Signature.PositiveInfinity, Signature.NegativeInfinity, Signature.Indefinite);
            operateNaN_Register(OP_ADD, Signature.PositiveInfinity, Signature.PositiveInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.PositiveInfinity, Signature.Zero, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.PositiveInfinity, Signature.Negative, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.PositiveInfinity, Signature.Positive, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.Zero, Signature.PositiveInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.Negative, Signature.PositiveInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_ADD, Signature.Positive, Signature.PositiveInfinity, Signature.PositiveInfinity);

            //
            //		乗算
            //
            operateNaN_Register(OP_MUL, Signature.NegativeInfinity, Signature.NegativeInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_MUL, Signature.NegativeInfinity, Signature.PositiveInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_MUL, Signature.NegativeInfinity, Signature.Zero, Signature.Indefinite);
            operateNaN_Register(OP_MUL, Signature.NegativeInfinity, Signature.Negative, Signature.PositiveInfinity);
            operateNaN_Register(OP_MUL, Signature.NegativeInfinity, Signature.Positive, Signature.NegativeInfinity);
            operateNaN_Register(OP_MUL, Signature.Zero, Signature.NegativeInfinity, Signature.Indefinite);
            operateNaN_Register(OP_MUL, Signature.Negative, Signature.NegativeInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_MUL, Signature.Positive, Signature.NegativeInfinity, Signature.NegativeInfinity);

            operateNaN_Register(OP_MUL, Signature.PositiveInfinity, Signature.NegativeInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_MUL, Signature.PositiveInfinity, Signature.PositiveInfinity, Signature.PositiveInfinity);
            operateNaN_Register(OP_MUL, Signature.PositiveInfinity, Signature.Zero, Signature.Indefinite);
            operateNaN_Register(OP_MUL, Signature.PositiveInfinity, Signature.Negative, Signature.NegativeInfinity);
            operateNaN_Register(OP_MUL, Signature.PositiveInfinity, Signature.Positive, Signature.PositiveInfinity);
            operateNaN_Register(OP_MUL, Signature.Zero, Signature.PositiveInfinity, Signature.Indefinite);
            operateNaN_Register(OP_MUL, Signature.Negative, Signature.PositiveInfinity, Signature.NegativeInfinity);
            operateNaN_Register(OP_MUL, Signature.Positive, Signature.PositiveInfinity, Signature.PositiveInfinity);

            //
            //		大なり比較
            //
            operateNaN_Register(OP_GT, Signature.NegativeInfinity, Signature.NegativeInfinity, false);
            operateNaN_Register(OP_GT, Signature.NegativeInfinity, Signature.PositiveInfinity, false);
            operateNaN_Register(OP_GT, Signature.NegativeInfinity, Signature.Zero, false);
            operateNaN_Register(OP_GT, Signature.NegativeInfinity, Signature.Negative, false);
            operateNaN_Register(OP_GT, Signature.NegativeInfinity, Signature.Positive, false);
            operateNaN_Register(OP_GT, Signature.Zero, Signature.NegativeInfinity, true);
            operateNaN_Register(OP_GT, Signature.Negative, Signature.NegativeInfinity, true);
            operateNaN_Register(OP_GT, Signature.Positive, Signature.NegativeInfinity, true);

            operateNaN_Register(OP_GT, Signature.PositiveInfinity, Signature.NegativeInfinity, true);
            operateNaN_Register(OP_GT, Signature.PositiveInfinity, Signature.PositiveInfinity, false);
            operateNaN_Register(OP_GT, Signature.PositiveInfinity, Signature.Zero, true);
            operateNaN_Register(OP_GT, Signature.PositiveInfinity, Signature.Negative, true);
            operateNaN_Register(OP_GT, Signature.PositiveInfinity, Signature.Positive, true);
            operateNaN_Register(OP_GT, Signature.Zero, Signature.PositiveInfinity, false);
            operateNaN_Register(OP_GT, Signature.Negative, Signature.PositiveInfinity, false);
            operateNaN_Register(OP_GT, Signature.Positive, Signature.PositiveInfinity, false);

            /*
             * //
             * //		≧ 比較
             * //
             * operateNaN_Register(OP_GE,Signature.NegativeInfinity,Signature.NegativeInfinity,	true);
             * operateNaN_Register(OP_GE,Signature.NegativeInfinity,Signature.PositiveInfinity,	false);
             * operateNaN_Register(OP_GE,Signature.NegativeInfinity,Signature.Zero,				false);
             * operateNaN_Register(OP_GE,Signature.NegativeInfinity,Signature.Negative,			false);
             * operateNaN_Register(OP_GE,Signature.NegativeInfinity,Signature.Positive,			false);
             * operateNaN_Register(OP_GE,Signature.Zero,Signature.NegativeInfinity,				true);
             * operateNaN_Register(OP_GE,Signature.Negative,Signature.NegativeInfinity,			true);
             * operateNaN_Register(OP_GE,Signature.Positive,Signature.NegativeInfinity,			true);
             *
             * operateNaN_Register(OP_GE,Signature.PositiveInfinity,Signature.NegativeInfinity,	true);
             * operateNaN_Register(OP_GE,Signature.PositiveInfinity,Signature.PositiveInfinity,	true);
             * operateNaN_Register(OP_GE,Signature.PositiveInfinity,Signature.Zero,				false);
             * operateNaN_Register(OP_GE,Signature.PositiveInfinity,Signature.Negative,			false);
             * operateNaN_Register(OP_GE,Signature.PositiveInfinity,Signature.Positive,			false);
             * operateNaN_Register(OP_GE,Signature.Zero,Signature.PositiveInfinity,				true);
             * operateNaN_Register(OP_GE,Signature.Negative,Signature.PositiveInfinity,			true);
             * operateNaN_Register(OP_GE,Signature.Positive,Signature.PositiveInfinity,			true);
             */
        }
コード例 #25
0
        //============================================================
        //		コマンド \* の読み取り
        //============================================================
        private void readCommand(Gen::Dictionary <string, CommandData> commands)
        {
            __debug__.RegexParserToDo("複数文字名のコマンド");

            if (!this.lreader.MoveNext())
            {
                this.lreader.SetError((@"\ の後にコマンド名が続いていません。"), 0, null);
                wtype = WordType.Text;
                return;
            }
            this.cword += this.lreader.CurrentLetter; if (!this.lreader.MoveNext())
            {
                return;
            }

            CommandData dat;

            if (!commands.TryGetValue(cword, out dat))
            {
                this.lreader.SetError((@"指定した名前のコマンドは登録されていません。"), 0, null);
                wtype = WordType.Text;
                return;
            }

            if (dat.ArgumentType == CommandArgumentType.Brace)
            {
                if (!(this.lreader.CurrentLetter == '{'))
                {
                    value = null;
                }
                else
                {
                    string cmd = cword;
                    cword = "";
                    if (!this.lreader.MoveNext())
                    {
                        goto ERR_ARG;
                    }

                    int  iP     = 1;
                    bool escape = false;
                    while (true)
                    {
                        if (escape)
                        {
                            escape = false;
                        }
                        else
                        {
                            if ((this.lreader.CurrentLetter == '{'))
                            {
                                iP++;
                            }
                            else if ((this.lreader.CurrentLetter == '}'))
                            {
                                if (--iP == 0)
                                {
                                    lreader.MoveNext(); break;
                                }
                            }
                            else if ((this.lreader.CurrentLetter == '\\'))
                            {
                                escape = true;
                            }
                        }
                        this.cword += this.lreader.CurrentLetter; if (!this.lreader.MoveNext())
                        {
                            goto ERR_ARG;
                        }
                    }
                    value = cword;
                    cword = cmd;
                    return;

ERR_ARG:
                    value = cword;
                    cword = cmd;
                    this.lreader.SetError(("引数の終端が来ない内に、正規表現の末端に達しました。"), 0, null);
                }
            }
        }
コード例 #26
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
    public static string GenerateTokenReplacing(string input)
    {
        // token 登場回数を計数
        Gen::Dictionary <string, int> d_tok = new Gen::Dictionary <string, int>();

        foreach (Rgx::Match m in reg_tok.Matches(input))
        {
            string k = m.Value;
            if (d_tok.ContainsKey(k))
            {
                d_tok[k]++;
            }
            else
            {
                d_tok[k] = 1;
            }
        }

        // 各 token に対するコード減少量の概算

        /*
         * Gen::Dictionary<string, int> d_tok2 = new Gen::Dictionary<string, int>();
         * foreach (string k in d_tok.Keys) {
         * int iReduce = (k.Length - 2) * d_tok[k];
         * iReduce -= k.Length + 3; // "hoge",
         * d_tok2[k] = iReduce;
         * }
         * /*/
        Gen::Dictionary <string, int> d_tok2 = d_tok;

        //*/

        // token に対する代替番号の割り当て
        System.Text.StringBuilder     b_tok = new System.Text.StringBuilder();
        Gen::Dictionary <string, int> d_map = new Gen::Dictionary <string, int>();
        int n = 0;

        foreach (string k in EnumFreqOrder(d_tok2))
        {
#if REPL_INTEG
            // k が \d+ か否か
            bool isnum = true;
            for (int i = 0; i < k.Length; i++)
            {
                if ('0' <= k[i] && k[i] <= '9')
                {
                    continue;
                }
                isnum = false;
                break;
            }

            // k が非整数なら枝刈り判定
            if (!isnum)
            {
                if (d_tok[k] <= 1)
                {
                    continue;
                }

                // コード減少量を計算
                int iReduce = (k.Length - n.ToString().Length) * d_tok[k];
                iReduce -= k.Length + 3; // "hoge",
                if (iReduce <= 0)
                {
                    continue;
                }
            }
#else
            // コード減少量を計算
            int iReduce = (k.Length - 1 - n.ToString().Length) * d_tok[k];
            iReduce -= k.Length + 3; // "hoge",
            if (iReduce <= 0)
            {
                continue;
            }
#endif

            d_map[k] = n;
            if (n++ > 0)
            {
                b_tok.Append('|');
            }
            b_tok.Append(k);
        }

        // token の置換
        string replaced = reg_tok.Replace(input, delegate(Rgx::Match m) {
            string k = m.Value;
#if REPL_INTEG
            if (d_map.ContainsKey(k))
            {
                return(d_map[k].ToString());
            }
#else
            if (d_map.ContainsKey(k))
            {
                return("_" + d_map[k].ToString());
            }
#endif
            return(k);
        });

        // 変換結果
#if REPL_INTEG
        return(@"(function(){
var r=" + Stringize(b_tok.ToString()) + @".split('|');
var s=" + Stringize(replaced) + @";
eval(s.replace(/\b\d+\b/g,function($){return r[$];}));
})();");
#else
        return(@"(function(){
var r=" + b_tok.ToString() + @";
var s=" + Stringize(replaced) + @";
eval(s.replace(/\b_(\d+)\b/g,function($0,$1){return r[$1];}));
})();");
#endif
    }
コード例 #27
0
ファイル: HTMLParser.cs プロジェクト: akinomyoga/afh
        private static void initialize_judgeNest()
        {
            Gen::Dictionary <string, bool> listNoChild = new Gen::Dictionary <string, bool>();

            listNoChild.Add(JUDGENEST_LISTKEY_DEFAULT, false);
            foreach (string tagName in readElement_closedElem)
            {
                judgeNest_table.Add(tagName, listNoChild);
            }

            Gen::Dictionary <string, bool> listNoBlock = new Gen::Dictionary <string, bool>();

            listNoBlock.Add(JUDGENEST_LISTKEY_DEFAULT, true);
            foreach (string childTag in TAGS_BLOCKELEM)
            {
                listNoBlock.Add(childTag, false);
            }
            judgeNest_table.Add("p", listNoBlock);
            judgeNest_table.Add("h1", listNoBlock);
            judgeNest_table.Add("h2", listNoBlock);
            judgeNest_table.Add("h3", listNoBlock);
            judgeNest_table.Add("h4", listNoBlock);
            judgeNest_table.Add("h5", listNoBlock);
            judgeNest_table.Add("h6", listNoBlock);
            judgeNest_table.Add("address", listNoBlock);

            {
                Gen::Dictionary <string, bool> listLi = new Gen::Dictionary <string, bool>();
                listLi.Add(JUDGENEST_LISTKEY_DEFAULT, true);
                listLi.Add("li", false);
                judgeNest_table.Add("li", listLi);

                Gen::Dictionary <string, bool> listDt = new Gen::Dictionary <string, bool>(listNoBlock);
                listDt.Add("dt", false);
                listDt.Add("dd", false);
                judgeNest_table.Add("dt", listDt);

                Gen::Dictionary <string, bool> listDd = new Gen::Dictionary <string, bool>();
                listDd.Add(JUDGENEST_LISTKEY_DEFAULT, true);
                listDd.Add("dt", false);
                listDd.Add("dd", false);
                judgeNest_table.Add("dd", listDd);
            }

            {
                Gen::Dictionary <string, bool> listTablePart = new Gen::Dictionary <string, bool>();
                listTablePart.Add(JUDGENEST_LISTKEY_DEFAULT, true);
                listTablePart.Add("thead", false);
                listTablePart.Add("tbody", false);
                listTablePart.Add("tfoot", false);
                judgeNest_table.Add("thead", listTablePart);
                judgeNest_table.Add("tbody", listTablePart);
                judgeNest_table.Add("tfoot", listTablePart);

                Gen::Dictionary <string, bool> listTableRow = new Gen::Dictionary <string, bool>(listTablePart);
                listTableRow.Add("tr", false);
                judgeNest_table.Add("tr", listTableRow);
                judgeNest_table.Add("caption", listTableRow);

                Gen::Dictionary <string, bool> listTableCell = new Gen::Dictionary <string, bool>(listTableRow);
                listTableCell.Add("th", false);
                listTableCell.Add("td", false);
                judgeNest_table.Add("th", listTableCell);
                judgeNest_table.Add("td", listTableCell);
            }

            {
                Gen::Dictionary <string, bool> list = new Gen::Dictionary <string, bool>(listNoBlock);
                list.Add("rb", false);
                list.Add("rt", false);
                list.Add("rp", false);
                judgeNest_table.Add("rb", list);
                judgeNest_table.Add("rt", list);
                judgeNest_table.Add("rp", list);
            }
        }
コード例 #28
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
  public static string ProcessSource(string input,Argument _args){
    string output=input;
    Argument args=_args;
    string dirname=System.IO.Path.GetDirectoryName(args.OutputFile);

    // directives の読み取り
    Gen::Dictionary<string,string> tokenmap=new Gen::Dictionary<string,string>();
    Gen::List<ReplaceData> replaces=new Gen::List<ReplaceData>();

    output=reg_gzjs_directive.Replace(output,delegate(Rgx::Match m){
      // 先頭以外に改行が入っている物は無効
      if(0<m.Value.IndexOfAny("\r\n".ToCharArray()))return m.Value;
      
      switch(m.Groups["dir"].Value){
      case "outfile":
        args.OutputFile=System.IO.Path.Combine(
          System.IO.Path.GetDirectoryName(args.OutputFile),
          ReadArg(m.Groups["arg1"])
        );
        if(args.Verbose)
          args.WriteLine("#> output-file was set to '"+args.OutputFile+"'");
        return "\n";
      case "tokenmap":{
        string before=ReadArg(m.Groups["arg1"]);
        string after=ReadArg(m.Groups["arg2"]);
        tokenmap[before]=after;
        if(args.Verbose)
          args.WriteLine("#> token-mapping registered: "+before+" -> "+after+"");
        return "\n";
      }
      case "replace":{
        string before=ReadArg(m.Groups["arg1"]);
        string after=ReadArg(m.Groups["arg2"]);
        replaces.Add(new ReplaceData(before,after));
        if(args.Verbose)
          args.WriteLine("#> replace registered: "+before+" -> "+after+"");
        return "\n";
      }
      case "include":{
        if(args.Verbose)
          args.WriteLine("#gzjs-include");
        return Program.Include(ReadArg(m.Groups["arg1"]),args)??m.Value;
      }
      case "option":{
        string op=ReadArg(m.Groups["arg1"]);
        if(!args.ReadOption(op)){
          args.WriteLine("#gzjs-option > '{0}' は認識できない option です",op);
          return m.Value;
        }
        return "\n";
      }
      default:
        return m.Value;
      }
    });

    // コメント空白類の削除
    if(args.CutComment)
      output=RegExp.CutComment(output);

    // token 置き換え
    if(tokenmap.Count>0){
      string rex=null;
      foreach(string token in tokenmap.Keys){
        if(rex==null)rex=token;else rex+="|"+token;
      }
      rex=@"\b(?:"+rex+@")\b";
      output=new Rgx::Regex(rex).Replace(output,delegate(Rgx::Match m){
        return tokenmap[m.Value];
      });
    }

    // #gzjs-replace 実行
    foreach(ReplaceData r in replaces)
      output=r.Replace(output);

    return output;
  }
コード例 #29
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
  public static string GenerateTokenReplacing2(string input,Argument args){
    // 1 各単語の登場数を数える
    //
    Gen::Dictionary<string,int> hist=new Gen::Dictionary<string,int>();
    foreach(Rgx::Match m in reg_tok.Matches(input)){
      string word=m.Value;
      if(hist.ContainsKey(word))
        hist[word]++;
      else
        hist[word]=1;
    }

    // 2 単語の "重み" を計算する
    //
    //   ※優先順位は頻度だけで決まる (共に置換すると決まっている場合)
    //
    //     ∵トークン A, B のどちらを 1文字/2文字で表現するか決める場合は、
    //       「1文字の場合の gain がより多い方を選ぶ」のではなく合計の gain で判断すべき。
    //       A, B をそれぞれ a, b と符号化する時、合計の gain は
    //         (len(A)-len(a))count(A)+(len(B)-len(b))count(B)-(len(A)+1+len(B)+1)
    //         = const - len(a)count(A) - len(b)count(B)
    //       これを最大化する為には count() の大きいトークンに小さい符号を割り当てれば良い。
    //       重要なのは各トークン自体の長さには依存しないという事である■
    //
    //   ※或るトークン A が数字 N をおしのけてまで符号化するべきかどうかも頻度で決まる
    //
    //     - もし数字Nも置換対象になっている場合は大体 count(A)-count(N) の gain がある。
    //       (もしトークン A を1文字長い別の符号で表すと count(A) のロスがある。
    //       一方で数字 N を1文字長い別の符号で表すと count(N) のロスがある。
    //       実際には1文字長いだけの符号で表す事ができるかどうかは分からないが。)
    //     - 加えて数字Nをおしのける事によって数字Nを表に登録する必要が出るので
    //       len(N) のロスがある。更に、数字Nの符号 n が最大の符号だとすると区切り文字
    //       として 1 以上のロスが生じる。つまり、符号表が
    //         ....|foo → ....|foo||||||n
    //       等の様に変化するという事である。近似的に常に 1 文字のロスがあるという事にする。
    //     →結局近似的に count(A) - (count(N)+len(N)+1) の gain と考える事にする。
    //       つまり、数字の重みは count(N)+len(N)+1 という事である。
    //
    int wordCount=hist.Count;
    string[] tokens =new string[wordCount];
    int   [] weights=new int   [wordCount];
    int j=0;
    foreach(string cand in hist.Keys){
      tokens [j]=cand;
      weights[j]=hist[cand];

      int icand;
      if(int.TryParse(cand,out icand)&&icand.ToString()==cand)
        weights[j]+=cand.ToString().Length+1;

      j++;
    }
    System.Array.Sort(weights,tokens);

    // 3 重みの高い符号から順番に符号を割り当てる
    //   - 符号は短い物から順に割り当てる
    //   - 整数は無条件で符号化対象として考慮する
    //   - その他の単語は gain > loss の時に考慮する:
    //     "次に短い符号の長さ" を用いて、
    //     その単語の gain, loss を計算する。
    //
    string[] mapCodeToWord=new string[wordCount];

    // 新しいコードの割当先、かつ、有意な符号の終端を表す。
    // 有意な符号とは "自分自身から map される符号" ではないという事。
    int code=0;

    // 有意かどうかに拘わらず登録されている符号の数
    int codeCount=0; // code Count

    // 現在割り当てられている符号の長さ
    // 及び、その長さの符号の範囲
    int ndigit=0,code0=-1,codeM=0;

    int effectiveWordCount=wordCount;

    for(int index=wordCount;--index>=0;){
      string cand=tokens[index];

      if(codeCount>=codeM){
        ndigit++;
        code0=codeM;
        codeM=(int)System.Math.Pow(10,ndigit);
      }

      int icand;
      bool isInt=int.TryParse(cand,out icand)&&icand.ToString()==cand;
      if(!isInt||icand>=effectiveWordCount){
        // gain, loss を計算し割に合わないなら跳ばす
        // 小さい整数(<effectiveWordCount)は別の単語に上書きされる危険があるので跳ばせない
        int loss=cand.Length+1;
        int gain=(cand.Length-ndigit)*hist[cand];
        if(gain<=loss){
          effectiveWordCount--;
          continue;
        }
      }

      if(isInt&&code0<=icand&&icand<codeM){
        // 不変な整数値の場合
        //   整数値で符号と自身の長さが同じ場合は符号表に登録する必要はない
        //   自分自身に対して mapping すれば良い。
        
        if(icand<code){
          // 自分自身の番号に既に別の単語が割り当てられている場合は待避
          mapCodeToWord[code++]=mapCodeToWord[icand];
        }

        if(icand<wordCount)
          mapCodeToWord[icand]="";
      }else{
        // 普通の単語の場合
        //   登録する。既に不変の整数値として決まっている番号は跳ばす。
        while(mapCodeToWord[code]!=null)code++;
        mapCodeToWord[code++]=cand;
      }

      codeCount++;
    }

    // 4 置換の実行
    if(code==0)return input;

    Gen::Dictionary<string,string> mapWordToCode=new Gen::Dictionary<string,string>();
    System.Text.StringBuilder table=new System.Text.StringBuilder();
    for(int c=0;c<code;c++){
      string word=mapCodeToWord[c];
      if(word!="")
        mapWordToCode[word]=c.ToString();

      if(c>0)table.Append(':');
      table.Append(word);

      // System.Console.WriteLine(
      //   "dbg: {0} -> {1} {2}",word,c,hist.ContainsKey(c.ToString())?"collide":"");
    }

    string replaced=reg_tok.Replace(input,delegate(Rgx::Match m){
      string word=m.Value;
      if(mapWordToCode.ContainsKey(word))
        return mapWordToCode[word];
      else
        return word;
    });

    string strTable;
    string strSource;
    if(args.FlagFoldString){
      strTable=Stringize(table.ToString());
      strSource=Stringize(replaced);
    }else{
      strTable="'"+RegExp.EscapeSingleQuote(table.ToString())+"'";
      strSource="'"+RegExp.EscapeSingleQuote(replaced)+"'";
    }

//     string ret=@"(function(){
// var r="+strTable+@".split("":"");
// var s="+strSource+@";
// eval(s.replace(/\b\d+\b/g,function($){return r[$]||$;}));
// })();";

    string ret=@"(function(r){
r="+strTable+@".split("":"");
eval("+strSource+@".replace(/\b\d+\b/g,function($){return r[$]||$;}));
})();";

    if(!args.FlagFoldString)
      ret=RegExp.RemoveLineBreaks(ret);

    return ret.Length<input.Length?ret:input;
  }
コード例 #30
0
ファイル: Selector.cs プロジェクト: akinomyoga/afh
 /// <summary>
 /// 値読込命令を含む際に値をスタックに返す形式の判断メソッドです。
 /// 通常ではこのメソッドは Test(HTMLElement) をそのまま呼び出すだけです。
 /// </summary>
 /// <param name="elem">適合するかどうかを確かめる要素を指定します。</param>
 /// <param name="dict">値を設定する先の辞書を指定します。</param>
 /// <returns>適合した場合に true を返します。</returns>
 public virtual bool Test(HTMLElement elem, Gen::Dictionary <string, string> dict)
 {
     return(Test(elem));
 }
コード例 #31
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
    public static string GenerateTokenReplacing2(string input, Argument args)
    {
        // 1 各単語の登場数を数える
        //
        Gen::Dictionary <string, int> hist = new Gen::Dictionary <string, int>();

        foreach (Rgx::Match m in reg_tok.Matches(input))
        {
            string word = m.Value;
            if (hist.ContainsKey(word))
            {
                hist[word]++;
            }
            else
            {
                hist[word] = 1;
            }
        }

        // 2 単語の "重み" を計算する
        //
        //   ※優先順位は頻度だけで決まる (共に置換すると決まっている場合)
        //
        //     ∵トークン A, B のどちらを 1文字/2文字で表現するか決める場合は、
        //       「1文字の場合の gain がより多い方を選ぶ」のではなく合計の gain で判断すべき。
        //       A, B をそれぞれ a, b と符号化する時、合計の gain は
        //         (len(A)-len(a))count(A)+(len(B)-len(b))count(B)-(len(A)+1+len(B)+1)
        //         = const - len(a)count(A) - len(b)count(B)
        //       これを最大化する為には count() の大きいトークンに小さい符号を割り当てれば良い。
        //       重要なのは各トークン自体の長さには依存しないという事である■
        //
        //   ※或るトークン A が数字 N をおしのけてまで符号化するべきかどうかも頻度で決まる
        //
        //     - もし数字Nも置換対象になっている場合は大体 count(A)-count(N) の gain がある。
        //       (もしトークン A を1文字長い別の符号で表すと count(A) のロスがある。
        //       一方で数字 N を1文字長い別の符号で表すと count(N) のロスがある。
        //       実際には1文字長いだけの符号で表す事ができるかどうかは分からないが。)
        //     - 加えて数字Nをおしのける事によって数字Nを表に登録する必要が出るので
        //       len(N) のロスがある。更に、数字Nの符号 n が最大の符号だとすると区切り文字
        //       として 1 以上のロスが生じる。つまり、符号表が
        //         ....|foo → ....|foo||||||n
        //       等の様に変化するという事である。近似的に常に 1 文字のロスがあるという事にする。
        //     →結局近似的に count(A) - (count(N)+len(N)+1) の gain と考える事にする。
        //       つまり、数字の重みは count(N)+len(N)+1 という事である。
        //
        int wordCount = hist.Count;

        string[] tokens  = new string[wordCount];
        int   [] weights = new int   [wordCount];
        int      j       = 0;

        foreach (string cand in hist.Keys)
        {
            tokens [j] = cand;
            weights[j] = hist[cand];

            int icand;
            if (int.TryParse(cand, out icand) && icand.ToString() == cand)
            {
                weights[j] += cand.ToString().Length + 1;
            }

            j++;
        }
        System.Array.Sort(weights, tokens);

        // 3 重みの高い符号から順番に符号を割り当てる
        //   - 符号は短い物から順に割り当てる
        //   - 整数は無条件で符号化対象として考慮する
        //   - その他の単語は gain > loss の時に考慮する:
        //     "次に短い符号の長さ" を用いて、
        //     その単語の gain, loss を計算する。
        //
        string[] mapCodeToWord = new string[wordCount];

        // 新しいコードの割当先、かつ、有意な符号の終端を表す。
        // 有意な符号とは "自分自身から map される符号" ではないという事。
        int code = 0;

        // 有意かどうかに拘わらず登録されている符号の数
        int codeCount = 0; // code Count

        // 現在割り当てられている符号の長さ
        // 及び、その長さの符号の範囲
        int ndigit = 0, code0 = -1, codeM = 0;

        int effectiveWordCount = wordCount;

        for (int index = wordCount; --index >= 0;)
        {
            string cand = tokens[index];

            if (codeCount >= codeM)
            {
                ndigit++;
                code0 = codeM;
                codeM = (int)System.Math.Pow(10, ndigit);
            }

            int  icand;
            bool isInt = int.TryParse(cand, out icand) && icand.ToString() == cand;
            if (!isInt || icand >= effectiveWordCount)
            {
                // gain, loss を計算し割に合わないなら跳ばす
                // 小さい整数(<effectiveWordCount)は別の単語に上書きされる危険があるので跳ばせない
                int loss = cand.Length + 1;
                int gain = (cand.Length - ndigit) * hist[cand];
                if (gain <= loss)
                {
                    effectiveWordCount--;
                    continue;
                }
            }

            if (isInt && code0 <= icand && icand < codeM)
            {
                // 不変な整数値の場合
                //   整数値で符号と自身の長さが同じ場合は符号表に登録する必要はない
                //   自分自身に対して mapping すれば良い。

                if (icand < code)
                {
                    // 自分自身の番号に既に別の単語が割り当てられている場合は待避
                    mapCodeToWord[code++] = mapCodeToWord[icand];
                }

                if (icand < wordCount)
                {
                    mapCodeToWord[icand] = "";
                }
            }
            else
            {
                // 普通の単語の場合
                //   登録する。既に不変の整数値として決まっている番号は跳ばす。
                while (mapCodeToWord[code] != null)
                {
                    code++;
                }
                mapCodeToWord[code++] = cand;
            }

            codeCount++;
        }

        // 4 置換の実行
        if (code == 0)
        {
            return(input);
        }

        Gen::Dictionary <string, string> mapWordToCode = new Gen::Dictionary <string, string>();

        System.Text.StringBuilder table = new System.Text.StringBuilder();
        for (int c = 0; c < code; c++)
        {
            string word = mapCodeToWord[c];
            if (word != "")
            {
                mapWordToCode[word] = c.ToString();
            }

            if (c > 0)
            {
                table.Append(':');
            }
            table.Append(word);

            // System.Console.WriteLine(
            //   "dbg: {0} -> {1} {2}", word, c, hist.ContainsKey(c.ToString()) ? "collide" : "");
        }

        string replaced = reg_tok.Replace(input, delegate(Rgx::Match m) {
            string word = m.Value;
            if (mapWordToCode.ContainsKey(word))
            {
                return(mapWordToCode[word]);
            }
            else
            {
                return(word);
            }
        });

        string strTable;
        string strSource;

        if (args.FlagFoldString)
        {
            strTable  = Stringize(table.ToString());
            strSource = Stringize(replaced);
        }
        else
        {
            strTable  = "'" + RegExp.EscapeSingleQuote(table.ToString()) + "'";
            strSource = "'" + RegExp.EscapeSingleQuote(replaced) + "'";
        }

//     string ret = @"(function(){
// var r = " + strTable + @".split("":"");
// var s = " + strSource + @";
// eval(s.replace(/\b\d+\b/g,function($){return r[$]||$;}));
// })();";

        string ret = @"(function(r){
r=" + strTable + @".split("":"");
eval(" + strSource + @".replace(/\b\d+\b/g,function($){return r[$]||$;}));
})();";

        if (!args.FlagFoldString)
        {
            ret = RegExp.RemoveLineBreaks(ret);
        }

        return(ret.Length < input.Length ? ret : input);
    }
コード例 #32
0
 public FsDirectory(string name) : base(name)
 {
     this.files            = new Gen::Dictionary <string, FsNode>();
     this.info.Attributes |= System.IO.FileAttributes.Directory;
     this.info.Length      = 0;
 }
コード例 #33
0
ファイル: gzjs.cs プロジェクト: akinomyoga/agh
    public static string ProcessSource(string input, Argument _args)
    {
        string   output = input;
        Argument args   = _args;

        // directives の読み取り
        Gen::Dictionary <string, string> tokenmap = new Gen::Dictionary <string, string>();
        Gen::List <ReplaceData>          replaces = new Gen::List <ReplaceData>();

        output = reg_gzjs_directive.Replace(output, delegate(Rgx::Match m) {
            // 先頭以外に改行が入っている物は無効
            if (0 < m.Value.IndexOfAny("\r\n".ToCharArray()))
            {
                return(m.Value);
            }

            switch (m.Groups["dir"].Value)
            {
            case "outfile": {
                string dirname  = System.IO.Path.GetDirectoryName(args.OutputFile);
                args.OutputFile = System.IO.Path.Combine(dirname, ReadArg(m.Groups["arg1"]));
                if (args.Verbose)
                {
                    args.WriteLine("#> output-file was set to '" + args.OutputFile + "'");
                }
                return("\n");
            }

            case "tokenmap": {
                string before    = ReadArg(m.Groups["arg1"]);
                string after     = ReadArg(m.Groups["arg2"]);
                tokenmap[before] = after;
                if (args.Verbose)
                {
                    args.WriteLine("#> token-mapping registered: " + before + " -> " + after + "");
                }
                return("\n");
            }

            case "replace": {
                string before = ReadArg(m.Groups["arg1"]);
                string after  = ReadArg(m.Groups["arg2"]);
                replaces.Add(new ReplaceData(before, after));
                if (args.Verbose)
                {
                    args.WriteLine("#> replace registered: " + before + " -> " + after + "");
                }
                return("\n");
            }

            case "include": {
                if (args.Verbose)
                {
                    args.WriteLine("#gzjs-include");
                }
                return(Program.Include(ReadArg(m.Groups["arg1"]), args) ?? m.Value);
            }

            case "option": {
                string op = ReadArg(m.Groups["arg1"]);
                if (!args.ReadOption(op))
                {
                    args.WriteLine("#gzjs-option > '{0}' は認識できない option です", op);
                    return(m.Value);
                }
                return("\n");
            }

            default:
                return(m.Value);
            }
        });

        // コメント空白類の削除
        if (args.CutComment)
        {
            output = RegExp.CutComment(output);
        }

        // token 置き換え
        if (tokenmap.Count > 0)
        {
            string rex = null;
            foreach (string token in tokenmap.Keys)
            {
                if (rex == null)
                {
                    rex = token;
                }
                else
                {
                    rex += "|" + token;
                }
            }
            rex    = @"\b(?:" + rex + @")\b";
            output = new Rgx::Regex(rex).Replace(output, delegate(Rgx::Match m) {
                return(tokenmap[m.Value]);
            });
        }

        // #gzjs-replace 実行
        foreach (ReplaceData r in replaces)
        {
            output = r.Replace(output);
        }

        return(output);
    }