语法分析器建议(ANTLR)

时间:2017-07-12 23:17:12

标签: parsing antlr qbasic

我正试图在Antlr4上编写一个简单的QBasic语法。而且' Else-If'循环赢了,它会在assigncommand之后自动转换为THEN。你能复习我的语法吗,有什么改进吗?

如何在正则表达式中编写string。(也使用西里尔字母表)

我应该写下这些关键词('PRINT' 'IF')吗?或使用词法分析器(如..PRINTKEY; PRINTKEY : 'PRINT'

grammar Hello3;

// AssignCommand; MainCommand; FlowCommand
prog : (assigncommand | maincommand | flowcommand)+;

// AssignInt; AssignString
// MyAge = PreviousAge + 1
// MyName$ = FirstName$ + MiddleName$ + LastName$
assigncommand : assignint | assignstring;
assignint : IDINT '=' (IDINT | INT) (OPERATORMATH (IDINT | INT))* '\n'+;
assignstring : IDSTRING '=' (IDSTRING | STRING) ('+' (IDSTRING | STRING))* '\n'+;

//PrintCommand, InputCommand
//PRINT MyName$, MyAge, "Hello", 123
//INPUT "What is your name?", yourname$
//(or)INPUT yourname$ 
maincommand : printcommand | inputcommand;
printcommand : 'PRINT' (',' (IDINT | IDSTRING | STRING | INT))+ '\n'+;
inputcommand : 'INPUT' (IDINT | IDSTRING | STRING)? ',' (IDINT | IDSTRING) '\n'+;


//If-ElseFlow; WhileFlow
//If-Else-Add; Else-Add
//
//IF a > 3 THEN
//PRINT a
//a = a -1
//ELSE IF a = 1 THEN
//b = a
//END IF
//
//WHILE a > 3
//a = a - 1
//PRINT a
//WEND
flowcommand : ifelseflow | whileflow;
ifelseflow : 'IF' conditionflow 'THEN' '\n' ifelseadd* elseadd* 'END' 'IF' '\n'+;
whileflow : 'WHILE' conditionflow '\n' (assigncommand | maincommand | flowcommand)*  'WEND' '\n'+;

conditionflow : ((INT | IDINT) OPERATORBOOL (INT | IDINT)) | ((STRING | IDSTRING) '=' (STRING | IDSTRING));
ifelseadd : 'ELSEIF' conditionflow 'THEN' '\n' ((assigncommand | maincommand | flowcommand) '\n')+;
elseadd : 'ELSE' '\n' ((assigncommand | maincommand | flowcommand) '\n')+;

//Lexers
INT : [0-9]+;
STRING : '"' [a-zA-Z\u0400-\u04FF\0-9' ''?'':']+ '"'; 
IDINT : [a-zA-Z]([a-zA-Z0-9]*);       //MyAge
IDSTRING : [a-zA-Z]([a-zA-Z0-9]*)'$';  //MyName$ 
OPERATORMATH : '+'|'-'|'*'|'/';
OPERATORBOOL : '='|'>'|'<'|'>='|'<=';
WS : [ \t\r]+ -> skip;

1 个答案:

答案 0 :(得分:0)

与您一样,我发现以类似BASIC的语言实现if..else构造是实现的真正挑战。我在网上找到了一些好的资源。请看一下我的语法剪辑:

ifstmt
:   IF condition_block (ELSE IF condition_block)* (ELSE stmt_block)?
;

condition_block
:   expr stmt_block
;

stmt_block
:   OBRACE statement+ CBRACE
|   statement
;

我的实现(在C#访客模式中):

    public override MuValue VisitIfstmt(LISBASICParser.IfstmtContext context)
    {
        LISBASICParser.Condition_blockContext[] conditions = context.condition_block();
        bool evaluatedBlock = false;
        foreach (LISBASICParser.Condition_blockContext condition in conditions)
        {
            MuValue evaluated = Visit(condition.expr());
            if (evaluated.AsBoolean())
            {
                evaluatedBlock = true;
                Visit(condition.stmt_block());
                break;
            }
        }
        if (!evaluatedBlock && context.stmt_block() != null)
        {
            Visit(context.stmt_block());
        }
        return MuValue.Void;
    }

我借用了Bart Kiers对MuValue语言的出色表现的Mu想法。在他的项目中有很多很棒的想法。