从函数参数而不是文件中获取输入

发布于 2024-08-13 23:02:31 字数 166 浏览 4 评论 0原文

我看到的所有示例都在 lex & 文件中读取。解析它。

我需要一个函数,它接受一个字符串(char *,我正在生成 C 代码)作为参数,并对其进行操作。

我怎样才能做到最好?我想过将字符串写入流,然后将其提供给词法分析器,但感觉不对。还有更好的办法吗?

提前致谢

All of the examples which I see read in a file the lex & parse it.

I need to have a function which takes a string (char *, I'm generating C code) as parameter, and acts upon that.

How can I do that best? I thought of writing the string to a stream, then feeding that to the lexer, but it doesn't feel right. Is there any better way?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧夏天 2024-08-20 23:02:31

您需要使用 antlr3NewAsciiStringInPlaceStream 方法。

您没有说明您使用的 Antlr 版本,所以我假设使用 Antlr v3。

此方法的输入是要解析的字符串及其长度,然后您可以使用 NULL 作为最后一个输入。

这会生成一个类似于用于解析文件的 antlr3AsciiFileStreamNew 的输入流。

我看到您提到将输入写入流。如果您可以使用 C++,那么这可能是您会遇到的最佳方法。

这是我通常使用的准系统代码:

std::istringstream  issInput(std::cin); // make this an ifstream if you want to parse a file
Lexer           oLexer(issInput);
Parser          oParser(oLexer);

oFactory("CommonASTWithHiddenTokens",&antlr::CommonASTWithHiddenTokens::factory);
    antlr::ASTFactory oFactory;
oParser.initializeASTFactory(oFactory);
oParser.setASTFactory(&oFactory);

oParser.main();
antlr::RefAST ast = oParser.getAST();
if (ast)
{
    TreeWalker  oTreeWalker;
    oTreeWalker.main(ast, rPCode);
}

You would need to use the antlr3NewAsciiStringInPlaceStream method.

You didn't say what version of Antlr you were using so I'll assume Antlr v3.

The inputs to this method are the string to parse, it's length and then you can probably use NULL for the last input.

This produces an input stream similar to the antlr3AsciiFileStreamNew that you would use to parse a file.

I see that you mentioned writing the input to a stream. If you can use C++ then that's the best method you'll probably come by.

This is the barebones code I normally use:

std::istringstream  issInput(std::cin); // make this an ifstream if you want to parse a file
Lexer           oLexer(issInput);
Parser          oParser(oLexer);

oFactory("CommonASTWithHiddenTokens",&antlr::CommonASTWithHiddenTokens::factory);
    antlr::ASTFactory oFactory;
oParser.initializeASTFactory(oFactory);
oParser.setASTFactory(&oFactory);

oParser.main();
antlr::RefAST ast = oParser.getAST();
if (ast)
{
    TreeWalker  oTreeWalker;
    oTreeWalker.main(ast, rPCode);
}
埋情葬爱 2024-08-20 23:02:31

我认为你应该将它提供给流。如果您愿意,可以将其提供给标准输入。这样,您的代码与从文件中读取字符串应该不会有太大差异。

I think you should feed it to a stream. You could feed it to stdin if you'd like. That way, your code shouldn't differ too much from reading strings from a file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文