LexicalAnalyzer.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using NTERA.EmuEra.Game.EraEmu.Config;
  7. using NTERA.EmuEra.Game.EraEmu.GameData;
  8. using NTERA.EmuEra.Game.EraEmu.GameData.Expression;
  9. namespace NTERA.EmuEra.Game.EraEmu.Sub
  10. {
  11. enum LexEndWith
  12. {
  13. //いずれにせよEoLで強制終了
  14. None = 0,
  15. EoL,//常に最後まで解析
  16. Operator,//演算子を見つけたら終了。代入式の左辺
  17. Question,//三項演算子?により終了。\@~~?~~#~~\@
  18. Percent,//%により終了。%~~%
  19. RightCurlyBrace,//}により終了。{~~}
  20. Comma,//,により終了。TIMES第一引数
  21. //Single,//Identifier一つで終了//1807 Single削除
  22. GreaterThan//'>'により終了。Htmlタグ解析
  23. }
  24. enum FormStrEndWith
  25. {
  26. //いずれにせよEoLで強制終了
  27. None = 0,
  28. EoL,//常に最後まで解析
  29. DoubleQuotation,//"で終了。@"~~"
  30. Sharp,//#で終了。\@~~?~~#~~\@ の一つ目
  31. YenAt,//\@で終了。\@~~?~~#~~\@ の二つ目
  32. Comma,//,により終了。ANY_FORM引数
  33. LeftParenthesis_Bracket_Comma_Semicolon//[または(または,または;により終了。CALLFORM系の関数名部分。
  34. }
  35. enum StrEndWith
  36. {
  37. //いずれにせよEoLで強制終了
  38. None = 0,
  39. EoL,//常に最後まで解析
  40. SingleQuotation,//"で終了。'~~'
  41. DoubleQuotation,//"で終了。"~~"
  42. Comma,//,により終了。PRINTV'~~,
  43. LeftParenthesis_Bracket_Comma_Semicolon//[または(または,または;により終了。関数名部分。
  44. }
  45. enum LexAnalyzeFlag
  46. {
  47. None = 0,
  48. AnalyzePrintV = 1,
  49. AllowAssignment = 2,
  50. AllowSingleQuotationStr = 4
  51. }
  52. /// <summary>
  53. /// 1756 TokenReaderより改名
  54. /// Lexicalといいつつ構文解析を含む
  55. /// </summary>
  56. internal static class LexicalAnalyzer
  57. {
  58. const int MAX_EXPAND_MACRO = 100;
  59. //readonly static IList<char> operators = new char[] { '+', '-', '*', '/', '%', '=', '!', '<', '>', '|', '&', '^', '~', '?', '#' };
  60. //readonly static IList<char> whiteSpaces = new char[] { ' ', ' ', '\t' };
  61. //readonly static IList<char> endOfExpression = new char[] { ')', '}', ']', ',', ':' };
  62. //readonly static IList<char> startOfExpression = new char[] { '(' };
  63. //readonly static IList<char> stringToken = new char[] { '\"', };
  64. //readonly static IList<char> stringFormToken = new char[] { '@', };
  65. //readonly static IList<char> etcSymbol = new char[] { '[', '{', '$', '\\', };
  66. //readonly static IList<char> decimalDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
  67. static readonly IList<char> hexadecimalDigits = new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' };
  68. //1819 正規表現使うとやや遅い。いずれdoubleにも対応させたい。そのうち考える
  69. //readonly static Regex DigitsReg = new Regex("" +
  70. // "(" +
  71. // "((?<simple>[-]?[0-9]+)([^.xXbBeEpP]|$))" +
  72. // "|(" +
  73. // "(0(x|X)(?<hex>[0-9a-fA-F]+))|"+
  74. // "(0(b|B)(?<bin>[01]+))|"+
  75. // "(" + //base10
  76. // "(?<integer>[-]?[0-9]*(?<double>[.][0-9])?)" +
  77. // "(((p|P)(?<exp2>[0-9]+))|" +
  78. // "((e|E)(?<exp10>[0-9]+)))?" +
  79. // ")"+
  80. // "))"
  81. // , RegexOptions.Compiled);
  82. //readonly static Regex idReg = new Regex(@"[^][ \t+*/%=!<>|&^~?#(){},:$\\'""@.; -]+", RegexOptions.Compiled);
  83. //public static Int64 ReadInt64(StringStream st, bool retZero)
  84. //{
  85. // Match m = DigitsReg.Match(st.RowString, st.CurrentPosition);
  86. // string numstr = m.Groups["simple"].Value;
  87. // if (numstr.Length > 0)
  88. // {
  89. // st.Jump(numstr.Length);
  90. // return Convert.ToInt64(numstr, 10);
  91. // }
  92. // st.Jump(m.Length);
  93. // if (m.Groups["bin"].Length > 0)
  94. // return Convert.ToInt64(m.Groups["bin"].Value, 2);
  95. // if(m.Groups["hex"].Length > 0)
  96. // return Convert.ToInt64(m.Groups["hex"].Value, 16);
  97. // numstr = m.Groups["number"].Value;
  98. // if (numstr.Length > 0)
  99. // {
  100. // int exp = 0;
  101. // string exp2 = m.Groups["exp2"].Value;
  102. // string exp10 = m.Groups["exp10"].Value;
  103. // if(m.Groups["double"].Length == 0 && exp2.Length == 0 && exp10.Length == 0)
  104. // {
  105. // return Convert.ToInt64(numstr,10);
  106. // }
  107. // double d = Convert.ToDouble(numstr);
  108. // if (exp2.Length > 0)
  109. // {
  110. // exp = Convert.ToInt32(exp2, 10);
  111. // d = d * Math.Pow(2, exp);
  112. // }
  113. // else if (exp10.Length > 0)
  114. // {
  115. // exp = Convert.ToInt32(exp10, 10);
  116. // d = d * Math.Pow(10, exp);
  117. // }
  118. // return ((Int64)(d + 0.49));
  119. // }
  120. // throw new CodeEE("数字で始まるトークンが適切でありません");
  121. //}
  122. public static bool UseMacro = true;
  123. #region read
  124. public static Int64 ReadInt64(StringStream st, bool retZero)
  125. {
  126. Int64 significand = 0;
  127. int expBase = 0;
  128. int exponent = 0;
  129. int stStartPos = st.CurrentPosition;
  130. int stEndPos = st.CurrentPosition;
  131. int fromBase = 10;
  132. if (st.Current == '0')
  133. {
  134. char c = st.Next;
  135. if ((c == 'x') || (c == 'X'))
  136. {
  137. fromBase = 16;
  138. st.ShiftNext();
  139. st.ShiftNext();
  140. }
  141. else if ((c == 'b') || (c == 'B'))
  142. {
  143. fromBase = 2;
  144. st.ShiftNext();
  145. st.ShiftNext();
  146. }
  147. //8進法は互換性の問題から採用しない。
  148. //else if (dchar.IsDigit(c))
  149. //{
  150. // fromBase = 8;
  151. // st.ShiftNext();
  152. //}
  153. }
  154. if (retZero && st.Current != '+' && st.Current != '-' && !char.IsDigit(st.Current))
  155. {
  156. if (fromBase != 16)
  157. return 0;
  158. if (!hexadecimalDigits.Contains(st.Current))
  159. return 0;
  160. }
  161. significand = readDigits(st, fromBase);
  162. if ((st.Current == 'p') || (st.Current == 'P'))
  163. expBase = 2;
  164. else if ((st.Current == 'e') || (st.Current == 'E'))
  165. expBase = 10;
  166. if (expBase != 0)
  167. {
  168. st.ShiftNext();
  169. unchecked { exponent = (int)readDigits(st, fromBase); }
  170. }
  171. stEndPos = st.CurrentPosition;
  172. if ((expBase != 0) && (exponent != 0))
  173. {
  174. double d = significand * Math.Pow(expBase, exponent);
  175. if ((double.IsNaN(d)) || (double.IsInfinity(d)) || (d > Int64.MaxValue) || (d < Int64.MinValue))
  176. throw new CodeEE("\"" + st.Substring(stStartPos, stEndPos) + "\"は64ビット符号付整数の範囲を超えています");
  177. significand = (Int64)d;
  178. }
  179. return significand;
  180. }
  181. //static Regex reg = new Regex(@"[0-9A-Fa-f]+", RegexOptions.Compiled);
  182. private static Int64 readDigits(StringStream st, int fromBase)
  183. {
  184. int start = st.CurrentPosition;
  185. //1756 正規表現を使ってみたがほぼ変わらなかったので没
  186. //Match m = reg.Match(st.RowString, st.CurrentPosition);
  187. //st.Jump(m.Length);
  188. char c = st.Current;
  189. if ((c == '-') || (c == '+'))
  190. {
  191. st.ShiftNext();
  192. }
  193. if (fromBase == 10)
  194. {
  195. while (!st.EOS)
  196. {
  197. c = st.Current;
  198. if (char.IsDigit(c))
  199. {
  200. st.ShiftNext();
  201. continue;
  202. }
  203. break;
  204. }
  205. }
  206. else if (fromBase == 16)
  207. {
  208. while (!st.EOS)
  209. {
  210. c = st.Current;
  211. if (char.IsDigit(c) || hexadecimalDigits.Contains(c))
  212. {
  213. st.ShiftNext();
  214. continue;
  215. }
  216. break;
  217. }
  218. }
  219. else if (fromBase == 2)
  220. {
  221. while (!st.EOS)
  222. {
  223. c = st.Current;
  224. if (char.IsDigit(c))
  225. {
  226. if ((c != '0') && (c != '1'))
  227. throw new CodeEE("二進法表記の中で使用できない文字が使われています");
  228. st.ShiftNext();
  229. continue;
  230. }
  231. break;
  232. }
  233. }
  234. string strInt = st.Substring(start, st.CurrentPosition - start);
  235. try
  236. {
  237. return Convert.ToInt64(strInt, fromBase);
  238. }
  239. catch (FormatException)
  240. {
  241. throw new CodeEE("\"" + strInt + "\"は整数値に変換できません");
  242. }
  243. catch (OverflowException)
  244. {
  245. throw new CodeEE("\"" + strInt + "\"は64ビット符号付き整数の範囲を超えています");
  246. }
  247. catch (ArgumentOutOfRangeException)
  248. {
  249. if (string.IsNullOrEmpty(strInt))
  250. throw new CodeEE("数値として認識できる文字が必要です");
  251. throw new CodeEE("文字列\"" + strInt + "\"は数値として認識できません");
  252. }
  253. }
  254. /// <summary>
  255. /// TIMES第二引数のみが使用する。
  256. /// Convertクラスが発行する例外をそのまま投げるので適切に処理すること。
  257. /// </summary>
  258. /// <param name="st"></param>
  259. /// <returns></returns>
  260. public static double ReadDouble(StringStream st)
  261. {
  262. int start = st.CurrentPosition;
  263. //大雑把に読み込んでエラー処理はConvertクラスに任せる。
  264. //仮数小数部
  265. if ((st.Current == '-') || (st.Current == '+'))
  266. {
  267. st.ShiftNext();
  268. }
  269. while (!st.EOS)
  270. {//仮数部
  271. char c = st.Current;
  272. if (char.IsDigit(c) || (c == '.'))
  273. {
  274. if ((c == '.') && (Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator == ","))
  275. st.Replace(st.CurrentPosition, 1, ",");
  276. st.ShiftNext();
  277. continue;
  278. }
  279. break;
  280. }
  281. if ((st.Current == 'e') || (st.Current == 'E'))
  282. {
  283. st.ShiftNext();
  284. if (st.Current == '-')
  285. {
  286. st.ShiftNext();
  287. }
  288. while (!st.EOS)
  289. {//指数部
  290. char c = st.Current;
  291. if (char.IsDigit(c) || (c == '.'))
  292. {
  293. st.ShiftNext();
  294. continue;
  295. }
  296. break;
  297. }
  298. }
  299. return Convert.ToDouble(st.Substring(start, st.CurrentPosition - start));
  300. }
  301. /// <summary>
  302. /// 行頭の単語の取得。マクロ展開あり。ただし単語でないマクロ展開はしない。
  303. /// </summary>
  304. /// <param name="st"></param>
  305. /// <returns></returns>
  306. public static IdentifierWord ReadFirstIdentifierWord(StringStream st)
  307. {
  308. int startpos = st.CurrentPosition;
  309. string str = ReadSingleIdentifier(st);
  310. if (string.IsNullOrEmpty(str))
  311. throw new CodeEE("不正な文字で行が始まっています");
  312. //1808a3 先頭1単語の展開をやめる。-命令の置換を禁止。
  313. //if (UseMacro)
  314. //{
  315. // int i = 0;
  316. // while (true)
  317. // {
  318. // DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(str);
  319. // i++;
  320. // if (i > MAX_EXPAND_MACRO)
  321. // throw new CodeEE("マクロの展開数が1文あたりの上限を超えました(自己参照・循環参照のおそれ)");
  322. // if (macro == null)
  323. // break;
  324. // //単語(識別子一個)でないマクロが出現したらここでは処理しない
  325. // if (macro.IDWord == null)
  326. // {
  327. // st.CurrentPosition = startpos;
  328. // return null;//変数処理に任せる。
  329. // }
  330. // str = macro.IDWord.Code;
  331. // }
  332. //}
  333. return new IdentifierWord(str);
  334. }
  335. /// <summary>
  336. /// 単語の取得。マクロ展開あり。関数型マクロ展開なし
  337. /// </summary>
  338. /// <param name="st"></param>
  339. /// <returns></returns>
  340. public static IdentifierWord ReadSingleIdentifierWord(StringStream st)
  341. {
  342. string str = ReadSingleIdentifier(st);
  343. if (string.IsNullOrEmpty(str))
  344. return null;
  345. if (UseMacro)
  346. {
  347. int i = 0;
  348. while (true)
  349. {
  350. DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(str);
  351. i++;
  352. if (i > MAX_EXPAND_MACRO)
  353. throw new CodeEE("マクロの展開数が1文あたりの上限値" + MAX_EXPAND_MACRO + "を超えました(自己参照・循環参照のおそれ)");
  354. if (macro == null)
  355. break;
  356. if (macro.IDWord != null)
  357. throw new CodeEE("マクロ" + macro.Keyword + "はこの文脈では使用できません(1単語に置き換えるマクロのみが使用できます)");
  358. str = macro.IDWord.Code;
  359. }
  360. }
  361. return new IdentifierWord(str);
  362. }
  363. /// <summary>
  364. /// 単語を文字列で取得。マクロ適用なし
  365. /// </summary>
  366. /// <param name="st"></param>
  367. /// <returns></returns>
  368. public static string ReadSingleIdentifier(StringStream st)
  369. {
  370. //1819 やや遅い。でもいずれやりたい
  371. //Match m = idReg.Match(st.RowString, st.CurrentPosition);
  372. //st.Jump(m.Length);
  373. //return m.Value;
  374. int start = st.CurrentPosition;
  375. while (!st.EOS)
  376. {
  377. switch (st.Current)
  378. {
  379. case ' ':
  380. case '\t':
  381. case '+':
  382. case '-':
  383. case '*':
  384. case '/':
  385. case '%':
  386. case '=':
  387. case '!':
  388. case '<':
  389. case '>':
  390. case '|':
  391. case '&':
  392. case '^':
  393. case '~':
  394. case '?':
  395. case '#':
  396. case ')':
  397. case '}':
  398. case ']':
  399. case ',':
  400. case ':':
  401. case '(':
  402. case '{':
  403. case '[':
  404. case '$':
  405. case '\\':
  406. case '\'':
  407. case '\"':
  408. case '@':
  409. case '.':
  410. case ';'://コメントに関しては直後に行われるであろうSkipWhiteSpaceなどが対応する。
  411. goto end;
  412. case ' ':
  413. if (!Config.Config.SystemAllowFullSpace)
  414. throw new CodeEE("予期しない全角スペースを発見しました(この警告はシステムオプション「" + Config.Config.GetConfigName(ConfigCode.SystemAllowFullSpace) + "」により無視できます)");
  415. goto end;
  416. }
  417. st.ShiftNext();
  418. }
  419. end:
  420. return st.Substring(start, st.CurrentPosition - start);
  421. }
  422. /// <summary>
  423. /// endWithが見つかるまで読み込む。始点と終端のチェックは呼び出し側で行うこと。
  424. /// エスケープあり。
  425. /// </summary>
  426. /// <param name="st"></param>
  427. /// <returns></returns>
  428. public static string ReadString(StringStream st, StrEndWith endWith)
  429. {
  430. StringBuilder buffer = new StringBuilder(100);
  431. while (true)
  432. {
  433. switch (st.Current)
  434. {
  435. case '\0':
  436. goto end;
  437. case '\"':
  438. if (endWith == StrEndWith.DoubleQuotation)
  439. goto end;
  440. break;
  441. case '\'':
  442. if (endWith == StrEndWith.SingleQuotation)
  443. goto end;
  444. break;
  445. case ',':
  446. if ((endWith == StrEndWith.Comma) || (endWith == StrEndWith.LeftParenthesis_Bracket_Comma_Semicolon))
  447. goto end;
  448. break;
  449. case '(':
  450. case '[':
  451. case ';':
  452. if (endWith == StrEndWith.LeftParenthesis_Bracket_Comma_Semicolon)
  453. goto end;
  454. break;
  455. case '\\'://エスケープ処理
  456. st.ShiftNext();//\を読み飛ばす
  457. switch (st.Current)
  458. {
  459. case StringStream.EndOfString:
  460. throw new CodeEE("エスケープ文字\\の後に文字がありません");
  461. case '\n': break;
  462. case 's': buffer.Append(' '); break;
  463. case 'S': buffer.Append(' '); break;
  464. case 't': buffer.Append('\t'); break;
  465. case 'n': buffer.Append('\n'); break;
  466. default: buffer.Append(st.Current); break;
  467. }
  468. st.ShiftNext();//\の次の文字を読み飛ばす
  469. continue;
  470. }
  471. buffer.Append(st.Current);
  472. st.ShiftNext();
  473. }
  474. end:
  475. return buffer.ToString();
  476. }
  477. /// <summary>
  478. /// 失敗したらCodeEE。OperatorManagerには頼らない
  479. /// OperatorCode.Assignmentを返すことがある。
  480. /// </summary>
  481. /// <param name="st"></param>
  482. /// <returns></returns>
  483. public static OperatorCode ReadOperator(StringStream st, bool allowAssignment)
  484. {
  485. char cur = st.Current;
  486. st.ShiftNext();
  487. char next = st.Current;
  488. switch (cur)
  489. {
  490. case '+':
  491. if (next == '+')
  492. {
  493. st.ShiftNext();
  494. return OperatorCode.Increment;
  495. }
  496. return OperatorCode.Plus;
  497. case '-':
  498. if (next == '-')
  499. {
  500. st.ShiftNext();
  501. return OperatorCode.Decrement;
  502. }
  503. return OperatorCode.Minus;
  504. case '*':
  505. return OperatorCode.Mult;
  506. case '/':
  507. return OperatorCode.Div;
  508. case '%':
  509. return OperatorCode.Mod;
  510. case '=':
  511. if (next == '=')
  512. {
  513. st.ShiftNext();
  514. return OperatorCode.Equal;
  515. }
  516. if (allowAssignment)
  517. return OperatorCode.Assignment;
  518. throw new CodeEE("予期しない代入演算子'='を発見しました(等価比較には'=='を使用してください)");
  519. case '!':
  520. if (next == '=')
  521. {
  522. st.ShiftNext();
  523. return OperatorCode.NotEqual;
  524. }
  525. else if (next == '&')
  526. {
  527. st.ShiftNext();
  528. return OperatorCode.Nand;
  529. }
  530. else if (next == '|')
  531. {
  532. st.ShiftNext();
  533. return OperatorCode.Nor;
  534. }
  535. return OperatorCode.Not;
  536. case '<':
  537. if (next == '=')
  538. {
  539. st.ShiftNext();
  540. return OperatorCode.LessEqual;
  541. }
  542. else if (next == '<')
  543. {
  544. st.ShiftNext();
  545. return OperatorCode.LeftShift;
  546. }
  547. return OperatorCode.Less;
  548. case '>':
  549. if (next == '=')
  550. {
  551. st.ShiftNext();
  552. return OperatorCode.GreaterEqual;
  553. }
  554. else if (next == '>')
  555. {
  556. st.ShiftNext();
  557. return OperatorCode.RightShift;
  558. }
  559. return OperatorCode.Greater;
  560. case '|':
  561. if (next == '|')
  562. {
  563. st.ShiftNext();
  564. return OperatorCode.Or;
  565. }
  566. return OperatorCode.BitOr;
  567. case '&':
  568. if (next == '&')
  569. {
  570. st.ShiftNext();
  571. return OperatorCode.And;
  572. }
  573. return OperatorCode.BitAnd;
  574. case '^':
  575. if (next == '^')
  576. {
  577. st.ShiftNext();
  578. return OperatorCode.Xor;
  579. }
  580. return OperatorCode.BitXor;
  581. case '~':
  582. return OperatorCode.BitNot;
  583. case '?':
  584. return OperatorCode.Ternary_a;
  585. case '#':
  586. return OperatorCode.Ternary_b;
  587. }
  588. throw new CodeEE("'" + cur + "'は演算子として認識できません");
  589. }
  590. /// <summary>
  591. /// 失敗したらCodeEE。OperatorManagerには頼らない
  592. /// "="の時、OperatorCode.Assignmentを返す。"=="の時はEqual
  593. /// </summary>
  594. /// <param name="st"></param>
  595. /// <returns></returns>
  596. public static OperatorCode ReadAssignmentOperator(StringStream st)
  597. {
  598. OperatorCode ret = OperatorCode.NULL;
  599. char cur = st.Current;
  600. st.ShiftNext();
  601. char next = st.Current;
  602. switch (cur)
  603. {
  604. case '+':
  605. if (next == '+')
  606. ret = OperatorCode.Increment;
  607. else if (next == '=')
  608. ret = OperatorCode.Plus;
  609. break;
  610. case '-':
  611. if (next == '-')
  612. ret = OperatorCode.Decrement;
  613. else if (next == '=')
  614. ret = OperatorCode.Minus;
  615. break;
  616. case '*':
  617. if (next == '=')
  618. ret = OperatorCode.Mult;
  619. break;
  620. case '/':
  621. if (next == '=')
  622. ret = OperatorCode.Div;
  623. break;
  624. case '%':
  625. if (next == '=')
  626. ret = OperatorCode.Mod;
  627. break;
  628. case '=':
  629. if (next == '=')
  630. {
  631. ret = OperatorCode.Equal;
  632. break;
  633. }
  634. return OperatorCode.Assignment;
  635. case '\'':
  636. if (next == '=')
  637. {
  638. ret = OperatorCode.AssignmentStr;
  639. break;
  640. }
  641. throw new CodeEE("\"\'\"は代入演算子として認識できません");
  642. case '<':
  643. if (next == '<')
  644. {
  645. st.ShiftNext();
  646. if (st.Current == '=')
  647. {
  648. ret = OperatorCode.LeftShift;
  649. break;
  650. }
  651. throw new CodeEE("'<'は代入演算子として認識できません");
  652. }
  653. break;
  654. case '>':
  655. if (next == '>')
  656. {
  657. st.ShiftNext();
  658. if (st.Current == '=')
  659. {
  660. ret = OperatorCode.RightShift;
  661. break;
  662. }
  663. throw new CodeEE("'>'は代入演算子として認識できません");
  664. }
  665. break;
  666. case '|':
  667. if (next == '=')
  668. ret = OperatorCode.BitOr;
  669. break;
  670. case '&':
  671. if (next == '=')
  672. ret = OperatorCode.BitAnd;
  673. break;
  674. case '^':
  675. if (next == '=')
  676. ret = OperatorCode.BitXor;
  677. break;
  678. }
  679. if (ret == OperatorCode.NULL)
  680. throw new CodeEE("'" + cur + "'は代入演算子として認識できません");
  681. st.ShiftNext();
  682. return ret;
  683. }
  684. /// <summary>
  685. /// Consoleの文字表示用。字句解析や構文解析に使ってはならない
  686. /// </summary>
  687. public static int SkipAllSpace(StringStream st)
  688. {
  689. int count = 0;
  690. while (true)
  691. {
  692. switch (st.Current)
  693. {
  694. case ' ':
  695. case '\t':
  696. case ' ':
  697. count++;
  698. st.ShiftNext();
  699. continue;
  700. }
  701. return count;
  702. }
  703. }
  704. public static bool IsWhiteSpace(char c)
  705. {
  706. return c == ' ' || c == '\t' || c == ' ';
  707. }
  708. /// <summary>
  709. /// 字句解析・構文解析用。ホワイトスペースの他、コメントも飛ばす。
  710. /// </summary>
  711. public static int SkipWhiteSpace(StringStream st)
  712. {
  713. int count = 0;
  714. while (true)
  715. {
  716. switch (st.Current)
  717. {
  718. case ' ':
  719. case '\t':
  720. count++;
  721. st.ShiftNext();
  722. continue;
  723. case ' ':
  724. if (!Config.Config.SystemAllowFullSpace)
  725. return count;
  726. goto case ' ';
  727. case ';':
  728. if (st.CurrentEqualTo(";#;") && Program.DebugMode)
  729. {
  730. st.Jump(3);
  731. continue;
  732. }
  733. else if (st.CurrentEqualTo(";!;"))
  734. {
  735. st.Jump(3);
  736. continue;
  737. }
  738. st.Seek(0, SeekOrigin.End);
  739. return count;
  740. }
  741. return count;
  742. }
  743. }
  744. /// <summary>
  745. /// 字句解析・構文解析用。文字列直前の半角スペースを飛ばす。性質上、半角スペースのみを見る。
  746. /// </summary>
  747. public static int SkipHalfSpace(StringStream st)
  748. {
  749. int count = 0;
  750. while (st.Current == ' ')
  751. {
  752. count++;
  753. st.ShiftNext();
  754. }
  755. return count;
  756. }
  757. #endregion
  758. #region analyse
  759. /// <summary>
  760. /// 解析できるものは関数宣言や式のみ。FORM文字列や普通の文字列を送ってはいけない
  761. /// return時にはendWithの文字がCurrentになっているはず。終端の適切さの検証は呼び出し元が行う。
  762. /// </summary>
  763. /// <returns></returns>
  764. public static WordCollection Analyse(StringStream st, LexEndWith endWith, LexAnalyzeFlag flag)
  765. {
  766. WordCollection ret = new WordCollection();
  767. int nestBracketS = 0;
  768. //int nestBracketM = 0;
  769. int nestBracketL = 0;
  770. while (true)
  771. {
  772. switch (st.Current)
  773. {
  774. case '\n':
  775. case '\0':
  776. goto end;
  777. case ' ':
  778. case '\t':
  779. st.ShiftNext();
  780. continue;
  781. case ' ':
  782. if (!Config.Config.SystemAllowFullSpace)
  783. throw new CodeEE("字句解析中に予期しない全角スペースを発見しました(この警告はシステムオプション「" + Config.Config.GetConfigName(ConfigCode.SystemAllowFullSpace) + "」により無視できます)");
  784. st.ShiftNext();
  785. continue;
  786. case '0':
  787. case '1':
  788. case '2':
  789. case '3':
  790. case '4':
  791. case '5':
  792. case '6':
  793. case '7':
  794. case '8':
  795. case '9':
  796. ret.Add(new LiteralIntegerWord(ReadInt64(st, false)));
  797. break;
  798. case '>':
  799. if(endWith == LexEndWith.GreaterThan)
  800. goto end;
  801. goto case '+';
  802. case '+':
  803. case '-':
  804. case '*':
  805. case '/':
  806. case '%':
  807. case '=':
  808. case '!':
  809. case '<':
  810. case '|':
  811. case '&':
  812. case '^':
  813. case '~':
  814. case '?':
  815. case '#':
  816. if ((nestBracketS == 0) && (nestBracketL == 0))
  817. {
  818. if (endWith == LexEndWith.Operator)
  819. goto end;//代入演算子のはずである。呼び出し元がチェックするはず
  820. if ((endWith == LexEndWith.Percent) && (st.Current == '%'))
  821. goto end;
  822. if ((endWith == LexEndWith.Question) && (st.Current == '?'))
  823. goto end;
  824. }
  825. ret.Add(new OperatorWord(ReadOperator(st, (flag & LexAnalyzeFlag.AllowAssignment) == LexAnalyzeFlag.AllowAssignment)));
  826. break;
  827. case ')': ret.Add(new SymbolWord(')')); nestBracketS--; st.ShiftNext(); continue;
  828. case ']': ret.Add(new SymbolWord(']')); nestBracketL--; st.ShiftNext(); continue;
  829. case '(': ret.Add(new SymbolWord('(')); nestBracketS++; st.ShiftNext(); continue;
  830. case '[':
  831. if (st.Next == '[')
  832. {
  833. //throw new CodeEE("字句解析中に予期しない文字'[['を発見しました");
  834. ////1808alpha006 rename処理変更
  835. //1808beta009 ここだけ戻す
  836. //現在の処理だとここに来た時点でrename失敗確定だが警告内容を元に戻すため
  837. if (ParserMediator.RenameDic == null)
  838. throw new CodeEE("字句解析中に予期しない文字\"[[\"を発見しました");
  839. int start = st.CurrentPosition;
  840. int find = st.Find("]]");
  841. if (find <= 2)
  842. {
  843. if (find == 2)
  844. throw new CodeEE("空の[[]]です");
  845. throw new CodeEE("対応する\"]]\"のない\"[[\"です");
  846. }
  847. string key = st.Substring(start, find + 2);
  848. //1810 ここまでで置換できなかったものは強制エラーにする
  849. //行連結前に置換不能で行連結より置換することができるようになったものまで置換されていたため
  850. throw new CodeEE("字句解析中に置換(rename)できない符号" + key + "を発見しました");
  851. //string value = null;
  852. //if (!ParserMediator.RenameDic.TryGetValue(key, out value))
  853. // throw new CodeEE("字句解析中に置換(rename)できない符号" + key + "を発見しました");
  854. //st.Replace(start, find + 2, value);
  855. //continue;//その場から再度解析スタート
  856. }
  857. ret.Add(new SymbolWord('[')); nestBracketL++; st.ShiftNext(); continue;
  858. case ':': ret.Add(new SymbolWord(':')); st.ShiftNext(); continue;
  859. case ',':
  860. if ((endWith == LexEndWith.Comma) && (nestBracketS == 0))// && (nestBracketL == 0))
  861. goto end;
  862. ret.Add(new SymbolWord(',')); st.ShiftNext(); continue;
  863. //case '}': ret.Add(new SymbolWT('}')); nestBracketM--; continue;
  864. //case '{': ret.Add(new SymbolWT('{')); nestBracketM++; continue;
  865. case '\'':
  866. if ((flag & LexAnalyzeFlag.AllowSingleQuotationStr) == LexAnalyzeFlag.AllowSingleQuotationStr)
  867. {
  868. st.ShiftNext();
  869. ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.SingleQuotation)));
  870. if (st.Current != '\'')
  871. throw new CodeEE("\'が閉じられていません");
  872. st.ShiftNext();
  873. break;
  874. }
  875. if ((flag & LexAnalyzeFlag.AnalyzePrintV) != LexAnalyzeFlag.AnalyzePrintV)
  876. {
  877. //AssignmentStr用特殊処理 代入文の代入演算子を探索中で'=の場合のみ許可
  878. if ((endWith == LexEndWith.Operator) && (nestBracketS == 0) && (nestBracketL == 0) && st.Next == '=' )
  879. goto end;
  880. throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました");
  881. }
  882. st.ShiftNext();
  883. ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.Comma)));
  884. if (st.Current == ',')
  885. goto case ',';//続きがあるなら,の処理へ。それ以外は行終端のはず
  886. goto end;
  887. case '}':
  888. if (endWith == LexEndWith.RightCurlyBrace)
  889. goto end;
  890. throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました");
  891. case '\"':
  892. st.ShiftNext();
  893. ret.Add(new LiteralStringWord(ReadString(st, StrEndWith.DoubleQuotation)));
  894. if (st.Current != '\"')
  895. throw new CodeEE("\"が閉じられていません");
  896. st.ShiftNext();
  897. break;
  898. case '@':
  899. if (st.Next != '\"')
  900. {
  901. ret.Add(new SymbolWord('@'));
  902. st.ShiftNext();
  903. continue;
  904. }
  905. st.ShiftNext();
  906. st.ShiftNext();
  907. ret.Add(AnalyseFormattedString(st, FormStrEndWith.DoubleQuotation, false));
  908. if (st.Current != '\"')
  909. throw new CodeEE("\"が閉じられていません");
  910. st.ShiftNext();
  911. break;
  912. case '.':
  913. ret.Add(new SymbolWord('.'));
  914. st.ShiftNext();
  915. continue;
  916. case '\\':
  917. if (st.Next != '@')
  918. throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました");
  919. {
  920. st.Jump(2);
  921. ret.Add(new StrFormWord(new[] { "", "" }, new SubWord[] { AnalyseYenAt(st) }));
  922. }
  923. break;
  924. case '{':
  925. case '$':
  926. throw new CodeEE("字句解析中に予期しない文字'" + st.Current + "'を発見しました");
  927. case ';'://1807 行中コメント
  928. if (st.CurrentEqualTo(";#;") && Program.DebugMode)
  929. {
  930. st.Jump(3);
  931. break;
  932. }
  933. else if (st.CurrentEqualTo(";!;"))
  934. {
  935. st.Jump(3);
  936. break;
  937. }
  938. st.Seek(0, SeekOrigin.End);
  939. goto end;
  940. default:
  941. {
  942. ret.Add(new IdentifierWord(ReadSingleIdentifier(st)));
  943. break;
  944. }
  945. }
  946. }
  947. end:
  948. if ((nestBracketS != 0) || (nestBracketL != 0))
  949. {
  950. if (nestBracketS < 0)
  951. throw new CodeEE("字句解析中に対応する'('のない')'を発見しました");
  952. if (nestBracketS > 0)
  953. throw new CodeEE("字句解析中に対応する')'のない'('を発見しました");
  954. if (nestBracketL < 0)
  955. throw new CodeEE("字句解析中に対応する'['のない']'を発見しました");
  956. if (nestBracketL > 0)
  957. throw new CodeEE("字句解析中に対応する']'のない'['を発見しました");
  958. }
  959. if (UseMacro)
  960. return expandMacro(ret);
  961. return ret;
  962. }
  963. private static WordCollection expandMacro(WordCollection wc)
  964. {
  965. //マクロ展開
  966. wc.Pointer = 0;
  967. int count = 0;
  968. while (!wc.EOL)
  969. {
  970. IdentifierWord word = wc.Current as IdentifierWord;
  971. if (word == null)
  972. {
  973. wc.ShiftNext();
  974. continue;
  975. }
  976. string idStr = word.Code;
  977. DefineMacro macro = GlobalStatic.IdentifierDictionary.GetMacro(idStr);
  978. if (macro == null)
  979. {
  980. wc.ShiftNext();
  981. continue;
  982. }
  983. count++;
  984. if (count > MAX_EXPAND_MACRO)
  985. throw new CodeEE("マクロの展開数が1文あたりの上限" + MAX_EXPAND_MACRO + "を超えました(自己参照・循環参照のおそれ)");
  986. if (!macro.HasArguments)
  987. {
  988. wc.Remove();
  989. wc.InsertRange(macro.Statement);
  990. continue;
  991. }
  992. //関数型マクロ
  993. wc = expandFunctionlikeMacro(macro, wc);
  994. }
  995. wc.Pointer = 0;
  996. return wc;
  997. }
  998. private static WordCollection expandFunctionlikeMacro(DefineMacro macro, WordCollection wc)
  999. {
  1000. int macroStart = wc.Pointer;
  1001. wc.ShiftNext();
  1002. SymbolWord symbol = wc.Current as SymbolWord;
  1003. if (symbol == null || symbol.Type != '(')
  1004. throw new CodeEE("関数形式のマクロ" + macro.Keyword + "に引数がありません");
  1005. WordCollection macroWC = macro.Statement.Clone();
  1006. WordCollection[] args = new WordCollection[macro.ArgCount];
  1007. //引数部読み取りループ
  1008. for (int i = 0; i < macro.ArgCount; i++)
  1009. {
  1010. int macroNestBracketS = 0;
  1011. args[i] = new WordCollection();
  1012. while (true)
  1013. {
  1014. wc.ShiftNext();
  1015. if (wc.EOL)
  1016. throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の用法が正しくありません");
  1017. symbol = wc.Current as SymbolWord;
  1018. if (symbol == null)
  1019. {
  1020. args[i].Add(wc.Current);
  1021. continue;
  1022. }
  1023. switch (symbol.Type)
  1024. {
  1025. case '(': macroNestBracketS++; break;
  1026. case ')':
  1027. if (macroNestBracketS > 0)
  1028. {
  1029. macroNestBracketS--;
  1030. break;
  1031. }
  1032. if (i != macro.ArgCount - 1)
  1033. throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の引数の数が正しくありません");
  1034. goto exitfor;
  1035. case ',':
  1036. if (macroNestBracketS == 0)
  1037. goto exitwhile;
  1038. break;
  1039. }
  1040. args[i].Add(wc.Current);
  1041. }
  1042. exitwhile:
  1043. if (args[i].Collection.Count == 0)
  1044. throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の引数を省略することはできません");
  1045. }
  1046. //引数部読み取りループ終端
  1047. exitfor:
  1048. symbol = wc.Current as SymbolWord;
  1049. if (symbol == null || symbol.Type != ')')
  1050. throw new CodeEE("関数形式のマクロ" + macro.Keyword + "の用法が正しくありません");
  1051. int macroLength = wc.Pointer - macroStart + 1;
  1052. wc.Pointer = macroStart;
  1053. for (int j = 0; j < macroLength; j++)
  1054. wc.Collection.RemoveAt(macroStart);
  1055. while (!macroWC.EOL)
  1056. {
  1057. MacroWord w = macroWC.Current as MacroWord;
  1058. if (w == null)
  1059. {
  1060. macroWC.ShiftNext();
  1061. continue;
  1062. }
  1063. macroWC.Remove();
  1064. macroWC.InsertRange(args[w.Number]);
  1065. macroWC.Pointer += args[w.Number].Collection.Count;
  1066. }
  1067. wc.InsertRange(macroWC);
  1068. wc.Pointer = macroStart;
  1069. return wc;
  1070. }
  1071. /// <summary>
  1072. /// @"などの直後からの開始
  1073. /// return時にはendWithの文字がCurrentになっているはず。終端の適切さの検証は呼び出し元が行う。
  1074. /// </summary>
  1075. /// <returns></returns>
  1076. public static StrFormWord AnalyseFormattedString(StringStream st, FormStrEndWith endWith, bool trim)
  1077. {
  1078. List<string> strs = new List<string>();
  1079. List<SubWord> SWTs = new List<SubWord>();
  1080. StringBuilder buffer = new StringBuilder(100);
  1081. while (true)
  1082. {
  1083. char cur = st.Current;
  1084. switch (cur)
  1085. {
  1086. case '\n':
  1087. case '\0':
  1088. goto end;
  1089. case '\"':
  1090. if (endWith == FormStrEndWith.DoubleQuotation)
  1091. goto end;
  1092. buffer.Append(cur);
  1093. break;
  1094. case '#':
  1095. if (endWith == FormStrEndWith.Sharp)
  1096. goto end;
  1097. buffer.Append(cur);
  1098. break;
  1099. case ',':
  1100. if ((endWith == FormStrEndWith.Comma) || (endWith == FormStrEndWith.LeftParenthesis_Bracket_Comma_Semicolon))
  1101. goto end;
  1102. buffer.Append(cur);
  1103. break;
  1104. case '(':
  1105. case '[':
  1106. case ';':
  1107. if (endWith == FormStrEndWith.LeftParenthesis_Bracket_Comma_Semicolon)
  1108. goto end;
  1109. buffer.Append(cur);
  1110. break;
  1111. case '%':
  1112. strs.Add(buffer.ToString());
  1113. buffer.Remove(0, buffer.Length);
  1114. st.ShiftNext();
  1115. SWTs.Add(new PercentSubWord(Analyse(st, LexEndWith.Percent, LexAnalyzeFlag.None)));
  1116. if (st.Current != '%')
  1117. throw new CodeEE("\'%\'が使われましたが対応する\'%\'が見つかりません");
  1118. break;
  1119. case '{':
  1120. strs.Add(buffer.ToString());
  1121. buffer.Remove(0, buffer.Length);
  1122. st.ShiftNext();
  1123. SWTs.Add(new CurlyBraceSubWord(Analyse(st, LexEndWith.RightCurlyBrace, LexAnalyzeFlag.None)));
  1124. if (st.Current != '}')
  1125. throw new CodeEE("\'{\'が使われましたが対応する\'}\'が見つかりません");
  1126. break;
  1127. case '*':
  1128. case '+':
  1129. case '=':
  1130. case '/':
  1131. case '$':
  1132. if (!Config.Config.SystemIgnoreTripleSymbol && st.TripleSymbol())
  1133. {
  1134. strs.Add(buffer.ToString());
  1135. buffer.Remove(0, buffer.Length);
  1136. st.Jump(3);
  1137. SWTs.Add(new TripleSymbolSubWord(cur));
  1138. continue;
  1139. }
  1140. else
  1141. buffer.Append(cur);
  1142. break;
  1143. case '\\'://エスケープ文字の使用
  1144. st.ShiftNext();
  1145. cur = st.Current;
  1146. switch (cur)
  1147. {
  1148. case '\0':
  1149. throw new CodeEE("エスケープ文字\\の後に文字がありません");
  1150. case '\n': break;
  1151. case 's': buffer.Append(' '); break;
  1152. case 'S': buffer.Append(' '); break;
  1153. case 't': buffer.Append('\t'); break;
  1154. case 'n': buffer.Append('\n'); break;
  1155. case '@'://\@~~?~~#~~\@
  1156. {
  1157. if ((endWith == FormStrEndWith.YenAt) || (endWith == FormStrEndWith.Sharp))
  1158. goto end;
  1159. strs.Add(buffer.ToString());
  1160. buffer.Remove(0, buffer.Length);
  1161. st.ShiftNext();
  1162. SWTs.Add(AnalyseYenAt(st));
  1163. continue;
  1164. }
  1165. default:
  1166. buffer.Append(cur);
  1167. st.ShiftNext();
  1168. continue;
  1169. }
  1170. break;
  1171. default:
  1172. buffer.Append(cur);
  1173. break;
  1174. }
  1175. st.ShiftNext();
  1176. }
  1177. end:
  1178. strs.Add(buffer.ToString());
  1179. string[] retStr = new string[strs.Count];
  1180. SubWord[] retSWTs = new SubWord[SWTs.Count];
  1181. strs.CopyTo(retStr);
  1182. SWTs.CopyTo(retSWTs);
  1183. if (trim && retStr.Length > 0)
  1184. {
  1185. retStr[0] = retStr[0].TrimStart(' ', '\t');
  1186. retStr[retStr.Length - 1] = retStr[retStr.Length - 1].TrimEnd(' ', '\t');
  1187. }
  1188. return new StrFormWord(retStr, retSWTs);
  1189. }
  1190. /// <summary>
  1191. /// \@直後からの開始、\@の直後がCurrentになる
  1192. /// </summary>
  1193. /// <param name="st"></param>
  1194. /// <returns></returns>
  1195. public static YenAtSubWord AnalyseYenAt(StringStream st)
  1196. {
  1197. WordCollection w = Analyse(st, LexEndWith.Question, LexAnalyzeFlag.None);
  1198. if (st.Current != '?')
  1199. throw new CodeEE("\'\\@\'が使われましたが対応する\'?\'が見つかりません");
  1200. st.ShiftNext();
  1201. StrFormWord left = AnalyseFormattedString(st, FormStrEndWith.Sharp, true);
  1202. if (st.Current != '#')
  1203. {
  1204. if (st.Current != '@')
  1205. throw new CodeEE("\'\\@\',\'?\'が使われましたが対応する\'#\'が見つかりません");
  1206. st.ShiftNext();
  1207. ParserMediator.Warn("\'\\@\',\'?\'が使われましたが対応する\'#\'が見つかりません", GlobalStatic.Process.GetScaningLine(), 1, false, false);
  1208. return new YenAtSubWord(w, left, null);
  1209. }
  1210. st.ShiftNext();
  1211. StrFormWord right = AnalyseFormattedString(st, FormStrEndWith.YenAt, true);
  1212. if (st.Current != '@')
  1213. throw new CodeEE("\'\\@\',\'?\',\'#\'が使われましたが対応する\'\\@\'が見つかりません");
  1214. st.ShiftNext();
  1215. return new YenAtSubWord(w, left, right);
  1216. }
  1217. #endregion
  1218. }
  1219. }