- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试实现 python 之类的依赖缩进的语法。
源示例:
ABC QWE
CDE EFG
EFG CDE
ABC
QWE ZXC
grammar mygrammar;
text: (ID | block)+;
block: INDENT (ID|block)+ DEDENT;
INDENT: ????;
DEDENT: ????;
最佳答案
我不知道最简单的处理方法是什么,但以下是一种相对简单的方法。每当您在词法分析器中匹配换行符时,可选择匹配一个或多个空格。如果换行后有空格,则将这些空格的长度与当前的缩进大小进行比较。如果它大于当前缩进大小,则发出 Indent
token ,如果它小于当前缩进大小,则发出 Dedent
token ,如果相同,则不执行任何操作。
您还需要发出许多 Dedent
文件末尾的标记让每个 Indent
有一个匹配的 Dedent
token 。
为了使其正常工作,您 必须在输入源文件中添加前导和尾随换行符!
ANTRL3
快速演示:
grammar PyEsque;
options {
output=AST;
}
tokens {
BLOCK;
}
@lexer::members {
private int previousIndents = -1;
private int indentLevel = 0;
java.util.Queue<Token> tokens = new java.util.LinkedList<Token>();
@Override
public void emit(Token t) {
state.token = t;
tokens.offer(t);
}
@Override
public Token nextToken() {
super.nextToken();
return tokens.isEmpty() ? Token.EOF_TOKEN : tokens.poll();
}
private void jump(int ttype) {
indentLevel += (ttype == Dedent ? -1 : 1);
emit(new CommonToken(ttype, "level=" + indentLevel));
}
}
parse
: block EOF -> block
;
block
: Indent block_atoms Dedent -> ^(BLOCK block_atoms)
;
block_atoms
: (Id | block)+
;
NewLine
: NL SP?
{
int n = $SP.text == null ? 0 : $SP.text.length();
if(n > previousIndents) {
jump(Indent);
previousIndents = n;
}
else if(n < previousIndents) {
jump(Dedent);
previousIndents = n;
}
else if(input.LA(1) == EOF) {
while(indentLevel > 0) {
jump(Dedent);
}
}
else {
skip();
}
}
;
Id
: ('a'..'z' | 'A'..'Z')+
;
SpaceChars
: SP {skip();}
;
fragment NL : '\r'? '\n' | '\r';
fragment SP : (' ' | '\t')+;
fragment Indent : ;
fragment Dedent : ;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
public class Main {
public static void main(String[] args) throws Exception {
PyEsqueLexer lexer = new PyEsqueLexer(new ANTLRFileStream("in.txt"));
PyEsqueParser parser = new PyEsqueParser(new CommonTokenStream(lexer));
CommonTree tree = (CommonTree)parser.parse().getTree();
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
System.out.println(st);
}
}
in.txt
的文件中:
AAA AAAAA BBB BB B BB BBBBB BB CCCCCC C CC BB BBBBBB C CCC DDD DD D DDD D DDD
(Note the leading and trailing line breaks!)
then you'll see output that corresponds to the following AST:
Note that my demo wouldn't produce enough dedents in succession, like dedenting from ccc
to aaa
(2 dedent tokens are needed):
aaa
bbb
ccc
aaa
else if(n < previousIndents) { ... }
中的代码根据
n
之间的差异,可能会发出 1 个以上的 dedent token 和
previousIndents
.在我的头顶上,这可能是这样的:
else if(n < previousIndents) {
// Note: assuming indent-size is 2. Jumping from previousIndents=6
// to n=2 will result in emitting 2 `Dedent` tokens
int numDedents = (previousIndents - n) / 2;
while(numDedents-- > 0) {
jump(Dedent);
}
previousIndents = n;
}
grammar Python3;
tokens { INDENT, DEDENT }
@lexer::members {
// A queue where extra tokens are pushed on (see the NEWLINE lexer rule).
private java.util.LinkedList<Token> tokens = new java.util.LinkedList<>();
// The stack that keeps track of the indentation level.
private java.util.Stack<Integer> indents = new java.util.Stack<>();
// The amount of opened braces, brackets and parenthesis.
private int opened = 0;
// The most recently produced token.
private Token lastToken = null;
@Override
public void emit(Token t) {
super.setToken(t);
tokens.offer(t);
}
@Override
public Token nextToken() {
// Check if the end-of-file is ahead and there are still some DEDENTS expected.
if (_input.LA(1) == EOF && !this.indents.isEmpty()) {
// Remove any trailing EOF tokens from our buffer.
for (int i = tokens.size() - 1; i >= 0; i--) {
if (tokens.get(i).getType() == EOF) {
tokens.remove(i);
}
}
// First emit an extra line break that serves as the end of the statement.
this.emit(commonToken(Python3Parser.NEWLINE, "\n"));
// Now emit as much DEDENT tokens as needed.
while (!indents.isEmpty()) {
this.emit(createDedent());
indents.pop();
}
// Put the EOF back on the token stream.
this.emit(commonToken(Python3Parser.EOF, "<EOF>"));
}
Token next = super.nextToken();
if (next.getChannel() == Token.DEFAULT_CHANNEL) {
// Keep track of the last token on the default channel.
this.lastToken = next;
}
return tokens.isEmpty() ? next : tokens.poll();
}
private Token createDedent() {
CommonToken dedent = commonToken(Python3Parser.DEDENT, "");
dedent.setLine(this.lastToken.getLine());
return dedent;
}
private CommonToken commonToken(int type, String text) {
int stop = this.getCharIndex() - 1;
int start = text.isEmpty() ? stop : stop - text.length() + 1;
return new CommonToken(this._tokenFactorySourcePair, type, DEFAULT_TOKEN_CHANNEL, start, stop);
}
// Calculates the indentation of the provided spaces, taking the
// following rules into account:
//
// "Tabs are replaced (from left to right) by one to eight spaces
// such that the total number of characters up to and including
// the replacement is a multiple of eight [...]"
//
// -- https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
static int getIndentationCount(String spaces) {
int count = 0;
for (char ch : spaces.toCharArray()) {
switch (ch) {
case '\t':
count += 8 - (count % 8);
break;
default:
// A normal space char.
count++;
}
}
return count;
}
boolean atStartOfInput() {
return super.getCharPositionInLine() == 0 && super.getLine() == 1;
}
}
single_input
: NEWLINE
| simple_stmt
| compound_stmt NEWLINE
;
// more parser rules
NEWLINE
: ( {atStartOfInput()}? SPACES
| ( '\r'? '\n' | '\r' ) SPACES?
)
{
String newLine = getText().replaceAll("[^\r\n]+", "");
String spaces = getText().replaceAll("[\r\n]+", "");
int next = _input.LA(1);
if (opened > 0 || next == '\r' || next == '\n' || next == '#') {
// If we're inside a list or on a blank line, ignore all indents,
// dedents and line breaks.
skip();
}
else {
emit(commonToken(NEWLINE, newLine));
int indent = getIndentationCount(spaces);
int previous = indents.isEmpty() ? 0 : indents.peek();
if (indent == previous) {
// skip indents of the same size as the present indent-size
skip();
}
else if (indent > previous) {
indents.push(indent);
emit(commonToken(Python3Parser.INDENT, spaces));
}
else {
// Possibly emit more than 1 DEDENT token.
while(!indents.isEmpty() && indents.peek() > indent) {
this.emit(createDedent());
indents.pop();
}
}
}
}
;
// more lexer rules
关于ANTLR 实现 python 之类的缩进依赖语法的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8642154/
让我们考虑以下 ANTLR4 语法(最小示例): grammar Foo; expr : a? b? c? ; 我如何指定 a、b 或 c 中的至少一个 必须出现在表达式? 基本上我正在寻
我为字符串变量声明写了下面的语法。字符串的定义类似于单引号之间的任何内容,但必须有一种方法可以通过使用 $ 字母转义将单引号添加到字符串值。 grammar test; options {
我最近创建了一个 ANTLR3 解析器规则 options : foo bar; 它没有编译,我花了一些时间才发现 options是一个保留字(AntlrWorks 指出了错误,但没有指出原因)。 A
我正在从“The Definitive Antlr reference”一书中学习 Antlr。我还处于起步阶段。我喜欢动手做东西,所以我认为做一个好的示例项目会是一个很好的学习经验。 我正在寻找一个
我们有一个为 antlr V2 编写的语法,我想迁移到 antlr v4。有迁移指南吗?我还想知道对现有 V2 语法的修改,以便我们更好地利用 v4 功能。 最佳答案 我通过编写一个新的 Antlr
介绍 查看文档,ANTLR 2 曾经有一个叫做 predicated lexing 的东西。 ,有这样的例子(受 Pascal 启发): RANGE_OR_INT : ( INT ".."
我已经开始学习 ANTLR,并且拥有 2007 年的书《The Definitive ANTLR Reference》和 ANTLRWorks(用于创建语法的交互式工具)。而且,作为这样的人,我从第三
我正在开发 D 语言的解析器,当我尝试添加“切片”运算符规则时遇到了麻烦。你可以找到它的ANTLR语法here 。基本上问题是,如果词法分析器遇到这样的字符串:“1..2”,它就会完全丢失,并且最终成
在 ANTLR 语法中,我们如何区分变量名和标识符? VAR: ('A'..'Z')+ DIGIT* ; IDENT : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'
我想在 ANTLR 语法中解析 ISO 8601 日期。 2001-05-03 我的语法文件中有以下条目: date : FOUR_DIGIT ('-')? TWO_DIGIT ('-')? T
我们有一个为 antlr V3 编写的语法,我想迁移到 antlr v4。有没有迁移指南。我还想知道对现有 V3 语法的修改,以便我们很好地利用 v4 的功能。 最佳答案 如果您在 v3 或更早版本中
我正在尝试在一台新计算机上使用 ANTLR v4 语法插件在 IntelliJ 中运行一个简单的语法文件。我已经按照在线步骤在 IntelliJ 中安装插件,插件看起来安装正确。我在 .g4 语法文件
我正在使用 ANTLR 为旧的专有报告规范编写一个解析器,目前我正在尝试实现生成的解析树的访问者,以扩展自动生成的抽象访问类。 我对 ANTLR(我最近才学会)和一般的访问者模式都没有什么经验,但是如
我知道插入符号后缀在 antlr 中的含义(即 make root)但是当插入符号是我一直在阅读的以下语法中的前缀时呢(该语法是全新的,由学习 antlr 的新团队完成)。 .. selectClau
我不知道这个问题是否有效,因为我对源代码解析不是很熟悉。我的目标是为一种现有的编程语言(语言“X”)编写一个源代码完成函数,以供学习之用。 Antlr(v4) 是否适合这样的任务,还是应该手动完成必要
请查看源代码:https://gist.github.com/1684022 . 我定义了两个 token : ID : ('a'..'z' | 'A'..'Z') ('0'..'9' | 'a
我知道“+”、“?”和 '*'。但是,如果我希望某事重复 5 次,该怎么办?例如,如果标识符必须是长度为 5 的十六进制数字符串? 更具体地说,我正在考虑定义一个无限长度的通用词法分析器规则,然后在解
如何控制切换Antlr来自解析器操作的词法分析器模式? 我扩展了生成的 Parser 和 Lexer,所以我可以调用 pushMode和 popMode从解析器女巫依次调用合适的pushMode和 p
我正在使用 ANTLR 来标记一个简单的语法,并且需要区分一个 ID: ID : LETTER (LETTER | DIGIT)* ; fragment DIGIT : '
我有一个这样的 ANTLR 规则 receive returns[Evaluator e,String message] : RECEIVE FILENAME {$e= new ReceiveEv
我是一名优秀的程序员,十分优秀!