gpt4 book ai didi

c# - 解析器生成器 : How to use GPLEX and GPPG together?

转载 作者:太空狗 更新时间:2023-10-29 20:31:24 31 4
gpt4 key购买 nike

在浏览了优秀的 C# 解析器生成器的帖子后,我偶然发现了 GPLEX 和 GPPG。我想使用 GPLEX 为 GPPG 生成 token 以解析和创建树(类似于 lex/yacc 关系)。但是,我似乎找不到关于这两者如何相互作用的示例。使用 lex/yacc,lex 返回由 yacc 定义的标记,并且可以将值存储在 yylval 中。这在 GPLEX/GPPG 中是如何完成的(他们的文档中没有)?

附件是我想转换成 GPLEX 的 lex 代码:

%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
[Oo][Rr] return OR;
[Aa][Nn][Dd] return AND;
[Nn][Oo][Tt] return NOT;
[A-Za-z][A-Za-z0-9_]* yylval=yytext; return ID;
%%

谢谢!安德鲁

最佳答案

首先:在您的项目中包含引用“QUT.ShiftReduceParser.dll”。它在 GPLEX 的下载包中提供。

主程序示例代码:

using System;
using ....;
using QUT.Gppg;
using Scanner;
using Parser;

namespace NCParser
{
class Program
{
static void Main(string[] args)
{
string pathTXT = @"C:\temp\testFile.txt";
FileStream file = new FileStream(pathTXT, FileMode.Open);
Scanner scanner = new Scanner();
scanner.SetSource(file, 0);
Parser parser = new Parser(scanner);
}
}
}

GPLEX 示例代码:

%using Parser;           //include the namespace of the generated Parser-class
%Namespace Scanner //names the Namespace of the generated Scanner-class
%visibility public //visibility of the types "Tokens","ScanBase","Scanner"
%scannertype Scanner //names the Scannerclass to "Scanner"
%scanbasetype ScanBase //names the Scanbaseclass to "ScanBase"
%tokentype Tokens //names the Tokenenumeration to "Tokens"

%option codePage:65001 out:Scanner.cs /*see the documentation of GPLEX for further Options you can use */

%{ //user-specified code will be copied in the Output-file
%}

OR [Oo][Rr]
AND [Aa][Nn][Dd]
Identifier [A-Za-z][A-Za-z0-9_]*

%% //Rules Section
%{ //user-code that will be executed before getting the next token
%}

{OR} {return (int)Tokens.kwAND;}
{AND} {return (int)Tokens.kwAND;}
{Identifier} {yylval = yytext; return (int)Tokens.ID;}

%% //User-code Section

GPPG 输入文件的示例代码:

%using Scanner      //include the Namespace of the scanner-class
%output=Parser.cs //names the output-file
%namespace Parser //names the namespace of the Parser-class

%parsertype Parser //names the Parserclass to "Parser"
%scanbasetype ScanBase //names the ScanBaseclass to "ScanBase"
%tokentype Tokens //names the Tokensenumeration to "Tokens"

%token kwAND "AND", kwOR "OR" //the received Tokens from GPLEX
%token ID

%% //Grammar Rules Section

program : /* nothing */
| Statements
;

Statements : EXPR "AND" EXPR
| EXPR "OR" EXPR
;

EXPR : ID
;

%% User-code Section
// Don't forget to declare the Parser-Constructor
public Parser(Scanner scnr) : base(scnr) { }

关于c# - 解析器生成器 : How to use GPLEX and GPPG together?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10808564/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com