如何在语法中使用类似Python的缩进形式编写语言? [英] How to write a language with Python-like indentation in syntax?

查看:69
本文介绍了如何在语法中使用类似Python的缩进形式编写语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种与Python类似的内置语言来编写工具.我想使缩进在语法上有意义(这样,行首的制表符和空格将表示命令的嵌套).

I'm writing a tool with it's own built-in language similar to Python. I want to make indentation meaningful in the syntax (so that tabs and spaces at line beginning would represent nesting of commands).

做到这一点的最佳方法是什么?

What is the best way to do this?

我以前写过递归下降和有限自动机解析器.

I've written recursive-descent and finite automata parsers before.

推荐答案

当前 CPython '解析器似乎要使用称为 ASDL .

The current CPython's parser seems to be generated using something called ASDL.

关于您要求的缩进,使用完成称为 INDENT DEDENT 的特殊词法标记.要复制该标记,只需在词法分析器中实现这些标记(如果使用堆栈存储先前缩进行的起始列,这将非常容易),然后像往常一样将它们插入语法中(就像其他任何关键字或运算符一样)

Regarding the indentation you're asking for, it's done using special lexer tokens called INDENT and DEDENT. To replicate that, just implement those tokens in your lexer (that is pretty easy if you use a stack to store the starting columns of previous indented lines), and then plug them into your grammar as usual (like any other keyword or operator token).

这篇关于如何在语法中使用类似Python的缩进形式编写语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆