readebnf.pp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. {
  2. This file is part of the Free Component Library (FCL)
  3. Copyright (c) 2025 by Michael Van Canneyt ([email protected])
  4. EBNF grammar Parser demo
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {$mode objfpc}
  12. {$h+}
  13. program readebnf;
  14. {$IFDEF WINDOWS}
  15. {$APPTYPE CONSOLE}
  16. {$ENDIF}
  17. uses
  18. SysUtils, classes,
  19. ebnf.tree,
  20. ebnf.parser;
  21. var
  22. EBNFSource: string;
  23. Parser: TEBNFParser;
  24. Grammar: TEBNFGrammar;
  25. Rule: TEBNFRule;
  26. List : TStrings;
  27. begin
  28. // Our example
  29. if ParamCount=1 then
  30. EBNFSource:=GetFileAsString(ParamStr(1))
  31. else
  32. begin
  33. Writeln('Using example source. Provide filename to parse actual file.');
  34. Writeln('');
  35. EBNFSource :=
  36. 'program = statement { ";" statement } ;' + sLineBreak +
  37. 'statement = "IF" expression "THEN" statement [ "ELSE" statement ]' + sLineBreak +
  38. ' | identifier "=" expression' + sLineBreak +
  39. ' | "PRINT" ( string_literal | identifier ) ;' + sLineBreak +
  40. 'expression = term { ("+" | "-") term } ;' + sLineBreak +
  41. 'term = factor { ("*" | "/") factor } ;' + sLineBreak +
  42. 'factor = identifier | string_literal | number | "(" expression ")" | "?comment?" ;';
  43. end;
  44. Parser := nil;
  45. Grammar := nil;
  46. try
  47. Parser := TEBNFParser.Create(EBNFSource);
  48. Grammar := Parser.Parse;
  49. Writeln('Successfully parsed EBNF grammar:');
  50. Writeln('-----------------------------------');
  51. Writeln(Grammar.ToString);
  52. Writeln('-----------------------------------');
  53. // demo accessing a specific rule
  54. Rule:=Grammar.Rules['program'];
  55. if Assigned(Rule) then
  56. begin
  57. Writeln('Details for rule "program":');
  58. Writeln(Rule.ToString);
  59. end;
  60. List:=TStringList.Create;
  61. try
  62. Grammar.FindUndefinedIdentifiers(List);
  63. if List.Count>0 then
  64. begin
  65. Writeln('Undefined meta-identifiers:');
  66. Writeln(list.text);
  67. end;
  68. finally
  69. list.Free;
  70. end;
  71. except
  72. on E: Exception do
  73. Writeln('Error: ' + E.Message);
  74. end;
  75. Grammar.Free;
  76. Parser.Free;
  77. end.