添加缩进

发布于 2024-09-15 14:30:27 字数 451 浏览 2 评论 0原文

我正在尝试为一种虚构的编程语言制作一个解析器。我现在正在进行练习,我们需要确保解析器的输出是输入的 C 语言转换。

所以像......这样的事情

STARTMAIN a=b+2; return a ENDMAIN

必须变得......

int main () { a=b+2; return a; }

到目前为止一切都很好,几乎。这项练习还要求,在转换的同时,我们必须添加适当的缩进和(因为去年我不得不艰难地学习)换行符。

明显的部分是,每次打开 { 时,您都会增加一个计数器,然后在每个新行上添加适当的选项卡。然而,右括号('}')是一个不同的故事,因为你无法事先检测到它们,并且一旦你解析了它们,你就不能通过删除最后一个打印的选项卡来将它们放在左侧。

是否有解决方案,和/或检查和添加缩进的一致方法?

I'm trying to make a parser for a made-up programming language. I'm now at the part of the exercise where we're required to make sure the parser's output is a conversion in C of the input.

So things like...

STARTMAIN a=b+2; return a ENDMAIN

...must become...

int main () { a=b+2; return a; }

So far so good, almost. The exercise also requires that in the same time, as we convert, we have to add proper indentation and (as I had to learn the hard way last year) newlines.

The obvious part is that each time a { opens, you increase a counter and then add the appropriate tabs on each new line. However, closing brackets ('}') are a different story as you can't detect them before hand, and once you've parsed them, you can't just put them a tab to the left by removing the last tab printed.

Is there a solution to this, and/or a consistent way of checking and adding indentation?

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

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

发布评论

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

评论(1

如果没有你 2024-09-22 14:30:27

好吧,您现在已经发现了为什么人们不总是费心去整齐地格式化生成的输出的原因之一;这样做相对困难。

事实上,解决这个问题的一种方法是为该语言提供官方格式化程序。 Google 的 Go 编程语言附带“gofmt”程序以鼓励官方格式。 C 没有这样的标准,因此关于大括号放置的宗教战争,但它确实有诸如 indent 实际上可以为您整齐地格式化代码。

诀窍是在您知道要输出多少个选项卡之前不要在一行上输出任何内容。因此,在带有右大括号的行上,您可以递减缩进计数器(确保它永远不会变为负数),然后才输出前导制表符和后面的大括号。

请注意,C 的某些部分在右大括号后需要一个分号(或逗号)(例如初始化程序和结构定义);其他人则没有(认为语句块)。

Well, you've now discovered one reason why people do not always bother to format generated output neatly; it is relatively hard to do so.

Indeed, one way to deal with the problem is to provide an official formatter for the language. Google's Go programming language comes with the 'gofmt' program to encourage the official format. C does not have such a standard, hence the religious wars over the placement of braces, but it does have programs such as indent which can in fact format the code neatly for you.

The trick is not to output anything on a line until you know how many tabs to output. So, on a line with a close brace, you decrement the indent counter (making sure it never goes negative) and only then do you output the leading tabs and the following brace.

Note that some parts of C require a semi-colon (or comma) after the close brace (think initializers and structure definitions); others do not (think statement blocks).

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