Lexer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. * Created by SharpDevelop.
  3. * User: lextm
  4. * Date: 2008/5/17
  5. * Time: 16:50
  6. *
  7. * To change this template use Tools | Options | Coding | Edit Standard Headers.
  8. */
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Text;
  13. using Lextm.SharpSnmpLib.Mib.Elements.Types;
  14. namespace Lextm.SharpSnmpLib.Mib
  15. {
  16. /// <summary>
  17. /// Lexer class that parses MIB files into symbol list.
  18. /// </summary>
  19. public sealed class Lexer
  20. {
  21. private readonly SymbolList _symbols = new SymbolList();
  22. public Lexer(string file)
  23. : this(file, new StreamReader(file))
  24. {
  25. }
  26. public Lexer(string file, TextReader stream)
  27. {
  28. this.Parse(file, stream);
  29. }
  30. public ISymbolEnumerator GetEnumerator()
  31. {
  32. return _symbols.GetSymbolEnumerator();
  33. }
  34. #region Parsing of MIB File
  35. private class ParseParams
  36. {
  37. public string File;
  38. public StringBuilder Temp = new StringBuilder();
  39. public bool StringSection = false;
  40. public bool AssignSection = false;
  41. public bool AssignAhead = false;
  42. public bool DotSection = false;
  43. }
  44. /// <summary>
  45. /// Parses MIB file to symbol list.
  46. /// </summary>
  47. /// <param name="file">File</param>
  48. /// <param name="stream">File stream</param>
  49. private void Parse(string file, TextReader stream)
  50. {
  51. if (stream == null)
  52. {
  53. throw new ArgumentNullException("stream");
  54. }
  55. ParseParams pp = new ParseParams();
  56. pp.File = file;
  57. string line;
  58. int row = 0;
  59. while ((line = stream.ReadLine()) != null)
  60. {
  61. if (!pp.StringSection && line.TrimStart().StartsWith("--", StringComparison.Ordinal))
  62. {
  63. row++;
  64. continue; // commented line
  65. }
  66. ParseLine(pp, line, row);
  67. row++;
  68. }
  69. }
  70. private void ParseLine(ParseParams pp, string line, int row)
  71. {
  72. line = line + "\n";
  73. int count = line.Length;
  74. for (int i = 0; i < count; i++)
  75. {
  76. char current = line[i];
  77. bool moveNext = Parse(pp, current, row, i);
  78. if (moveNext)
  79. {
  80. break;
  81. }
  82. }
  83. }
  84. private bool Parse(ParseParams pp, char current, int row, int column)
  85. {
  86. switch (current)
  87. {
  88. case '\n':
  89. case '{':
  90. case '}':
  91. case '(':
  92. case ')':
  93. case '[':
  94. case ']':
  95. case ';':
  96. case ',':
  97. case '|':
  98. if (!pp.StringSection)
  99. {
  100. bool moveNext = ParseLastSymbol(pp, row, column);
  101. if (moveNext)
  102. {
  103. _symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
  104. return true;
  105. }
  106. _symbols.Add(CreateSpecialSymbol(pp.File, current, row, column));
  107. return false;
  108. }
  109. break;
  110. case '"':
  111. pp.StringSection = !pp.StringSection;
  112. break;
  113. case '\r':
  114. return false;
  115. default:
  116. if ((int)current == 0x1A)
  117. {
  118. // IMPORTANT: ignore invisible characters such as SUB.
  119. return false;
  120. }
  121. if (Char.IsWhiteSpace(current) && !pp.AssignSection && !pp.StringSection)
  122. {
  123. bool moveNext = ParseLastSymbol(pp, row, column);
  124. if (moveNext)
  125. {
  126. _symbols.Add(CreateSpecialSymbol(pp.File, '\n', row, column));
  127. return true;
  128. }
  129. return false;
  130. }
  131. if (pp.AssignAhead)
  132. {
  133. pp.AssignAhead = false;
  134. ParseLastSymbol(pp, row, column);
  135. break;
  136. }
  137. if (pp.DotSection && current != '.')
  138. {
  139. ParseLastSymbol(pp, row, column);
  140. pp.DotSection = false;
  141. }
  142. if (current == '.' && !pp.StringSection)
  143. {
  144. if (!pp.DotSection)
  145. {
  146. ParseLastSymbol(pp, row, column);
  147. pp.DotSection = true;
  148. }
  149. }
  150. if (current == ':' && !pp.StringSection)
  151. {
  152. if (!pp.AssignSection)
  153. {
  154. ParseLastSymbol(pp, row, column);
  155. }
  156. pp.AssignSection = true;
  157. }
  158. if (current == '=' && !pp.StringSection)
  159. {
  160. pp.AssignSection = false;
  161. pp.AssignAhead = true;
  162. }
  163. break;
  164. }
  165. pp.Temp.Append(current);
  166. return false;
  167. }
  168. private bool ParseLastSymbol(ParseParams pp, int row, int column)
  169. {
  170. if (pp.Temp.Length > 0)
  171. {
  172. Symbol s = new Symbol(pp.File, pp.Temp.ToString(), row, column);
  173. pp.Temp.Length = 0;
  174. if (s.ToString().StartsWith(Symbol.Comment.ToString()))
  175. {
  176. // ignore the rest symbols on this line because they are in comment.
  177. return true;
  178. }
  179. _symbols.Add(s);
  180. }
  181. return false;
  182. }
  183. private static Symbol CreateSpecialSymbol(string file, char value, int row, int column)
  184. {
  185. string str;
  186. switch (value)
  187. {
  188. case '\n':
  189. str = Environment.NewLine;
  190. break;
  191. case '{':
  192. str = "{";
  193. break;
  194. case '}':
  195. str = "}";
  196. break;
  197. case '(':
  198. str = "(";
  199. break;
  200. case ')':
  201. str = ")";
  202. break;
  203. case '[':
  204. str = "[";
  205. break;
  206. case ']':
  207. str = "]";
  208. break;
  209. case ';':
  210. str = ";";
  211. break;
  212. case ',':
  213. str = ",";
  214. break;
  215. case '|':
  216. str = "|";
  217. break;
  218. default:
  219. throw new ArgumentException("value is not a special character");
  220. }
  221. return new Symbol(file, str, row, column);
  222. }
  223. #endregion
  224. #region Static Parse Helper
  225. public static ITypeAssignment ParseBasicTypeDef(IModule module, string name, ISymbolEnumerator symbols, bool isMacroSyntax = false)
  226. {
  227. Symbol current = symbols.NextNonEOLSymbol();
  228. if (current == Symbol.Bits)
  229. {
  230. return new BitsType(module, name, symbols);
  231. }
  232. if (IntegerType.IsIntegerType(current))
  233. {
  234. return new IntegerType(module, name, current, symbols);
  235. }
  236. if (UnsignedType.IsUnsignedType(current))
  237. {
  238. return new UnsignedType(module, name, current, symbols);
  239. }
  240. if (current == Symbol.Opaque)
  241. {
  242. return new OpaqueType(module, name, symbols);
  243. }
  244. if (current == Symbol.IpAddress)
  245. {
  246. return new IpAddressType(module, name, symbols);
  247. }
  248. if (current == Symbol.TextualConvention)
  249. {
  250. return new TextualConvention(module, name, symbols);
  251. }
  252. if (current == Symbol.Octet)
  253. {
  254. Symbol next = symbols.NextNonEOLSymbol();
  255. if (next == Symbol.String)
  256. {
  257. return new OctetStringType(module, name, symbols);
  258. }
  259. symbols.PutBack(next);
  260. }
  261. if (current == Symbol.Object)
  262. {
  263. Symbol next = symbols.NextNonEOLSymbol();
  264. if (next == Symbol.Identifier)
  265. {
  266. return new ObjectIdentifierType(module, name, symbols);
  267. }
  268. symbols.PutBack(next);
  269. }
  270. if (current == Symbol.Sequence)
  271. {
  272. Symbol next = symbols.NextNonEOLSymbol();
  273. if (next == Symbol.Of)
  274. {
  275. return new SequenceOf(module, name, symbols);
  276. }
  277. else
  278. {
  279. symbols.PutBack(next);
  280. return new Sequence(module, name, symbols);
  281. }
  282. }
  283. if (current == Symbol.Choice)
  284. {
  285. return new Choice(module, name, symbols);
  286. }
  287. return new TypeAssignment(module, name, current, symbols, isMacroSyntax);
  288. }
  289. public static void ParseOidValue(ISymbolEnumerator symbols, out string parent, out uint value)
  290. {
  291. parent = null;
  292. value = 0;
  293. Symbol current = symbols.NextNonEOLSymbol();
  294. current.Expect(Symbol.OpenBracket);
  295. Symbol previous = null;
  296. StringBuilder longParent = new StringBuilder();
  297. current = symbols.NextNonEOLSymbol();
  298. longParent.Append(current);
  299. while ((current = symbols.NextNonEOLSymbol()) != null)
  300. {
  301. bool succeeded;
  302. if (current == Symbol.OpenParentheses)
  303. {
  304. longParent.Append(current);
  305. current = symbols.NextNonEOLSymbol();
  306. succeeded = UInt32.TryParse(current.ToString(), out value);
  307. current.Assert(succeeded, "not a decimal");
  308. longParent.Append(current);
  309. current = symbols.NextNonEOLSymbol();
  310. current.Expect(Symbol.CloseParentheses);
  311. longParent.Append(current);
  312. continue;
  313. }
  314. if (current == Symbol.CloseBracket)
  315. {
  316. parent = longParent.ToString();
  317. return;
  318. }
  319. succeeded = UInt32.TryParse(current.ToString(), out value);
  320. if (succeeded)
  321. {
  322. // numerical way
  323. while ((current = symbols.NextNonEOLSymbol()) != Symbol.CloseBracket)
  324. {
  325. longParent.Append(".").Append(value);
  326. succeeded = UInt32.TryParse(current.ToString(), out value);
  327. current.Assert(succeeded, "not a decimal");
  328. }
  329. current.Expect(Symbol.CloseBracket);
  330. parent = longParent.ToString();
  331. return;
  332. }
  333. longParent.Append(".");
  334. longParent.Append(current);
  335. current = symbols.NextNonEOLSymbol();
  336. current.Expect(Symbol.OpenParentheses);
  337. longParent.Append(current);
  338. current = symbols.NextNonEOLSymbol();
  339. succeeded = UInt32.TryParse(current.ToString(), out value);
  340. current.Assert(succeeded, "not a decimal");
  341. longParent.Append(current);
  342. current = symbols.NextNonEOLSymbol();
  343. current.Expect(Symbol.CloseParentheses);
  344. longParent.Append(current);
  345. previous = current;
  346. }
  347. throw MibException.Create("end of file reached", previous);
  348. }
  349. public static ValueRanges DecodeRanges(ISymbolEnumerator symbols)
  350. {
  351. ValueRanges result = new ValueRanges();
  352. Symbol startSymbol = symbols.NextNonEOLSymbol();
  353. Symbol current = startSymbol;
  354. current.Expect(Symbol.OpenParentheses);
  355. while (current != Symbol.CloseParentheses)
  356. {
  357. Symbol value1Symbol = symbols.NextNonEOLSymbol();
  358. if ((value1Symbol == Symbol.Size) && !result.IsSizeDeclaration)
  359. {
  360. result.IsSizeDeclaration = true;
  361. symbols.NextNonEOLSymbol().Expect(Symbol.OpenParentheses);
  362. continue;
  363. }
  364. // check for valid number
  365. Int64? value1 = DecodeNumber(value1Symbol);
  366. if (!value1.HasValue)
  367. {
  368. value1Symbol.Assert(false, "Invalid range declaration!");
  369. }
  370. // process next symbol
  371. ValueRange range;
  372. current = symbols.NextNonEOLSymbol();
  373. if (current == Symbol.DoubleDot)
  374. {
  375. // its a continuous range
  376. Symbol value2Symbol = symbols.NextNonEOLSymbol();
  377. Int64? value2 = DecodeNumber(value2Symbol);
  378. value2Symbol.Assert(value2.HasValue && (value2.Value >= value1.Value), "Invalid range declaration!");
  379. if (value2.Value == value1.Value)
  380. {
  381. range = new ValueRange(value1.Value, null);
  382. }
  383. else
  384. {
  385. range = new ValueRange(value1.Value, value2.Value);
  386. }
  387. current = symbols.NextNonEOLSymbol();
  388. }
  389. else
  390. {
  391. // its a single number
  392. range = new ValueRange(value1.Value, null);
  393. }
  394. // validate range
  395. if (result.IsSizeDeclaration)
  396. {
  397. value1Symbol.Assert(range.Start >= 0, "Invalid range declaration! Size must be greater than 0");
  398. }
  399. result.Add(range);
  400. // check next symbol
  401. current.Expect(Symbol.Pipe, Symbol.CloseParentheses);
  402. }
  403. if (result.IsSizeDeclaration)
  404. {
  405. current = symbols.NextNonEOLSymbol();
  406. current.Expect(Symbol.CloseParentheses);
  407. }
  408. // validate ranges in between
  409. for (int i=0; i<result.Count; i++)
  410. {
  411. for (int k=i+1; k<result.Count; k++)
  412. {
  413. startSymbol.Assert(!result[i].IntersectsWith(result[k]), "Invalid range declaration! Overlapping of ranges!");
  414. }
  415. }
  416. return result;
  417. }
  418. public static Int64? DecodeNumber(Symbol number)
  419. {
  420. Int64 result;
  421. string numString = (number != null) ? number.ToString() : null;
  422. if (!String.IsNullOrEmpty(numString))
  423. {
  424. if (numString.StartsWith("'") && (numString.Length > 3))
  425. {
  426. // search second apostrophe
  427. int end = numString.IndexOf('\'', 1);
  428. if (end == (numString.Length - 2))
  429. {
  430. try
  431. {
  432. switch (numString[numString.Length - 1])
  433. {
  434. case 'b':
  435. case 'B':
  436. result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 2);
  437. return result;
  438. case 'h':
  439. case 'H':
  440. result = Convert.ToInt64(numString.Substring(1, numString.Length - 3), 16);
  441. return result;
  442. }
  443. }
  444. catch
  445. {
  446. }
  447. }
  448. }
  449. else if (Int64.TryParse(numString, out result))
  450. {
  451. return result;
  452. }
  453. }
  454. return null;
  455. }
  456. public static ValueMap DecodeEnumerations(ISymbolEnumerator symbols)
  457. {
  458. Symbol current = symbols.NextNonEOLSymbol();
  459. current.Expect(Symbol.OpenBracket);
  460. ValueMap map = new ValueMap();
  461. do
  462. {
  463. current = symbols.NextNonEOLSymbol();
  464. string identifier = current.ToString();
  465. current = symbols.NextNonEOLSymbol();
  466. current.Expect(Symbol.OpenParentheses);
  467. current = symbols.NextNonEOLSymbol();
  468. Int64 enumValue;
  469. if (Int64.TryParse(current.ToString(), out enumValue))
  470. {
  471. try
  472. {
  473. // Have to include the number as it seems repeated identifiers are allowed ??
  474. map.Add(enumValue, String.Format("{0}({1})", identifier, enumValue));
  475. }
  476. catch (ArgumentException ex)
  477. {
  478. current.Assert(false, ex.Message);
  479. }
  480. }
  481. else
  482. {
  483. // Need to get "DefinedValue".
  484. }
  485. current = symbols.NextNonEOLSymbol();
  486. current.Expect(Symbol.CloseParentheses);
  487. current = symbols.NextNonEOLSymbol();
  488. } while (current == Symbol.Comma);
  489. current.Expect(Symbol.CloseBracket);
  490. return map;
  491. }
  492. #endregion
  493. }
  494. }