QSPGameCode.cs 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.ComponentModel;
  8. namespace Analyser
  9. {
  10. public class Location : Common
  11. {
  12. QSPGameCode m_gamecode;
  13. string m_name;
  14. int m_line;
  15. bool m_start; //Стартовая локация
  16. List<string> location_codeline_text;
  17. Dictionary<int, int> location_codeline_level;
  18. int currentLine;
  19. bool currentRoot;
  20. enum ControlBlockType
  21. {
  22. None,
  23. SL_If,
  24. SL_Else,
  25. SL_Act,
  26. ML_If,
  27. ML_Else,
  28. ML_Act,
  29. IfCondition,
  30. ElseIfCondition,
  31. ActCondition
  32. }
  33. struct ControlLine
  34. {
  35. public ControlBlockType controlBlock;
  36. public int line;
  37. }
  38. public Location(QSPGameCode code, string name, int line, bool start)
  39. {
  40. m_gamecode = code;
  41. m_name = name;
  42. m_line = line;
  43. m_start = start;
  44. location_codeline_text = null;
  45. location_codeline_level = null;
  46. }
  47. public string GetName()
  48. {
  49. return m_name;
  50. }
  51. public int GetLine()
  52. {
  53. return m_line;
  54. }
  55. public int GetCodeLinesCount()
  56. {
  57. return location_codeline_text.Count;
  58. }
  59. public void GetCodeLine(int lineNum, ref string text, ref int level)
  60. {
  61. //Нужно для утилиты форматирования
  62. int realNum = lineNum + 1;
  63. text = location_codeline_text[lineNum];
  64. if (location_codeline_level.ContainsKey(realNum))
  65. level = location_codeline_level[realNum];
  66. else
  67. level = INVALID_INDEX;
  68. return;
  69. }
  70. new void SubmitError(string text, int line)
  71. {
  72. if (currentRoot)
  73. Common.SubmitError(text, line);
  74. else
  75. Common.SubmitError(text, currentLine);
  76. }
  77. new void SubmitWarning(string text, int line)
  78. {
  79. if (currentRoot)
  80. Common.SubmitWarning(text, line);
  81. else
  82. Common.SubmitWarning(text, currentLine);
  83. }
  84. bool qspCompileExprPushOpCode(ref int[] opStack, ref int opSp, ref int[] argStack, ref int argSp, int opCode)
  85. {
  86. if ((opSp == QSP_STACKSIZE - 1) || (argSp == QSP_STACKSIZE - 1))
  87. {
  88. SubmitError("Quite complicated expression", currentLine);
  89. return false;
  90. }
  91. opStack[++opSp] = opCode;
  92. argStack[++argSp] = (opCode < (int)QspFunctionType.First_Function) ? qspOps[opCode].MinArgsCount : 0;
  93. return true;
  94. }
  95. bool qspAppendToCompiled(ref int itemsCount)
  96. {
  97. if (itemsCount == QSP_MAXITEMS)
  98. {
  99. SubmitError("Quite many arguments in the expression", currentLine);
  100. return false;
  101. }
  102. ++itemsCount;
  103. return true;
  104. }
  105. public bool ParseLocation(List<string> code, bool root)
  106. {
  107. int quote = (int)QuoteType.None;
  108. if (root)
  109. {
  110. currentRoot = true;
  111. currentLine = 0;
  112. location_codeline_text = new List<string>(code);
  113. location_codeline_level = new Dictionary<int, int>();
  114. }
  115. //Склеиваем строки
  116. List<int> lineIndexes = new List<int>();
  117. List<string> escapedLines = new List<string>();
  118. int linesCount = code.Count;
  119. int oldLine = 0;
  120. int curLine = 0;
  121. int curlyLevel = 0;
  122. string extraLine = "";
  123. while (curLine < linesCount)
  124. {
  125. string line = code.ToArray()[curLine].Trim(WhiteSpace);
  126. int pos = 0;
  127. while (pos < line.Length)
  128. {
  129. char c = line[pos];
  130. if (c == '\'')
  131. {
  132. //Апостроф
  133. if (quote == (int)QuoteType.None)
  134. {
  135. quote = (int)QuoteType.Single;
  136. }
  137. else if (quote == (int)QuoteType.Single)
  138. {
  139. if ((pos + 1 < line.Length) && (line[pos + 1] == '\''))
  140. {
  141. //Экранированный апостроф
  142. pos++;
  143. }
  144. else
  145. {
  146. quote = (int)QuoteType.None;
  147. }
  148. }
  149. }
  150. else if (c == '"')
  151. {
  152. //Кавычка
  153. if (quote == (int)QuoteType.None)
  154. {
  155. quote = (int)QuoteType.Double;
  156. }
  157. else if (quote == (int)QuoteType.Double)
  158. {
  159. if ((pos + 1 < line.Length) && (line[pos + 1] == '"'))
  160. {
  161. //Экранированная кавычка
  162. pos++;
  163. }
  164. else
  165. {
  166. quote = (int)QuoteType.None;
  167. }
  168. }
  169. }
  170. else if (quote == (int)QuoteType.None)
  171. {
  172. if (c == '{')
  173. {
  174. curlyLevel++;
  175. }
  176. else if (c == '}')
  177. {
  178. if (curlyLevel == 0)
  179. {
  180. SubmitError("Closing curly brace without opening one", oldLine + 1);
  181. return false;
  182. }
  183. curlyLevel--;
  184. }
  185. }
  186. pos++;
  187. }
  188. if ((curlyLevel > 0) || (quote != (int)QuoteType.None) || line.EndsWith(" _"))
  189. {
  190. if (line.EndsWith(" _"))
  191. line = line.Substring(0, line.Length - 2);
  192. extraLine += line;
  193. if (curlyLevel > 0)
  194. extraLine += "\n";//Вставляем разделитель для строк, потом по нему "разобьем" строки
  195. if (curLine == linesCount - 1)
  196. {
  197. lineIndexes.Add(oldLine + 1);
  198. string escaped = extraLine + line;
  199. escapedLines.Add(escaped.Trim(WhiteSpace));
  200. }
  201. }
  202. else
  203. {
  204. lineIndexes.Add(oldLine + 1);
  205. string escaped = extraLine + line;
  206. escapedLines.Add(escaped.Trim(WhiteSpace));
  207. oldLine = curLine + 1;
  208. extraLine = "";
  209. }
  210. curLine++;
  211. }
  212. //Проверка на незакрытые в конце локации многострочные строки
  213. if (quote != (int)QuoteType.None)
  214. {
  215. SubmitError("Unclosed string", oldLine + 1);
  216. return false;
  217. }
  218. //Проверка на незакрытые в конце локации фигурные скобки
  219. if (curlyLevel > 0)
  220. {
  221. SubmitError("Unclosed curly bracket", oldLine + 1);
  222. return false;
  223. }
  224. //TODO
  225. // FOR
  226. // перечисления asd|12|ddd
  227. //Разбираем код
  228. int lineNum = 0;
  229. int linePlainNum = 0;
  230. string block = "";
  231. string quotedText = "";
  232. int controlBlock = (int)ControlBlockType.None;
  233. Stack<ControlLine> ControlStack = new Stack<ControlLine>();
  234. List<string> blockGroup = new List<string>();
  235. List<bool> blockInGroupIsText = new List<bool>();
  236. int groupInnerCounter = 0;
  237. bool blockStarted = false;
  238. bool blockCompleted = false;
  239. bool blockGroupStarted = false;
  240. bool blockGroupCompleted = false;
  241. bool quotedTextCompleted = false;
  242. string rawText = "";
  243. string debugText = "";
  244. foreach (string line in escapedLines)
  245. {
  246. lineNum = lineIndexes[linePlainNum];
  247. linePlainNum++;
  248. int startIndentLevel = 0;
  249. int endIndentLevel = 0;
  250. if (currentRoot)
  251. {
  252. currentLine = lineNum;
  253. //Вычисляем уровень вложенности(для утилиты форматирования кода)
  254. int stackSize = ControlStack.Count;
  255. if (stackSize > 0)
  256. startIndentLevel = stackSize;
  257. }
  258. int pos = 0;
  259. int firstSymbolPos = INVALID_INDEX;
  260. int blockStartPos = INVALID_INDEX;
  261. int lastIfPos = INVALID_INDEX;
  262. int lastActPos = INVALID_INDEX;
  263. int bracketLevel = 0;
  264. bool comment = false;
  265. bool label = false;
  266. string labelText = "";
  267. bool singleBlockGroup = false;
  268. //Разбор строки
  269. while (pos < line.Length)
  270. {
  271. bool appendDelimiter = false;
  272. String delimiterToAppend = "";
  273. char c = line[pos];
  274. if ((c.ToString().IndexOfAny(WhiteSpace) != 0) && (firstSymbolPos == INVALID_INDEX))
  275. {
  276. firstSymbolPos = pos;
  277. }
  278. if (c == '\'')
  279. {
  280. //Апостроф
  281. if (quote == (int)QuoteType.None)
  282. {
  283. quote = (int)QuoteType.Single;
  284. quotedText = "";
  285. if (blockStarted && !comment)
  286. blockCompleted = true;
  287. //для отладки
  288. if (rawText.Length == 0)
  289. rawText += c;
  290. else
  291. rawText += Environment.NewLine + c;
  292. }
  293. else if (quote == (int)QuoteType.Single)
  294. {
  295. if ((pos + 1 < line.Length) && (line[pos + 1] == '\''))
  296. {
  297. //Экранированный апостроф
  298. pos++;
  299. quotedText += c;
  300. }
  301. else
  302. {
  303. quote = (int)QuoteType.None;
  304. if (!comment && !label)
  305. quotedTextCompleted = true;
  306. }
  307. //для отладки
  308. rawText += c;
  309. }
  310. else
  311. {
  312. quotedText += c;
  313. //для отладки
  314. rawText += c;
  315. }
  316. }
  317. else if (c == '"')
  318. {
  319. //Кавычка
  320. if (quote == (int)QuoteType.None)
  321. {
  322. quote = (int)QuoteType.Double;
  323. quotedText = "";
  324. if (blockStarted && !comment)
  325. blockCompleted = true;
  326. //для отладки
  327. if (rawText.Length == 0)
  328. rawText += c;
  329. else
  330. rawText += Environment.NewLine + c;
  331. }
  332. else if (quote == (int)QuoteType.Double)
  333. {
  334. if ((pos + 1 < line.Length) && (line[pos + 1] == '"'))
  335. {
  336. //Экранированная кавычка
  337. pos++;
  338. quotedText += c;
  339. }
  340. else
  341. {
  342. quote = (int)QuoteType.None;
  343. if (!comment && !label)
  344. quotedTextCompleted = true;
  345. }
  346. //для отладки
  347. rawText += c;
  348. }
  349. else
  350. {
  351. quotedText += c;
  352. //для отладки
  353. rawText += c;
  354. }
  355. }
  356. else if (comment)
  357. {
  358. //Здесь игнорируем все до самого конца строки, но учитываем переводы строк внутри кавычек и апострофов.
  359. }
  360. else if (quote != (int)QuoteType.None)
  361. {
  362. //Строка текста внутри кавычек или апострофов
  363. quotedText += c;
  364. //для отладки
  365. rawText += c;
  366. }
  367. else if (c == '{')
  368. {
  369. if (blockStarted && !comment)
  370. blockCompleted = true;
  371. //Записываем содержимое фигурных скобок
  372. string curlyText = "";
  373. curlyLevel = 1;
  374. pos++;
  375. int curlyQuote = (int)QuoteType.None;
  376. while (pos < line.Length)
  377. {
  378. char c2 = line[pos];
  379. if (c2 == '\'')
  380. {
  381. //Апостроф
  382. if (curlyQuote == (int)QuoteType.None)
  383. {
  384. curlyQuote = (int)QuoteType.Single;
  385. }
  386. else if (curlyQuote == (int)QuoteType.Single)
  387. {
  388. if ((pos + 1 < line.Length) && (line[pos + 1] == '\''))
  389. {
  390. //Экранированный апостроф
  391. curlyText += c2;
  392. pos++;
  393. c2 = line[pos];
  394. }
  395. else
  396. {
  397. curlyQuote = (int)QuoteType.None;
  398. }
  399. }
  400. }
  401. else if (c2 == '"')
  402. {
  403. //Кавычка
  404. if (curlyQuote == (int)QuoteType.None)
  405. {
  406. curlyQuote = (int)QuoteType.Double;
  407. }
  408. else if (curlyQuote == (int)QuoteType.Double)
  409. {
  410. if ((pos + 1 < line.Length) && (line[pos + 1] == '"'))
  411. {
  412. //Экранированная кавычка
  413. curlyText += c2;
  414. pos++;
  415. c2 = line[pos];
  416. }
  417. else
  418. {
  419. curlyQuote = (int)QuoteType.None;
  420. }
  421. }
  422. }
  423. else if (curlyQuote == (int)QuoteType.None)
  424. {
  425. if (c2 == '{')
  426. {
  427. curlyLevel++;
  428. }
  429. else if (c2 == '}')
  430. {
  431. curlyLevel--;
  432. if (curlyLevel == 0)
  433. break;
  434. }
  435. }
  436. curlyText += c2;
  437. pos++;
  438. }
  439. if (curlyLevel > 0)
  440. {
  441. SubmitError("Internal error of the analyzer - unclosed curly bracket \"{\"", currentLine);
  442. break;
  443. }
  444. if (curlyParsing)
  445. {
  446. //Парсим содержимое фигурных скобок
  447. List<string> curlyLines = new List<string>(curlyText.Split('\n'));
  448. currentRoot = false;
  449. ParseLocation(curlyLines, currentRoot);
  450. currentRoot = root;
  451. //Добавляем пустую "строку в кавычках", чтобы анализатор не ругался на отсутствие параметра
  452. quotedText = "";
  453. }
  454. else
  455. {
  456. quotedText = curlyText;
  457. }
  458. quotedTextCompleted = true;
  459. }
  460. else
  461. {
  462. //Обычные символы
  463. if (label)
  464. {
  465. if (c == '&')
  466. {
  467. if (labelText.Trim(WhiteSpace).Equals(":"))
  468. {
  469. SubmitError("Empty label", lineNum);
  470. return false;
  471. }
  472. if (quote != (int)QuoteType.None)
  473. {
  474. SubmitError("Unclosed string in the label name", lineNum);
  475. return false;
  476. }
  477. label = false;
  478. }
  479. else
  480. {
  481. labelText += c;
  482. }
  483. }
  484. else if ((c == ':') && ((controlBlock == (int)ControlBlockType.IfCondition) ||
  485. (controlBlock == (int)ControlBlockType.ElseIfCondition)))
  486. {
  487. //Разбор условия
  488. if (blockStarted)
  489. blockCompleted = true;
  490. blockGroupCompleted = true;
  491. //Двоеточие после условия
  492. if ((pos == line.Length - 1))
  493. {
  494. //В конце строки - многострочный IF или ELSEIF
  495. if (firstSymbolPos == lastIfPos)
  496. {
  497. if (controlBlock == (int)ControlBlockType.IfCondition)
  498. {
  499. ControlLine cline;
  500. cline.line = lineNum;
  501. cline.controlBlock = ControlBlockType.ML_If;
  502. ControlStack.Push(cline);
  503. }
  504. else
  505. {
  506. ControlLine cline = ControlStack.Pop();
  507. if (cline.controlBlock != ControlBlockType.ML_If)
  508. {
  509. SubmitError("ELSEIF without IF", lineNum);
  510. return false;
  511. }
  512. cline.line = lineNum;
  513. ControlStack.Push(cline);
  514. }
  515. controlBlock = (int)ControlBlockType.ML_If;
  516. }
  517. else
  518. {
  519. if (controlBlock == (int)ControlBlockType.IfCondition)
  520. SubmitError("Multiline IF should be placed at the beginning of the line", lineNum);
  521. else
  522. SubmitError("Multiline ELSEIF should be placed at the beginning of the line", lineNum);
  523. return false;
  524. }
  525. }
  526. else if (controlBlock == (int)ControlBlockType.IfCondition)
  527. {
  528. //Строка не заканчивается - однострочный IF
  529. if (controlBlock == (int)ControlBlockType.IfCondition)
  530. {
  531. ControlLine cline;
  532. cline.line = lineNum;
  533. cline.controlBlock = ControlBlockType.SL_If;
  534. ControlStack.Push(cline);
  535. controlBlock = (int)cline.controlBlock;
  536. groupInnerCounter = 0;
  537. }
  538. else
  539. {
  540. SubmitError("ELSEIF cannot be used in single line IF", lineNum);
  541. return false;
  542. }
  543. }
  544. else
  545. {
  546. SubmitError("An operator cannot be placed after colon\":\" in multiline ELSEIF", lineNum);
  547. return false;
  548. }
  549. }
  550. else if ((c == ':') && (block == "else"))
  551. {
  552. SubmitError("ELSE with :", lineNum);
  553. return false;
  554. }
  555. else if ((c == ':') && (controlBlock == (int)ControlBlockType.ActCondition))
  556. {
  557. //Разбор аргумента
  558. if (blockStarted)
  559. blockCompleted = true;
  560. blockGroupCompleted = true;
  561. //Двоеточие после ACT
  562. if (pos == line.Length - 1)
  563. {
  564. //В конце строки - многострочный ACT
  565. if (firstSymbolPos == lastActPos)
  566. {
  567. controlBlock = (int)ControlBlockType.ML_Act;
  568. ControlLine cline;
  569. cline.line = lineNum;
  570. cline.controlBlock = ControlBlockType.ML_Act;
  571. ControlStack.Push(cline);
  572. }
  573. else
  574. {
  575. SubmitError("Multiline ACT should be placed at the beginning of the line", lineNum);
  576. return false;
  577. }
  578. }
  579. else
  580. {
  581. //Строка не заканчивается - однострочный ACT
  582. controlBlock = (int)ControlBlockType.SL_Act;
  583. groupInnerCounter = 0;
  584. }
  585. }
  586. else if (!comment && (c == '!') && !blockGroupStarted && !blockStarted)
  587. {
  588. //Начало комментария
  589. comment = true;
  590. }
  591. else if ((c == ':') && (firstSymbolPos == pos))
  592. {
  593. //Начало метки
  594. label = true;
  595. }
  596. else if (c.ToString().IndexOfAny(Delimiters) == 0)
  597. {
  598. if ((c == '&') && (bracketLevel == 0))
  599. {
  600. if (controlBlock == (int)ControlBlockType.IfCondition)
  601. {
  602. //В условии IF недопустимо использование "&" вне скобок
  603. SubmitError("Redundant \"&\": perhaps should be \"AND\"", lineNum);
  604. return false;
  605. }
  606. else if (controlBlock == (int)ControlBlockType.ActCondition)
  607. {
  608. //В названии ACT недопустимо использование "&" вне скобок
  609. SubmitError("Redundant \"&\"", lineNum);
  610. return false;
  611. }
  612. else
  613. {
  614. if (blockStarted)
  615. blockCompleted = true;
  616. if (blockGroupStarted)
  617. blockGroupCompleted = true;
  618. if (blockStarted && !blockGroupStarted)
  619. singleBlockGroup = true;
  620. }
  621. }
  622. else if (blockStarted && (c == ' ') && StartOfMultiWordOperator(block))
  623. {
  624. //Составной оператор - DEL ACT, DEL OBJ
  625. block += c;
  626. }
  627. else if (blockStarted && (c == ' ') && (qspGetStatCode(block) == (int)QspStatementType.Close) &&
  628. (line.Length > pos + 3) && line.Substring(pos + 1, 3).Equals("ALL", StringComparison.OrdinalIgnoreCase))
  629. {
  630. //CLOSE ALL
  631. block += c;
  632. }
  633. else if (!blockStarted && (c == '*'))
  634. {
  635. //Возможно, *PL, *P, *NL
  636. blockStarted = true;
  637. blockCompleted = false;
  638. block += c;
  639. blockStartPos = pos;
  640. }
  641. else if (!blockStarted && (c == '['))
  642. {
  643. //Квадратная скобка должна идти вплотную к имени массива
  644. SubmitError("A square bracket has to be placed just behind the name of the array, with no spaces", lineNum);
  645. return false;
  646. }
  647. else
  648. {
  649. //Самостоятельные знаки
  650. if (c == '(')
  651. {
  652. bracketLevel++;
  653. }
  654. else if (c == ')')
  655. {
  656. if (bracketLevel == 0)
  657. {
  658. SubmitError("Redundant bracket \")\"", lineNum);
  659. return false;
  660. }
  661. bracketLevel--;
  662. }
  663. bool whiteSpace = c.ToString().IndexOfAny(WhiteSpace) == 0;
  664. //Особый учет для последовательностей >=, => и т.д.
  665. bool comparer = pos + 1 < line.Length;
  666. String cmp = "";
  667. if (comparer)
  668. {
  669. cmp = line.Substring(pos, 2);
  670. comparer = cmp.Equals("<=") || cmp.Equals(">=") || cmp.Equals("=>") || cmp.Equals("=<") || cmp.Equals("<>") ||
  671. cmp.Equals("+=") || cmp.Equals("-=");
  672. }
  673. if (comparer)
  674. {
  675. //<= >= => =< <> += -=
  676. if (blockStarted)
  677. {
  678. appendDelimiter = true;
  679. delimiterToAppend = cmp;
  680. }
  681. else
  682. {
  683. blockStarted = true;
  684. blockStartPos = pos;
  685. block = cmp;
  686. }
  687. blockCompleted = true;
  688. pos++;
  689. }
  690. else if (blockStarted)
  691. {
  692. blockCompleted = true;
  693. if (!whiteSpace)
  694. {
  695. appendDelimiter = true;
  696. delimiterToAppend += c;
  697. }
  698. else
  699. {
  700. //Обрабатываем END IF, END ACT
  701. int blockCode = qspGetStatCode(block);
  702. if (blockCode == (int)QspStatementType.End)
  703. {
  704. int nextPos = line.LastIndexOfAny(WhiteSpace, blockStartPos + block.Length) + 1;
  705. if (nextPos < line.Length)
  706. {
  707. int delimPos = line.IndexOfAny(Delimiters, nextPos);
  708. string nextWord = "";
  709. if (delimPos == INVALID_INDEX)
  710. nextWord = line.Substring(nextPos);
  711. else
  712. nextWord = line.Substring(nextPos, delimPos - nextPos);
  713. int nextCode = qspGetStatCode(nextWord);
  714. if ((nextCode == (int)QspStatementType.If) || (nextCode == (int)QspStatementType.Act))
  715. {
  716. pos = nextPos + nextWord.Length - 1;
  717. }
  718. }
  719. }
  720. }
  721. }
  722. else if (!whiteSpace)
  723. {
  724. blockStarted = true;
  725. blockCompleted = true;
  726. blockStartPos = pos;
  727. block += c;
  728. }
  729. }
  730. }
  731. else
  732. {
  733. //Просто буквы
  734. if (!blockStarted)
  735. {
  736. blockStarted = true;
  737. blockCompleted = false;
  738. blockStartPos = pos;
  739. }
  740. block += c;
  741. }
  742. }
  743. //Последний символ в строке
  744. if (blockStarted && (pos == line.Length - 1))
  745. {
  746. blockCompleted = true;
  747. }
  748. if (blockCompleted || quotedTextCompleted)
  749. {
  750. if (!quotedTextCompleted && (block.Length == 0))
  751. {
  752. SubmitError("Internal error of analyzer! Empty block!", lineNum);
  753. return false;
  754. }
  755. debugText += "[" + block + "] ";
  756. bool skip = false;
  757. int blockCode = qspGetStatCode(block);
  758. if (blockCode == (int)QspStatementType.If)
  759. {
  760. controlBlock = (int)ControlBlockType.IfCondition;
  761. debugText += "<IfCondition> ";
  762. lastIfPos = blockStartPos;
  763. }
  764. if (blockCode == (int)QspStatementType.Act)
  765. {
  766. controlBlock = (int)ControlBlockType.ActCondition;
  767. debugText += "<ActCondition> ";
  768. lastActPos = blockStartPos;
  769. }
  770. if (blockCode == (int)QspStatementType.ElseIf)
  771. {
  772. if (controlBlock == (int)ControlBlockType.ML_If)
  773. {
  774. controlBlock = (int)ControlBlockType.ElseIfCondition;
  775. debugText += "<ElseIfCondition> ";
  776. lastIfPos = blockStartPos;
  777. }
  778. else
  779. {
  780. SubmitError("ELSEIF без IF", lineNum);
  781. return false;
  782. }
  783. }
  784. if (blockCode == (int)QspStatementType.Else)
  785. {
  786. if (controlBlock == (int)ControlBlockType.ML_If)
  787. {
  788. if (firstSymbolPos == blockStartPos)
  789. {
  790. if ((blockStartPos + block.Length == line.Length) || (line.Substring(blockStartPos + block.Length).Trim(WhiteSpace).Equals(":")))
  791. {
  792. controlBlock = (int)ControlBlockType.ML_Else;
  793. ControlStack.Pop();
  794. ControlLine cline;
  795. cline.controlBlock = ControlBlockType.ML_Else;
  796. cline.line = lineNum;
  797. ControlStack.Push(cline);
  798. }
  799. else
  800. {
  801. SubmitError("An operator cannot be placed after multiline ELSE", lineNum);
  802. return false;
  803. }
  804. }
  805. else
  806. {
  807. SubmitError("Multiline ELSE should be at the beginning of the line", lineNum);
  808. return false;
  809. }
  810. }
  811. else
  812. {
  813. if (controlBlock == (int)ControlBlockType.SL_Act)
  814. {
  815. if (groupInnerCounter > 0)
  816. {
  817. if ((ControlStack.Peek().controlBlock == ControlBlockType.SL_If) && (ControlStack.Peek().line == lineNum))
  818. {
  819. if (blockGroupStarted)
  820. {
  821. blockGroupCompleted = true;
  822. }
  823. }
  824. else
  825. {
  826. SubmitError("ELSE without IF", lineNum);
  827. return false;
  828. }
  829. }
  830. else
  831. {
  832. SubmitError("Invalid notation of single line ACT", lineNum);
  833. return false;
  834. }
  835. }
  836. else if (controlBlock == (int)ControlBlockType.SL_If)
  837. {
  838. if (blockGroupStarted)
  839. {
  840. blockGroupCompleted = true;
  841. }
  842. else if (groupInnerCounter == 0)
  843. {
  844. SubmitError("After single line IF has to be any operators before ELSE", lineNum);
  845. return false;
  846. }
  847. }
  848. else
  849. {
  850. SubmitError("ELSE without IF", lineNum);
  851. return false;
  852. }
  853. //Это правильный ELSE
  854. if (blockStartPos + block.Length < line.Length)
  855. {
  856. string restLine = line.Substring(blockStartPos + block.Length);
  857. if (restLine.Trim(WhiteSpace).StartsWith(":"))
  858. {
  859. pos += restLine.IndexOf(':') + 1;
  860. }
  861. }
  862. ControlStack.Pop();
  863. controlBlock = (int)ControlBlockType.SL_Else;
  864. groupInnerCounter = 0;
  865. }
  866. skip = true;
  867. }
  868. if (blockCode == (int)QspStatementType.End)
  869. {
  870. if (ControlStack.Count > 0)
  871. {
  872. ControlStack.Pop();
  873. if (ControlStack.Count > 0)
  874. {
  875. ControlLine cline = ControlStack.Peek();
  876. controlBlock = (int)cline.controlBlock;
  877. }
  878. else
  879. {
  880. controlBlock = (int)ControlBlockType.None;
  881. }
  882. }
  883. else
  884. {
  885. SubmitError("Redundant END", lineNum);
  886. return false;
  887. }
  888. skip = true;
  889. }
  890. if (!skip)
  891. {
  892. if (!blockGroupStarted)
  893. {
  894. blockGroupStarted = true;
  895. groupInnerCounter++;
  896. if (singleBlockGroup)
  897. {
  898. singleBlockGroup = false;
  899. blockGroupCompleted = true;
  900. }
  901. }
  902. if (quotedTextCompleted)
  903. {
  904. blockGroup.Add(quotedText);
  905. blockInGroupIsText.Add(true);
  906. quotedTextCompleted = false;
  907. }
  908. else
  909. {
  910. if ((blockCode == (int)QspStatementType.Unknown) && (block.Length > 1))
  911. {
  912. //Обрабатываем попытки "склеить" некоторые последовательности символов
  913. string first = block.Substring(0, 1);
  914. if (first.Equals("*"))
  915. {
  916. //Если была неудачная попытка прочесть *NL, *P, и т.д., "разделяем" блок на части
  917. blockGroup.Add(first);
  918. blockInGroupIsText.Add(false);
  919. block = block.Substring(1);
  920. }
  921. }
  922. blockGroup.Add(block);
  923. blockInGroupIsText.Add(false);
  924. }
  925. if (appendDelimiter)
  926. {
  927. blockGroup.Add(delimiterToAppend);
  928. blockInGroupIsText.Add(false);
  929. }
  930. if (blockGroupStarted && (pos == line.Length - 1))
  931. {
  932. blockGroupCompleted = true;
  933. }
  934. }
  935. block = "";
  936. blockCompleted = false;
  937. blockStarted = false;
  938. }
  939. if (blockGroupCompleted)
  940. {
  941. //Разбор аргументов
  942. if (blockGroup.Count == 0)
  943. {
  944. SubmitError("Internal error of the analyzer! Empty block!", lineNum);
  945. return false;
  946. }
  947. if (!CheckBlockGroup(blockGroup, blockInGroupIsText))
  948. return false;
  949. blockGroup.Clear();
  950. blockInGroupIsText.Clear();
  951. blockGroupStarted = false;
  952. blockGroupCompleted = false;
  953. }
  954. pos++;
  955. }
  956. //Строка закончилась
  957. if (bracketLevel>0)
  958. {
  959. SubmitError("Redundant bracket \"(\"", lineNum);
  960. return false;
  961. }
  962. if (controlBlock == (int)ControlBlockType.IfCondition)
  963. {
  964. SubmitError("IF without \":\"", lineNum);
  965. return false;
  966. }
  967. if (controlBlock == (int)ControlBlockType.ActCondition)
  968. {
  969. SubmitError("ACT without \":\"", lineNum);
  970. return false;
  971. }
  972. if ((controlBlock == (int)ControlBlockType.SL_Act) || (controlBlock == (int)ControlBlockType.SL_If) || (controlBlock == (int)ControlBlockType.SL_Else))
  973. {
  974. if (groupInnerCounter > 0)
  975. {
  976. while ((ControlStack.Count > 0) && (ControlStack.Peek().controlBlock == ControlBlockType.SL_If))
  977. ControlStack.Pop();
  978. if (ControlStack.Count > 0)
  979. {
  980. ControlLine cline = ControlStack.Peek();
  981. controlBlock = (int)cline.controlBlock;
  982. }
  983. else
  984. {
  985. controlBlock = (int)ControlBlockType.None;
  986. }
  987. }
  988. else if (controlBlock == (int)ControlBlockType.SL_Act)
  989. {
  990. SubmitError("Invalid notation of single line ACT", lineNum);
  991. return false;
  992. }
  993. else if (controlBlock == (int)ControlBlockType.SL_If)
  994. {
  995. SubmitError("Invalid notation of single line IF", lineNum);
  996. return false;
  997. }
  998. else if (controlBlock == (int)ControlBlockType.SL_Else)
  999. {
  1000. SubmitError("In single line IF has to be any operators after ELSE", lineNum);
  1001. return false;
  1002. }
  1003. }
  1004. //для отладки
  1005. if (line.Length > 0)
  1006. {
  1007. debugText += Environment.NewLine;
  1008. }
  1009. if (currentRoot)
  1010. {
  1011. //Вычисляем уровень вложенности(для утилиты форматирования кода)
  1012. int stackSize = ControlStack.Count;
  1013. int level = 0;
  1014. if (stackSize > 0)
  1015. {
  1016. endIndentLevel = stackSize;
  1017. ControlLine cline = ControlStack.Peek();
  1018. int b = (int)cline.controlBlock;
  1019. bool openingLine = cline.line == currentLine;
  1020. if (openingLine && ((b == (int)ControlBlockType.ML_Act) || (b == (int)ControlBlockType.ML_If)))
  1021. {
  1022. level = startIndentLevel;
  1023. }
  1024. else if (openingLine && (b == (int)ControlBlockType.ML_Else))
  1025. {
  1026. level = startIndentLevel - 1;
  1027. }
  1028. else
  1029. {
  1030. level = endIndentLevel;
  1031. }
  1032. }
  1033. location_codeline_level.Add(currentLine, level);
  1034. }
  1035. }
  1036. //Проверка на незакрытые в конце локации многострочные IF и ACT
  1037. if (ControlStack.Count > 0)
  1038. {
  1039. ControlLine cline = ControlStack.Pop();
  1040. if ((cline.controlBlock == ControlBlockType.ML_If) || (cline.controlBlock == ControlBlockType.ML_Else))
  1041. {
  1042. SubmitError("Multi line IF without END", cline.line);
  1043. return false;
  1044. }
  1045. else
  1046. {
  1047. SubmitError("Multi line ACT without END", cline.line);
  1048. return false;
  1049. }
  1050. }
  1051. AddLocationLink(m_name, true, m_start);
  1052. return true;
  1053. }
  1054. bool CheckBlockGroup(List<string> blockGroup, List<bool> blockInGroupIsText)
  1055. {
  1056. //Разбор аргументов для операторов ACT, IF, прочих операторов и функций.
  1057. string pomvarstr1;
  1058. string pomvarstr2;
  1059. bool iifpresent;
  1060. int blockCode = qspGetStatCode(blockGroup.ToArray()[0]);
  1061. if (blockInGroupIsText[0])
  1062. blockCode = (int)QspStatementType.Unknown;
  1063. bool isSetOp = blockCode == (int)QspStatementType.Set;
  1064. if ((blockCode == (int)QspStatementType.Unknown) || isSetOp)
  1065. {
  1066. //Это присваивание?
  1067. int setpos = FindInTopBracketLevel(blockGroup, blockInGroupIsText, "=");
  1068. if (setpos == INVALID_INDEX)
  1069. setpos = FindInTopBracketLevel(blockGroup, blockInGroupIsText, "+=");
  1070. if (setpos == INVALID_INDEX)
  1071. setpos = FindInTopBracketLevel(blockGroup, blockInGroupIsText, "-=");
  1072. if (isSetOp && (setpos == INVALID_INDEX))
  1073. {
  1074. SubmitError("Not found the char \"=\"", currentLine);
  1075. return false;
  1076. }
  1077. if (setpos != INVALID_INDEX)
  1078. {
  1079. //Присваивание
  1080. if ((setpos == 0) || (isSetOp && (setpos == 1)))
  1081. {
  1082. SubmitError("The name of a variable before the character \"=\" is not specified!", currentLine);
  1083. return false;
  1084. }
  1085. int last = blockGroup.Count - 1;
  1086. if (setpos==last)
  1087. {
  1088. SubmitError("It should be a value after char \"=\"", currentLine);
  1089. return false;
  1090. }
  1091. //Проверяем левую часть
  1092. int start = 0;
  1093. if (isSetOp)
  1094. start = 1;
  1095. int count = setpos - start;
  1096. List<string> args = new List<string>();
  1097. List<bool> types = new List<bool>();
  1098. args = blockGroup.GetRange(start, count);
  1099. types = blockInGroupIsText.GetRange(start, count);
  1100. if (!CheckLeftAssign(args, types))
  1101. return false;
  1102. string assignedVarName = args[0];
  1103. //Проверяем правую часть
  1104. start = setpos + 1;
  1105. count = last - start + 1;
  1106. args = blockGroup.GetRange(start, count);
  1107. types = blockInGroupIsText.GetRange(start, count);
  1108. if (!CheckExpression(args, types))
  1109. return false;
  1110. //Засчитываем присваивание некоторым переменным как обращение к локации
  1111. if ((count == 1) && types[0] && ListContainsIgnoreCase(callerVariables, assignedVarName))
  1112. {
  1113. AddLocationLink(args[0], false, true);
  1114. }
  1115. }
  1116. else
  1117. {
  1118. //Если оператор неизвестен, пытаемся разобрать выражение
  1119. if (!CheckExpression(blockGroup, blockInGroupIsText))
  1120. return false;
  1121. //Разбираем код в ссылках <a href="EXEC:GOTO 'loc1'">
  1122. if ((blockGroup.Count >= 1) && (blockInGroupIsText[0]))
  1123. {
  1124. pomvarstr1 = "";
  1125. pomvarstr2 = "";
  1126. iifpresent = false;
  1127. for (int ibc = 0; ibc < blockGroup.Count; ibc++)
  1128. {
  1129. if (blockGroup[Math.Min(ibc + 1, blockGroup.Count-1)] != "iif")
  1130. {
  1131. pomvarstr1 = pomvarstr1 + blockGroup[ibc];
  1132. pomvarstr2 = pomvarstr2 + blockGroup[ibc];
  1133. }
  1134. else
  1135. {
  1136. iifpresent = true;
  1137. while (blockGroup[ibc] != ",")
  1138. {
  1139. ibc++;
  1140. }
  1141. ibc++;
  1142. pomvarstr1 = pomvarstr1 + blockGroup[ibc];
  1143. ibc++;
  1144. ibc++;
  1145. pomvarstr2 = pomvarstr2 + blockGroup[ibc];
  1146. ibc++;
  1147. ibc++;
  1148. }
  1149. }
  1150. ParseExecInOutputText(pomvarstr1);
  1151. if (iifpresent)
  1152. ParseExecInOutputText(pomvarstr2);
  1153. }
  1154. }
  1155. }
  1156. else if ((blockCode == (int)QspStatementType.If) || (blockCode == (int)QspStatementType.ElseIf))
  1157. {
  1158. int start = 1;
  1159. int count = blockGroup.Count - 1;
  1160. if (count > 0)
  1161. {
  1162. List<string> args = blockGroup.GetRange(start, count);
  1163. List<bool> types = blockInGroupIsText.GetRange(start, count);
  1164. if (!CheckExpression(args, types))
  1165. return false;
  1166. }
  1167. else
  1168. {
  1169. if (blockCode == (int)QspStatementType.If)
  1170. {
  1171. SubmitError("Operator IF without condition", currentLine);
  1172. }
  1173. else
  1174. {
  1175. SubmitError("Operator ELSEIF without condition", currentLine);
  1176. }
  1177. return false;
  1178. }
  1179. }
  1180. else
  1181. {
  1182. //Если оператор известен, проверяем его аргументы.
  1183. int count = blockGroup.Count - 1;
  1184. List<string> args = new List<string>();
  1185. List<bool> types = new List<bool>();
  1186. if (count > 0)
  1187. {
  1188. args = blockGroup.GetRange(1, count);
  1189. types = blockInGroupIsText.GetRange(1, count);
  1190. }
  1191. if (!CheckStatementArgs(blockCode, args, types))
  1192. return false;
  1193. }
  1194. //Проверяем подвыражения вида <<$var>> в любых строках
  1195. for (int i = 0; i < blockGroup.Count; i++)
  1196. {
  1197. if (blockInGroupIsText[i])
  1198. {
  1199. if (!ParseSubExpressions(blockGroup[i]))
  1200. return false;
  1201. }
  1202. }
  1203. return true;
  1204. }
  1205. bool CheckStatementArgs(int code, List<string> argsSrc, List<bool> typesSrc)
  1206. {
  1207. int count = argsSrc.Count;
  1208. List<string> args = new List<string>();
  1209. List<bool> types = new List<bool>();
  1210. if (count > 0)
  1211. {
  1212. if ((count > 1) && argsSrc.ToArray()[0].Equals("(") && !typesSrc.ToArray()[0] &&
  1213. argsSrc.ToArray()[count - 1].Equals(")") && !typesSrc.ToArray()[count - 1])
  1214. {
  1215. //Игнорируем одну пару скобок по краям
  1216. args = argsSrc.GetRange(1, count - 2);
  1217. types = typesSrc.GetRange(1, count - 2);
  1218. }
  1219. else
  1220. {
  1221. args = argsSrc.GetRange(0, count);
  1222. types = typesSrc.GetRange(0, count);
  1223. }
  1224. }
  1225. count = args.Count;
  1226. if ((count >= 1) && types[0])
  1227. {
  1228. //Отмечаем в списке явные ссылки на локации
  1229. if ((code == (int)QspStatementType.GoSub) || (code == (int)QspStatementType.GoTo) ||
  1230. (code == (int)QspStatementType.XGoTo))
  1231. {
  1232. AddLocationLink(args[0], false, true);
  1233. }
  1234. //Разбираем код в ссылках <a href="EXEC:GOTO 'loc1'">
  1235. else if ((code == (int)QspStatementType.P) || (code == (int)QspStatementType.PL) ||
  1236. (code == (int)QspStatementType.NL) || (code == (int)QspStatementType.MP) ||
  1237. (code == (int)QspStatementType.MPL) || (code == (int)QspStatementType.MNL))
  1238. {
  1239. ParseExecInOutputText(args[0]);
  1240. }
  1241. //Отмечаем в списке добавленные предметы
  1242. else if (code == (int)QspStatementType.AddObj)
  1243. {
  1244. AddObj(args[0], true, false);
  1245. }
  1246. //Отмечаем в списке удаленные предметы
  1247. else if (code == (int)QspStatementType.DelObj)
  1248. {
  1249. AddObj(args[0], false, true);
  1250. }
  1251. //Отмечаем в списке добавленные действия
  1252. else if (code == (int)QspStatementType.Act)
  1253. {
  1254. AddAct(args[0], true, false);
  1255. }
  1256. //Отмечаем в списке удаленные действия
  1257. else if (code == (int)QspStatementType.DelAct)
  1258. {
  1259. AddAct(args[0], false, true);
  1260. }
  1261. }
  1262. int minArgCount = qspStats[code].MinArgsCount;
  1263. int maxArgCount = qspStats[code].MaxArgsCount;
  1264. int argCount = 0;
  1265. int curIndex = 0;
  1266. List<string> expr = new List<string>();
  1267. if (count > 0)
  1268. {
  1269. while (true)
  1270. {
  1271. if (argCount == maxArgCount)
  1272. {
  1273. SubmitError("Too many arguments for the operator", currentLine);
  1274. return false;
  1275. }
  1276. int index = FindInTopBracketLevel(args, types, ",", curIndex);
  1277. if (index != INVALID_INDEX)
  1278. {
  1279. if (index > curIndex)
  1280. {
  1281. if (!CheckExpression(args.GetRange(curIndex, index - curIndex), types.GetRange(curIndex, index - curIndex)))
  1282. return false;
  1283. }
  1284. else
  1285. {
  1286. SubmitError("Argument can not be empty", currentLine);
  1287. return false;
  1288. }
  1289. }
  1290. else
  1291. {
  1292. if (!CheckExpression(args.GetRange(curIndex, count - curIndex), types.GetRange(curIndex, count - curIndex)))
  1293. return false;
  1294. }
  1295. argCount++;
  1296. if (index == INVALID_INDEX)
  1297. break;
  1298. curIndex = index + 1;
  1299. if (curIndex == count)
  1300. {
  1301. SubmitError("Argument can not be empty", currentLine);
  1302. return false;
  1303. }
  1304. }
  1305. }
  1306. if (argCount < minArgCount)
  1307. {
  1308. SubmitError("The operator requires more arguments", currentLine);
  1309. return false;
  1310. }
  1311. return true;
  1312. }
  1313. bool CheckExpression(List<string> args, List<bool> types)
  1314. {
  1315. //Проверка выражения
  1316. int[] opStack = new int[QSP_STACKSIZE];
  1317. int[] argStack = new int[QSP_STACKSIZE];
  1318. bool waitForOperator = false;
  1319. int opCode, itemsCount = 0, opSp = -1, argSp = -1;
  1320. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, (int)QspFunctionType.Start))
  1321. return false;
  1322. int argIndex = 0;
  1323. while (argIndex <= args.Count)
  1324. {
  1325. String s = "";
  1326. if (argIndex < args.Count)
  1327. s = args[argIndex];
  1328. if (waitForOperator)
  1329. {
  1330. opCode = qspGetFunctionCode(s, false);
  1331. String nextArg = "";
  1332. bool nextArgIsString = false;
  1333. bool hasNextArg = argIndex + 1 < args.Count;
  1334. if (hasNextArg)
  1335. {
  1336. nextArg = args[argIndex + 1];
  1337. nextArgIsString = types[argIndex + 1];
  1338. }
  1339. if (opCode == (int)QspFunctionType.Unknown || opCode >= (int)QspFunctionType.First_Function)
  1340. {
  1341. SubmitError("Unknown action in the expression", currentLine);
  1342. break;
  1343. }
  1344. if (((opCode == (int)QspFunctionType.And) || (opCode == (int)QspFunctionType.Or) || (opCode == (int)QspFunctionType.Mod)) &&
  1345. !(hasNextArg && (nextArgIsString || nextArg.Equals("(") || (nextArg.IndexOfAny(Delimiters) == INVALID_INDEX)))
  1346. )
  1347. {
  1348. SubmitError("Syntax error", currentLine);
  1349. break;
  1350. }
  1351. bool bError = false;
  1352. while (qspOps[opCode].Priority <= qspOps[opStack[opSp]].Priority && qspOps[opStack[opSp]].Priority != 127)
  1353. {
  1354. if (opStack[opSp] >= (int)QspFunctionType.First_Function) ++argStack[argSp];
  1355. if (!qspAppendToCompiled(ref itemsCount))
  1356. {
  1357. bError = true;
  1358. break;
  1359. }
  1360. if (--opSp < 0 || --argSp < 0)
  1361. {
  1362. SubmitError("Syntax error", currentLine);
  1363. bError = true;
  1364. break;
  1365. }
  1366. }
  1367. if (bError)
  1368. break;
  1369. switch (opCode)
  1370. {
  1371. case (int)QspFunctionType.End:
  1372. if (opSp > 0)
  1373. {
  1374. SubmitError("Closing bracket not found", currentLine);
  1375. bError = true;
  1376. break;
  1377. }
  1378. return itemsCount > 0;
  1379. case (int)QspFunctionType.CloseBracket:
  1380. if (opStack[opSp] != (int)QspFunctionType.OpenBracket)
  1381. {
  1382. SubmitError("Opening bracket not found", currentLine);
  1383. bError = true;
  1384. break;
  1385. }
  1386. opCode = opStack[--opSp];
  1387. if (opCode >= (int)QspFunctionType.First_Function)
  1388. {
  1389. if (argStack[argSp] + 1 < qspOps[opCode].MinArgsCount || argStack[argSp] + 1 > qspOps[opCode].MaxArgsCount)
  1390. {
  1391. SubmitError("Invalid number of arguments", currentLine);
  1392. bError = true;
  1393. }
  1394. }
  1395. else
  1396. --argSp;
  1397. break;
  1398. case (int)QspFunctionType.Comma:
  1399. if ((opSp > 0) && opStack[opSp - 1] >= (int)QspFunctionType.First_Function)
  1400. {
  1401. if (++argStack[argSp] > qspOps[opStack[opSp - 1]].MaxArgsCount)
  1402. {
  1403. SubmitError("Invalid number of arguments", currentLine);
  1404. bError = true;
  1405. break;
  1406. }
  1407. }
  1408. else
  1409. {
  1410. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, (int)QspFunctionType.Comma))
  1411. {
  1412. bError = true;
  1413. break;
  1414. }
  1415. }
  1416. waitForOperator = false;
  1417. break;
  1418. default:
  1419. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, opCode))
  1420. {
  1421. bError = true;
  1422. break;
  1423. }
  1424. waitForOperator = false;
  1425. break;
  1426. }
  1427. if (bError)
  1428. break;
  1429. }
  1430. else
  1431. {
  1432. if ((argIndex < args.Count) && !types[argIndex] && IsNumber(s))
  1433. {
  1434. if (opStack[opSp] == (int)QspFunctionType.Minus)
  1435. {
  1436. --opSp;
  1437. --argSp;
  1438. }
  1439. if (!qspAppendToCompiled(ref itemsCount))
  1440. break;
  1441. waitForOperator = true;
  1442. }
  1443. // I added this piece of code (next 7 lines) so the program could detect function call and the first argument -name of the function / location
  1444. // I do not assure that I did it in a proper place, but it seems that it works.
  1445. else if ((opStack[1] == (int)QspFunctionType.Func) && (argIndex == 2))
  1446. {
  1447. AddLocationLink(s, false, true);
  1448. }
  1449. else if ((opStack[1] == (int)QspFunctionType.Func) && (argIndex == 3) && (s == ","))
  1450. {
  1451. }
  1452. else if ((argIndex < args.Count) && types[argIndex])
  1453. {
  1454. if (!qspAppendToCompiled(ref itemsCount))
  1455. break;
  1456. waitForOperator = true;
  1457. }
  1458. else if (s.Equals("+"))
  1459. {
  1460. }
  1461. else if (s.Equals("-"))
  1462. {
  1463. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, (int)QspFunctionType.Minus))
  1464. break;
  1465. }
  1466. else if (s.Equals("("))
  1467. {
  1468. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, (int)QspFunctionType.OpenBracket))
  1469. break;
  1470. }
  1471. else if (s.Equals(")"))
  1472. {
  1473. opCode = opStack[opSp];
  1474. if (opCode != (int)QspFunctionType.OpenBracket)
  1475. {
  1476. if (opCode >= (int)QspFunctionType.First_Function)
  1477. SubmitError("Invalid number of arguments", currentLine);
  1478. else
  1479. SubmitError("Syntax error", currentLine);
  1480. break;
  1481. }
  1482. opCode = opStack[--opSp];
  1483. if (opCode < (int)QspFunctionType.First_Function)
  1484. {
  1485. SubmitError("Syntax error", currentLine);
  1486. break;
  1487. }
  1488. if (qspOps[opCode].MinArgsCount > argSp)
  1489. {
  1490. SubmitError("Invalid number of arguments", currentLine);
  1491. break;
  1492. }
  1493. if (!qspAppendToCompiled(ref itemsCount))
  1494. break;
  1495. --opSp;
  1496. --argSp;
  1497. waitForOperator = true;
  1498. }
  1499. else if ((argIndex < args.Count) && s.IndexOfAny(Delimiters) != 0)
  1500. {
  1501. if (s.IndexOfAny(Delimiters) != INVALID_INDEX)
  1502. {
  1503. SubmitError("Internal error of the analyzer: Invalid characters in the variable name", currentLine);
  1504. break;
  1505. }
  1506. opCode = qspGetFunctionCode(s, true);
  1507. if (opCode >= (int)QspFunctionType.First_Function)
  1508. {
  1509. if ((args.Count - argIndex > 1) && (args[argIndex + 1].Equals("(") && !types[argIndex + 1]))
  1510. {
  1511. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, opCode))
  1512. break;
  1513. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, (int)QspFunctionType.OpenBracket))
  1514. break;
  1515. argIndex++;
  1516. --argSp;
  1517. }
  1518. else if (qspOps[opCode].MinArgsCount < 2)
  1519. {
  1520. if (qspOps[opCode].MinArgsCount > 0)
  1521. {
  1522. if (!qspCompileExprPushOpCode(ref opStack, ref opSp, ref argStack, ref argSp, opCode))
  1523. break;
  1524. }
  1525. else
  1526. {
  1527. if (!qspAppendToCompiled(ref itemsCount))
  1528. break;
  1529. waitForOperator = true;
  1530. }
  1531. }
  1532. else
  1533. {
  1534. SubmitError("Brackets not found", currentLine);
  1535. break;
  1536. }
  1537. }
  1538. else
  1539. {
  1540. int optArgsCount = 0;
  1541. //Проверяем выражение(индекс массива)
  1542. if ((args.Count - argIndex > 1) && (args[argIndex + 1].Equals("[") && !types[argIndex + 1]))
  1543. {
  1544. int optIndex = argIndex + 2;
  1545. int level = 1;
  1546. bool bFound = false;
  1547. while (optIndex < args.Count)
  1548. {
  1549. if (args[optIndex].Equals("[") && !types[optIndex])
  1550. {
  1551. level++;
  1552. }
  1553. else if (args[optIndex].Equals("]") && !types[optIndex])
  1554. {
  1555. level--;
  1556. if (level == 0)
  1557. {
  1558. bFound = true;
  1559. break;
  1560. }
  1561. }
  1562. optIndex++;
  1563. }
  1564. if (level > 0)
  1565. {
  1566. SubmitError("Unclosed parenthesis \"[\"", currentLine);
  1567. break;
  1568. }
  1569. if (bFound)
  1570. optArgsCount = optIndex - argIndex;
  1571. }
  1572. List<string> subArgs = args.GetRange(argIndex, optArgsCount + 1);
  1573. List<bool> subTypes = types.GetRange(argIndex, optArgsCount + 1);
  1574. if (!CheckVariable(subArgs, subTypes, false))
  1575. break;
  1576. argIndex += optArgsCount;
  1577. if (!qspAppendToCompiled(ref itemsCount))
  1578. break;
  1579. waitForOperator = true;
  1580. }
  1581. }
  1582. else
  1583. {
  1584. if (opStack[opSp] >= (int)QspFunctionType.First_Function)
  1585. SubmitError("Invalid number of arguments", currentLine);
  1586. else
  1587. SubmitError("Syntax error", currentLine);
  1588. break;
  1589. }
  1590. }
  1591. argIndex++;
  1592. }
  1593. return false;
  1594. }
  1595. bool CheckVariable(List<string> args, List<bool> types, bool assignment)
  1596. {
  1597. //Проверка имени переменной
  1598. if ((args.Count == 0) || (args[0].Length == 0) || types[0])
  1599. {
  1600. SubmitError("Internal error of the analyzer: empty name of variable!", currentLine);
  1601. return false;
  1602. }
  1603. string name = args[0];
  1604. int code1 = qspGetStatCode(name);
  1605. int code2 = qspGetFunctionCode(name, true);
  1606. if ((code1 != (int)QspStatementType.Unknown) || (code2 != (int)QspFunctionType.Unknown))
  1607. {
  1608. SubmitError("QSP Keyword \"" + name + "\" cannot be used as a variable name", currentLine);
  1609. return false;
  1610. }
  1611. //Проверяем имя переменной на валидность
  1612. //В имени переменной разрешены все символы, кроме DELIMS и цифры в начале имени
  1613. //Перед именем переменной может находиться префикс "$"
  1614. string checkName = name;
  1615. if (checkName.StartsWith("$"))
  1616. checkName = checkName.Substring(1);
  1617. // $ =
  1618. if (checkName.Length == 0)
  1619. {
  1620. SubmitError("Invalid variable name \"" + name + "\"", currentLine);
  1621. return false;
  1622. }
  1623. // 1asd =
  1624. if (checkName.Substring(0, 1).IndexOfAny(Digits) != INVALID_INDEX)
  1625. {
  1626. SubmitError("Variable name \"" + name + "\" cannot start with a digit", currentLine);
  1627. return false;
  1628. }
  1629. // /asd =
  1630. if (checkName.IndexOfAny(Delimiters) != INVALID_INDEX)
  1631. {
  1632. SubmitError("Invalid symbols in the name of the variable \"" + name + "\"", currentLine);
  1633. return false;
  1634. }
  1635. //Проверяем переменную на "смешанные раскладки"
  1636. if ((checkName.IndexOfAny(LatinLetters) != INVALID_INDEX) && (checkName.IndexOfAny(RussianLetters) != INVALID_INDEX))
  1637. {
  1638. SubmitWarning("English and Russian symbols are used simultaneously in the name of varible \"" + name + "\" , possibly a typo", currentLine);
  1639. }
  1640. //Проверяем выражение(индекс массива)
  1641. if (args.Count > 1)
  1642. {
  1643. if (args.Count > 2 && args[1].Equals("[") && !types[1] &&
  1644. args[args.Count - 1].Equals("]") && !types[args.Count - 1])
  1645. {
  1646. int start = 2;
  1647. int count = args.Count - 3;
  1648. if (count > 0)
  1649. {
  1650. List<string> argsCut = args.GetRange(start, count);
  1651. List<bool> typesCut = types.GetRange(start, count);
  1652. if (!CheckExpression(argsCut, typesCut))
  1653. return false;
  1654. }
  1655. }
  1656. else
  1657. {
  1658. SubmitError("Invalid expression", currentLine);
  1659. return false;
  1660. }
  1661. }
  1662. //Сохраняем имя переменной в глобальном списке
  1663. if (!assignment)
  1664. {
  1665. bool usedBySystem = ListContainsIgnoreCase(systemVariables, name);
  1666. AddVar(name, usedBySystem, true);
  1667. }
  1668. return true;
  1669. }
  1670. bool CheckLeftAssign(List<string> args, List<bool> types)
  1671. {
  1672. //Проверка имени переменной(слева от знака "=" в операции присваивания)
  1673. if ((args.Count == 0) || (args[0].Length == 0) || types[0])
  1674. {
  1675. //Текстовая строка
  1676. SubmitError("Name of the variable should be before char \"=\" in the assignment operation", currentLine);
  1677. return false;
  1678. }
  1679. if (!CheckVariable(args, types, true))
  1680. return false;
  1681. //Сохраняем имя переменной в глобальном списке
  1682. bool usedBySystem = ListContainsIgnoreCase(systemVariables, args[0]);
  1683. AddVar(args[0], true, usedBySystem);
  1684. return true;
  1685. }
  1686. int FindInTopBracketLevel(List<string> args, List<bool> types, string what)
  1687. {
  1688. return FindInTopBracketLevel(args, types, what, 0);
  1689. }
  1690. int FindInTopBracketLevel(List<string> args, List<bool> types, string what, int startIndex)
  1691. {
  1692. //Ищем знак "=" или запятую вне скобок
  1693. int bracketLevel = 0;
  1694. for (int i = startIndex; i < args.Count; i++)
  1695. {
  1696. if (types[i])
  1697. continue;
  1698. string block = args[i];
  1699. if (block.Equals("("))
  1700. {
  1701. bracketLevel++;
  1702. }
  1703. else if (block.Equals(")"))
  1704. {
  1705. bracketLevel--;
  1706. }
  1707. else if (block.Equals(what) && (bracketLevel == 0))
  1708. {
  1709. return i;
  1710. }
  1711. }
  1712. return INVALID_INDEX;
  1713. }
  1714. void ParseExecInOutputText(string text)
  1715. {
  1716. //Разбираем код в ссылках <a href="EXEC:GOTO 'loc1'">
  1717. int pos = 0;
  1718. //Строим "карту" подвыражений.
  1719. //Если подвыражения в строке содержат ошибки, то разбирать теги нет смысла.
  1720. List<int> subExpMap = new List<int>();
  1721. if (!ParseSubExpressions(text, ref subExpMap))
  1722. return;
  1723. int subExpSkipped = 0;
  1724. while (pos < text.Length)
  1725. {
  1726. pos = text.IndexOf("<a", pos);
  1727. if (pos == INVALID_INDEX)
  1728. break;
  1729. if (subExpMap.Count / 2 > subExpSkipped)
  1730. {
  1731. int subExpStartPos = subExpMap[subExpSkipped * 2];
  1732. int subExpEndPos = subExpMap[subExpSkipped * 2 + 1];
  1733. if (subExpStartPos == pos)
  1734. {
  1735. //Пропускаем подвыражения вне тегов
  1736. subExpSkipped++;
  1737. pos = subExpEndPos + 1;
  1738. continue;
  1739. }
  1740. }
  1741. //Разбираем содержимое угловых скобок
  1742. //Внутри HTML-тега кавычки экранируются не через дублирование, как в QSP, а через "\",
  1743. //причем экранирование требуется только внутри окавыченной строки.
  1744. List<string> blockGroup = new List<string>();
  1745. List<bool> blockInGroupIsText = new List<bool>();
  1746. int firstBlockPosition = INVALID_INDEX;
  1747. string quotedText = "";
  1748. string block = "";
  1749. bool tagClosed = false;
  1750. bool quotedTextCompleted = false;
  1751. bool blockCompleted = false;
  1752. pos++;
  1753. int startPos = pos;
  1754. if ((pos < text.Length) && (text[pos] == '/'))
  1755. startPos++;
  1756. int tagQuote = (int)QuoteType.None;
  1757. while (!tagClosed && (pos < text.Length))
  1758. {
  1759. if (subExpMap.Count / 2 > subExpSkipped)
  1760. {
  1761. int subExpStartPos = subExpMap[subExpSkipped * 2];
  1762. int subExpEndPos = subExpMap[subExpSkipped * 2 + 1];
  1763. if (subExpStartPos == pos)
  1764. {
  1765. //Пропускаем подвыражения вне тегов
  1766. subExpSkipped++;
  1767. string subExpText = text.Substring(pos, subExpEndPos - pos + 1);
  1768. if (tagQuote == (int)QuoteType.None)
  1769. block += subExpText;
  1770. else
  1771. quotedText += subExpText;
  1772. pos = subExpEndPos + 1;
  1773. continue;
  1774. }
  1775. }
  1776. char c2 = text[pos];
  1777. if (tagQuote != (int)QuoteType.None)
  1778. {
  1779. //Апостроф либо кавычка
  1780. if (((tagQuote == (int)QuoteType.Single) && (c2 == '\'')) ||
  1781. ((tagQuote == (int)QuoteType.Double) && (c2 == '"')))
  1782. {
  1783. if ((pos - 1 > 0) && (text[pos - 1] == '\\'))
  1784. {
  1785. //Экранированный апостроф либо кавычка
  1786. if (!quotedTextCompleted)
  1787. quotedText = quotedText.Substring(0, quotedText.Length - 1) + c2;
  1788. }
  1789. else
  1790. {
  1791. tagQuote = (int)QuoteType.None;
  1792. quotedTextCompleted = true;
  1793. }
  1794. }
  1795. else if (!quotedTextCompleted)
  1796. {
  1797. quotedText += c2;
  1798. }
  1799. }
  1800. else if (c2 == '>')
  1801. {
  1802. tagClosed = true;
  1803. }
  1804. else if ((block.Length == 0) && (c2 == '\''))
  1805. {
  1806. tagQuote = (int)QuoteType.Single;
  1807. if (text[pos + 1] == '\'')
  1808. {
  1809. pos++;
  1810. }
  1811. }
  1812. else if ((block.Length == 0) && (c2 == '"'))
  1813. {
  1814. tagQuote = (int)QuoteType.Double;
  1815. }
  1816. else if (c2.ToString().IndexOfAny(WhiteSpace) == 0)
  1817. {
  1818. if (block.Length > 0)
  1819. {
  1820. blockCompleted = true;
  1821. }
  1822. }
  1823. else if (c2 == '=')
  1824. {
  1825. if (block.Length > 0)
  1826. {
  1827. blockGroup.Add(block);
  1828. blockInGroupIsText.Add(false);
  1829. }
  1830. block = "=";
  1831. blockCompleted = true;
  1832. }
  1833. else
  1834. {
  1835. if (firstBlockPosition == INVALID_INDEX)
  1836. {
  1837. firstBlockPosition = pos - startPos;
  1838. }
  1839. block += c2;
  1840. }
  1841. if (tagClosed)
  1842. {
  1843. if (block.Length > 0)
  1844. blockCompleted = true;
  1845. }
  1846. if (blockCompleted)
  1847. {
  1848. blockGroup.Add(block);
  1849. blockInGroupIsText.Add(false);
  1850. blockCompleted = false;
  1851. block = "";
  1852. }
  1853. if (quotedTextCompleted)
  1854. {
  1855. blockGroup.Add(quotedText);
  1856. blockInGroupIsText.Add(true);
  1857. quotedTextCompleted = false;
  1858. quotedText = "";
  1859. }
  1860. pos++;
  1861. }
  1862. if (tagQuote == (int)QuoteType.Single)
  1863. {
  1864. SubmitWarning("Unclosed apostrophe inside the tag", currentLine);
  1865. break;
  1866. }
  1867. else if (tagQuote == (int)QuoteType.Double)
  1868. {
  1869. SubmitWarning("Unclosed quote inside the tag", currentLine);
  1870. break;
  1871. }
  1872. if (!tagClosed)
  1873. {
  1874. SubmitWarning("Unclosed tag",currentLine);
  1875. break;
  1876. }
  1877. if (firstBlockPosition > 0)
  1878. {
  1879. SubmitWarning("The name of the tag should follow immediately after the opening angle bracket, without spaces", currentLine);
  1880. break;
  1881. }
  1882. //Ищем HREF в атрибутах тега A
  1883. int hrefIndex = INVALID_INDEX;
  1884. if ((blockGroup.Count > 3) && (blockGroup[0].Equals("A", StringComparison.OrdinalIgnoreCase)) && !blockInGroupIsText[0])
  1885. {
  1886. for (int i = 1; i + 2 < blockGroup.Count; i++)
  1887. {
  1888. if (blockGroup[i].Equals("HREF", StringComparison.OrdinalIgnoreCase) && !blockInGroupIsText[i] &&
  1889. blockGroup[i + 1].Equals("=") && !blockInGroupIsText[i + 1])
  1890. {
  1891. hrefIndex = i + 2;
  1892. }
  1893. }
  1894. }
  1895. if (hrefIndex != INVALID_INDEX)
  1896. {
  1897. string hrefText = blockGroup[hrefIndex];
  1898. int execKeywordLength = "EXEC:".Length;
  1899. if (hrefText.StartsWith("EXEC:", StringComparison.OrdinalIgnoreCase) && (hrefText.Length > execKeywordLength))
  1900. {
  1901. string execText = hrefText.Substring(execKeywordLength);
  1902. List<int> subExpMapExec = new List<int>();
  1903. ParseSubExpressions(execText, ref subExpMapExec);
  1904. if (subExpMapExec.Count == 0)
  1905. {
  1906. //В EXEC не разбираем код с подвыражениями, это невозможно без интерпретации
  1907. List<string> tagLines = new List<string>(execText.Split('\n'));
  1908. bool wasRoot = currentRoot;
  1909. currentRoot = false;
  1910. ParseLocation(tagLines, currentRoot);
  1911. currentRoot = wasRoot;
  1912. }
  1913. }
  1914. }
  1915. }
  1916. }
  1917. bool ParseSubExpressions(string text)
  1918. {
  1919. List<int> dummy = null;
  1920. return ParseSubExpressions(text, ref dummy);
  1921. }
  1922. bool ParseSubExpressions(string text, ref List<int> subExpMap)
  1923. {
  1924. bool quiet = subExpMap != null;
  1925. //Разбираем подвыражения - <<$var>>
  1926. if (quiet)
  1927. subExpMap.Clear();
  1928. int pos = 0;
  1929. bool valid = true;
  1930. while (valid && pos < text.Length)
  1931. {
  1932. pos = text.IndexOf("<<", pos);
  1933. if (pos == INVALID_INDEX)
  1934. break;
  1935. if (quiet)
  1936. subExpMap.Add(pos);
  1937. //Разбираем содержимое двойных угловых скобок
  1938. string subText = "";
  1939. bool subClosed = false;
  1940. pos += 2;
  1941. int subQuote = (int)QuoteType.None;
  1942. int curlyLevel = 0;
  1943. while (pos < text.Length)
  1944. {
  1945. char c2 = text[pos];
  1946. if (subQuote == (int)QuoteType.None)
  1947. {
  1948. if ((c2 == '>') && (pos + 1 < text.Length) && (text[pos + 1] == '>') && (curlyLevel == 0))
  1949. {
  1950. subClosed = true;
  1951. break;
  1952. }
  1953. else if (c2 == '\'')
  1954. {
  1955. subQuote = (int)QuoteType.Single;
  1956. }
  1957. else if (c2 == '"')
  1958. {
  1959. subQuote = (int)QuoteType.Double;
  1960. }
  1961. else if (c2 == '{')
  1962. {
  1963. curlyLevel++;
  1964. }
  1965. else if (c2 == '}')
  1966. {
  1967. curlyLevel--;
  1968. }
  1969. }
  1970. else if (((subQuote == (int)QuoteType.Single) && (c2 == '\'')) ||
  1971. ((subQuote == (int)QuoteType.Double) && (c2 == '"')))
  1972. {
  1973. //Апостроф или кавычка
  1974. if ((pos + 1 < text.Length) && (
  1975. ((subQuote == (int)QuoteType.Single) && (text[pos + 1] == '\'')) ||
  1976. ((subQuote == (int)QuoteType.Double) && (text[pos + 1] == '"'))))
  1977. {
  1978. //Экранированный апостроф либо кавычка
  1979. }
  1980. else
  1981. {
  1982. subQuote = (int)QuoteType.None;
  1983. }
  1984. }
  1985. subText += c2;
  1986. pos++;
  1987. }
  1988. if (quiet)
  1989. {
  1990. if (subClosed)
  1991. subExpMap.Add(pos + 1);
  1992. else
  1993. subExpMap.Add(pos - 1);
  1994. }
  1995. if (subQuote == (int)QuoteType.Single)
  1996. {
  1997. if (!quiet)
  1998. SubmitError("Unclosed apostrophe in a subexpression", currentLine);
  1999. valid = false;
  2000. break;
  2001. }
  2002. else if (subQuote == (int)QuoteType.Double)
  2003. {
  2004. if (!quiet)
  2005. SubmitError("Unclosed quote in a subexpression", currentLine);
  2006. valid = false;
  2007. break;
  2008. }
  2009. else if (curlyLevel != 0)
  2010. {
  2011. if (!quiet)
  2012. SubmitError("Unclosed curly bracket in a subexpression", currentLine);
  2013. valid = false;
  2014. break;
  2015. }
  2016. if (!subClosed)
  2017. {
  2018. if (!quiet)
  2019. SubmitError("Unclosed subexpression", currentLine);
  2020. valid = false;
  2021. break;
  2022. }
  2023. if (subText.Trim(WhiteSpace).Length == 0)
  2024. {
  2025. if (!quiet)
  2026. SubmitError("Empty subexpression", currentLine);
  2027. valid = false;
  2028. break;
  2029. }
  2030. if (!quiet)
  2031. {
  2032. //Парсим подвыражение как исполняемый код.
  2033. //Для того, чтобы строка считалась именно выражением, добавляем ''+ в начало
  2034. subText = "''+" + subText;
  2035. List<string> subLines = new List<string>(subText.Split('\n'));
  2036. bool wasRoot = currentRoot;
  2037. currentRoot = false;
  2038. valid = ParseLocation(subLines, currentRoot);
  2039. currentRoot = wasRoot;
  2040. }
  2041. }
  2042. return valid;
  2043. }
  2044. }
  2045. public class QSPGameCode : Common
  2046. {
  2047. Hashtable m_LocationsByName;
  2048. List<Location> m_LocationsByOrder;
  2049. Location m_lastLocation;
  2050. public QSPGameCode()
  2051. {
  2052. m_LocationsByName = new Hashtable();
  2053. m_LocationsByOrder = new List<Location>();
  2054. m_lastLocation = null;
  2055. }
  2056. public bool ParseGame(string fileName, object sender, DoWorkEventArgs e)
  2057. {
  2058. int totalLines = 0;
  2059. StreamReader rTl = new StreamReader(fileName);
  2060. while (rTl.ReadLine() != null) { totalLines++; };
  2061. m_LocationsByName.Clear();
  2062. m_LocationsByOrder.Clear();
  2063. ClearErrors();
  2064. m_lastLocation = null;
  2065. currentLocation = "";
  2066. vars = new List<QspVariable>();
  2067. locationLinks = new List<QspLocationLink>();
  2068. objects = new List<QspObj>();
  2069. acts = new List<QspAct>();
  2070. StreamReader fi = null;
  2071. if (!OpenStreamForReading(ref fi, fileName))
  2072. {
  2073. return false;
  2074. }
  2075. string s;
  2076. int line_counter = 0;
  2077. List<string> locationCode = new List<string>();
  2078. bool inside = false;
  2079. while ((s = fi.ReadLine()) != null)
  2080. {
  2081. line_counter++;
  2082. string trimmed = s.Trim(WhiteSpace);
  2083. if ((trimmed.Length > 0) && (trimmed[0] == '#'))
  2084. {
  2085. //имя локации
  2086. string locName = trimmed.Substring(1).Trim(WhiteSpace);
  2087. if (!AddLocation(locName, line_counter))
  2088. {
  2089. fi.Close();
  2090. rTl.Close();
  2091. return false;
  2092. }
  2093. currentLocation = locName;
  2094. inside = true;
  2095. }
  2096. else if ((trimmed.Length > 38) && trimmed.StartsWith("--- ") && trimmed.EndsWith(" ---------------------------------"))
  2097. {
  2098. inside = false;
  2099. Location lastLoc = GetLastLocation();
  2100. if (lastLoc != null)
  2101. {
  2102. lastLoc.ParseLocation(locationCode, true);
  2103. locationCode.Clear();
  2104. currentLocation = "";
  2105. }
  2106. }
  2107. else
  2108. {
  2109. if (inside && GetLastLocation() != null)
  2110. locationCode.Add(s);
  2111. }
  2112. (sender as BackgroundWorker).ReportProgress(Convert.ToInt32(((double)line_counter/(double)totalLines) * 100));
  2113. if ((sender as BackgroundWorker).CancellationPending)
  2114. {
  2115. e.Cancel = true;
  2116. return true;
  2117. }
  2118. }
  2119. fi.Close();
  2120. rTl.Close();
  2121. return true;
  2122. }
  2123. public bool AddLocation(string name, int line)
  2124. {
  2125. if (name.Length <= 0)
  2126. {
  2127. SubmitError("Empty name of location", line);
  2128. return false;
  2129. }
  2130. if (m_LocationsByName.ContainsKey(name))
  2131. {
  2132. SubmitError("Location named " + name + " exist already", line);
  2133. return false;
  2134. }
  2135. Location newLoc = new Location(this, name, line, m_LocationsByOrder.Count == 0);
  2136. m_LocationsByName.Add(name, newLoc);
  2137. m_LocationsByOrder.Add(newLoc);
  2138. m_lastLocation = newLoc;
  2139. return true;
  2140. }
  2141. public Location GetLastLocation()
  2142. {
  2143. return m_lastLocation;
  2144. }
  2145. public Hashtable GetLocationsByName()
  2146. {
  2147. return m_LocationsByName;
  2148. }
  2149. public Location GetLocation(string locationName)
  2150. {
  2151. Location loc = (Location)m_LocationsByName[locationName];
  2152. return loc;
  2153. }
  2154. public bool Beautify(string fileName)
  2155. {
  2156. //Причесываем код - добавляем пробелов
  2157. StreamWriter fo = null;
  2158. if (!OpenStreamForWriting(ref fo, fileName))
  2159. return false;
  2160. for (int i = 0; i < m_LocationsByOrder.Count; i++)
  2161. {
  2162. Location loc = (Location)m_LocationsByOrder[i];
  2163. fo.WriteLine("# " + loc.GetName());
  2164. for (int j = 0; j < loc.GetCodeLinesCount(); j++)
  2165. {
  2166. string text = "";
  2167. int level = INVALID_INDEX;
  2168. loc.GetCodeLine(j, ref text, ref level);
  2169. if (level != INVALID_INDEX)
  2170. {
  2171. text = new string(' ', level * 4) + text.TrimStart(WhiteSpace);
  2172. }
  2173. fo.WriteLine(text);
  2174. }
  2175. fo.WriteLine("--- " + loc.GetName() + " ---------------------------------");
  2176. fo.WriteLine();
  2177. }
  2178. fo.Close();
  2179. return true;
  2180. }
  2181. }
  2182. }