`
javaG
  • 浏览: 553135 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

实现一个Number,float的词法解析器

 
阅读更多

Number

 

 

 

package compiler.lexer;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class NumberFloat
{
    static enum Type{
        Number,Float
    }
    private  StringCharacterIterator iter = null;
    private char currentChar;
    private String currentToken="";
    
    /**
     * @param iter
     */
    public NumberFloat(String sourceCode)
    {
        this.iter = new StringCharacterIterator(sourceCode);
        this.currentChar = this.iter.first();
    }
    
    public char nextChar() 
    {
        add(this.currentChar);
        this.currentChar = iter.next();
        
        return currentChar;
    }

    public Token parse()
    {
        // 1
        if (this.currentChar == '+' || this.currentChar == '-')
        {
            this.nextChar();
            // 2
            if (isDigit())
            {
                this.nextChar();
                // 3
                digitClosure();
                if (isDone())
                {
                    return new Token(Token.Number, this.currentToken);
                }
                // 4
                else if (isPoint())
                {
                    this.nextChar();
                    // 5
                    if (isDigit())
                    {
                        this.nextChar();
                        digitClosure();
                        if (isDone())
                        {
                            return new Token(Token.Float, this.currentToken);
                        }
                    }
                }
            }

        }
        // 1
        else if (isDigit())
        {
            this.nextChar();
            // 3
            digitClosure();
            if (isDone())
            {
                return new Token(Token.Number, this.currentToken);
            }
            // 4
            else if (isPoint())
            {
                this.nextChar();
                // 5
                if (isDigit())
                {
                    this.nextChar();
                    digitClosure();
                    if (isDone())
                    {
                        return new Token(Token.Float, this.currentToken);
                    }
                }
            }
        }
        System.out.println("error char at [" + this.currentChar + "].current parsed code:[" + this.currentToken+"]");
        return null;
    }

    private void digitClosure()
    {
        while (true)
        {   
            if (isDigit()) 
            {
                this.nextChar();
                continue;
            }    
            else
                break;
        }
    }
    
    private boolean isPoint()
    {
        return this.currentChar == '.';
    }

    private boolean isDigit()
    {
        return Character.isDigit(this.currentChar);
    }
    
    private boolean isDone()
    {
        return this.currentChar == CharacterIterator.DONE;
    }
    
    private void add(char c) 
    {
        this.currentToken += c;
    }
    
    private void clear() 
    {
        this.currentToken = "";
    }
    
    public static void main(String[] args)
    {
        System.out.println(new NumberFloat("100").parse());
        System.out.println(new NumberFloat("+100").parse());
        System.out.println(new NumberFloat("-100").parse());
        System.out.println(new NumberFloat("100.1").parse());
        System.out.println(new NumberFloatV2("100.1.").parse());
//        StringCharacterIterator iter = new StringCharacterIterator("100");
//        for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
//            System.out.println(c);            
//        }
    }
}
 

 

 

package compiler.lexer;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

/**
 * 
 * 输入: <br/>
 * 输出: <br/>
 * 描述: 区别于NumberFloat,这里是使用了DFA的节点编号来实现,这种实现方式的好处是直接按照图来翻译成代码非常方便<br/>
 * 用法: <br/>
 *
 */
public class NumberFloatV2
{
    static enum Type{
        Number,Float
    }
    private  StringCharacterIterator iter = null;
    private char currentChar;
    private String currentToken="";
    private int nextNo4DFA = 1;
    private String copySourceCode;
    
    /**
     * @param iter
     */
    public NumberFloatV2(String sourceCode)
    {
        this.iter = new StringCharacterIterator(sourceCode);
        this.copySourceCode = sourceCode;
    }
    
    public char nextChar() 
    {
        add(this.currentChar);
        this.currentChar = iter.next();
        
        return currentChar;
    }

    public Token parse()
    {
        this.currentChar = iter.first();
        // 1
        if (this.currentChar == '+' || this.currentChar == '-')
        {
           
           this.nextNo4DFA = 2;
        }
        else if(isDigit()) 
        {
            this.nextNo4DFA = 3;
        }
        
        //2
        if(this.nextNo4DFA == 2) 
        {
            this.nextChar();
            if(isDigit()) 
            {
                this.nextNo4DFA = 3;
            }
        }
        
        //3
        if(this.nextNo4DFA == 3) 
        {
            this.nextChar();
            digitClosure();
            if(isDone()) 
            {
                return new Token(Token.Number, this.currentToken);
            }
            else if(isPoint()) 
            {
                this.nextNo4DFA = 4;
            }
        }
        
        //4
        if(this.nextNo4DFA == 4) 
        {
            this.nextChar();
            if(isDigit()) 
            {
                this.nextNo4DFA = 5;
            }
        }
        
        //5
        if(this.nextNo4DFA == 5) 
        {
            this.nextChar();
            digitClosure();
            if(isDone()) 
            {
                return new Token(Token.Float, this.currentToken);
            }
        }
        System.out.println("error char at [" + this.currentChar + "].current parsed code:[" + this.currentToken+"] sourceCode:["+this.copySourceCode+"]");
        return null;
    }

    private void digitClosure()
    {
        while (true)
        {   
            if (isDigit()) 
            {
                this.nextChar();
                continue;
            }    
            else
                break;
        }
    }
    
    private boolean isPoint()
    {
        return this.currentChar == '.';
    }

    private boolean isDigit()
    {
        return Character.isDigit(this.currentChar);
    }
    
    private boolean isDone()
    {
        return this.currentChar == CharacterIterator.DONE;
    }
    
    private void add(char c) 
    {
        this.currentToken += c;
    }
    
    private void clear() 
    {
        this.currentToken = "";
    }
    
    public static void main(String[] args)
    {
        System.out.println(new NumberFloatV2("100").parse());
        System.out.println(new NumberFloatV2("+100").parse());
        System.out.println(new NumberFloatV2("-100").parse());
        System.out.println(new NumberFloatV2("100.1").parse());
        System.out.println(new NumberFloatV2("100.1.").parse());
//        StringCharacterIterator iter = new StringCharacterIterator("100");
//        for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
//            System.out.println(c);            
//        }
    }
}

 

 

package compiler.lexer;
public class Token
{
    
    public static final int Number = 1;
    public static final int Float = 2;
    
    
    /**
     * @param type
     * @param name
     */
    public Token(int type, String name)
    {
        super();
        this.type = type;
        Name = name;
    }
    private int type;
    private String Name;
    /**
     * @return the type
     */
    public int getType()
    {
        return type;
    }
    /**
     * @param type the type to set
     */
    public void setType(int type)
    {
        this.type = type;
    }
    /**
     * @return the name
     */
    public String getName()
    {
        return Name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name)
    {
        Name = name;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        return "Token {Name=[" + Name + "], type=[" + type + "]}";   }

}

 

 

package compiler.lexer;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

/**
 * 
 * 输入: <br/>
 * 输出: <br/>
 * 描述: 区别于NumberFloatV2,这里是使用循环来实现,这种实现方式的好处是如果存在节点回退的情况也是可以处理的,例如从state=5编程state=2<br/>
 * 用法: <br/>
 * 
 */
public class NumberFloatV3
{
    static enum Type
    {
        Number, Float
    }

    private StringCharacterIterator iter = null;
    private char currentChar;
    private String currentToken = "";
    private int state = 1;
    private String copySourceCode;

    /**
     * @param iter
     */
    public NumberFloatV3(String sourceCode)
    {
        this.iter = new StringCharacterIterator(sourceCode);
        this.copySourceCode = sourceCode;
        this.currentChar = iter.first();
    }

    public char nextChar()
    {
        add(this.currentChar);
        this.currentChar = iter.next();

        return currentChar;
    }

    public Token parse()
    {
        boolean isError = false;
        while (true)
        {
            switch (this.state)
            {
            case 1:
                if (this.currentChar == '+' || this.currentChar == '-')
                {
                    this.state = 2;
                }
                else if (isDigit())
                {
                    this.state = 3;
                }
                else
                    isError = true;
                break;
            case 2:
                if (isDigit())
                {
                    this.state = 3;
                }
                else
                    isError = true;
                break;
            case 3:
                digitStar();
                if (isDone())
                {
                    return new Token(Token.Number, this.currentToken);
                }
                else if (isPoint())
                {
                    this.state = 4;
                }
                else
                    isError = true;
                break;
            case 4:
                if (isDigit())
                {
                    this.state = 5;
                }
                else
                    isError = true;
                break;
            case 5:
                digitStar();
                if (isDone())
                {
                    return new Token(Token.Float, this.currentToken);
                }
                else
                    isError = true;
                break;

            default:
                break;
            }
            if(isError)
                break;
            this.nextChar();
        }
        System.out.println("error char at [" + this.currentChar + "] in parsed code:[" + this.currentToken
                + this.currentChar + "]");
        return null;
    }

    private boolean digitStar()
    {
        boolean isFound = false;
        while (true)
        {
            if (isDigit())
            {
                this.nextChar();
                isFound = true;
                continue;
            }
            else
                break;
        }
        return isFound;
    }

    private boolean isPoint()
    {
        return this.currentChar == '.';
    }

    private boolean isDigit()
    {
        return Character.isDigit(this.currentChar);
    }

    private boolean isDone()
    {
        return this.currentChar == CharacterIterator.DONE;
    }

    private void add(char c)
    {
        this.currentToken += c;
    }

    private void clear()
    {
        this.currentToken = "";
    }

    public static void main(String[] args)
    {
        System.out.println(new NumberFloatV3("100").parse());
        System.out.println(new NumberFloatV3("+100").parse());
        System.out.println(new NumberFloatV3("-100").parse());
        System.out.println(new NumberFloatV3("100.1").parse());
        System.out.println(new NumberFloatV3("100.1.").parse());
        // StringCharacterIterator iter = new StringCharacterIterator("100");
        // for(char c = iter.first(); c != CharacterIterator.DONE; c =
        // iter.next()) {
        // System.out.println(c);
        // }
    }
}

 

 

package compiler.lexer;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.ThisExpression;

/**
 * 
 * 输入: <br/>
 * 输出: <br/>
 * 描述: 区别于NumberFloatV3,这里功能新增加为识别多个token<br/>
 * 用法: <br/>
 * 
 */
public class NumberFloatV4
{
    static enum Type
    {
        Number, Float
    }

    private StringCharacterIterator iter = null;
    private char currentChar;
    private String currentToken = "";
    private int state = 1;
    private String copySourceCode;

    /**
     * @param iter
     */
    public NumberFloatV4(String sourceCode)
    {
        this.iter = new StringCharacterIterator(sourceCode);
        this.copySourceCode = sourceCode;
        this.currentChar = iter.first();
    }

    public char nextChar()
    {
        if (this.currentChar != ' ')
            add(this.currentChar);
        this.currentChar = iter.next();

        return currentChar;
    }

    public List<Token> parse()
    {
        List<Token> list = new ArrayList<Token>();
        boolean isError = false;
        while (true)
        {
            //过滤空格,在识别
            if(this.currentToken.length() == 0) 
            {
                blankStar();
                if(isEnd())
                    break;
            }    
            switch (this.state)
            {
            case 1:
                if (this.currentChar == '+' || this.currentChar == '-')
                {
                    this.state = 2;
                }
                else if (isDigit())
                {
                    this.state = 3;
                }
                else
                    isError = true;
                break;
            case 2:
                if (isDigit())
                {
                    this.state = 3;
                }
                else
                    isError = true;
                break;
            case 3:
                digitStar();
                if (isDone())
                {
                    addToken(list,Token.Number);
                    break;
                }
                else if (isPoint())
                {
                    this.state = 4;
                }
                else
                    isError = true;
                break;
            case 4:
                if (isDigit())
                {
                    this.state = 5;
                }
                else
                    isError = true;
                break;
            case 5:
                digitStar();
                if (isDone())
                {
                    addToken(list,Token.Float);
                    break;
                }
                else
                    isError = true;
                break;

            default:
                break;
            }
            if(isError || isEnd())
                break;
            this.nextChar();
        }
        if (isError)
            System.out.println("error char at [" + this.currentChar + "] in parsed code:[" + this.currentToken
                    + this.currentChar + "]");
        return list;
    }

    private void addToken(List<Token> list,int type)
    {
        list.add(new Token(type, this.currentToken));

        this.state = 1;
        this.currentToken = "";
    }
    
    private boolean blankStar() 
    {
        boolean isFound = false;
        while (true)
        {
            if (isBlank())
            {
                this.nextChar();
                isFound = true;
                continue;
            }
            else
                break;
        }
        return isFound;
    }

    private boolean digitStar()
    {
        boolean isFound = false;
        while (true)
        {
            if (isDigit())
            {
                this.nextChar();
                isFound = true;
                continue;
            }
            else
                break;
        }
        return isFound;
    }
    
    private boolean isBlank()
    {
        return this.currentChar == ' ';
    }

    private boolean isPoint()
    {
        return this.currentChar == '.';
    }

    private boolean isDigit()
    {
        return Character.isDigit(this.currentChar);
    }

    private boolean isDone()
    {
        boolean isDone =  isEnd() || isBlank();
        return isDone;
    }

    private boolean isEnd()
    {
        return this.currentChar == CharacterIterator.DONE;
    }

    private void add(char c)
    {
        this.currentToken += c;
    }

    private void clear()
    {
        this.currentToken = "";
    }

    public static void main(String[] args)
    {
        System.out.println(new NumberFloatV4("100").parse());
        System.out.println(new NumberFloatV4("+100").parse());
        System.out.println(new NumberFloatV4("-100").parse());
        System.out.println(new NumberFloatV4("100.1").parse());
        System.out.println(new NumberFloatV4("100.1.").parse());
        System.out.println(new NumberFloatV4("   100.1 100 +100 -1.100 ").parse());
        // StringCharacterIterator iter = new StringCharacterIterator("100");
        // for(char c = iter.first(); c != CharacterIterator.DONE; c =
        // iter.next()) {
        // System.out.println(c);
        // }
    }
}

 

  • 大小: 4.8 KB
分享到:
评论

相关推荐

    词法语法解析器

    词法语法解析器是计算机科学中的重要组成部分,主要用于处理编程语言的输入,将源代码转换成计算机可以...理解并实现一个高效的词法语法解析器需要深入理解编译原理和语言结构,这对于软件工程师来说是一项重要的技能。

    LEX实现一个C语言子集的词法分析器

    在这个项目中,“LEX实现一个C语言子集的词法分析器”,我们需要理解以下几个关键概念: 1. **LEX 规则**:LEX 文件(.l 文件)是由一系列规则组成的,每个规则都包含一个正则表达式和相应的动作。正则表达式描述了...

    编译原理词法分析器和语法分析器的实现(C++).zip

    - 使用递归下降解析器或LL(1)解析器实现语法分析器,能够将词法单元序列转换为抽象语法树(AST)。 - 处理语法错误,如语法错误和类型错误。 **技术要求**: - 熟悉C++编程语言。 - 了解编译原理中的词法分析、...

    编译原理:词法分析器实现(C)

    在这个主题中,我们将深入探讨词法分析器(也称为扫描器或 tokenizer)的实现,这是一个编译器前端的重要组成部分。本教程以C语言为工具,将帮助你理解如何构建一个基本的词法分析器。 词法分析器是编译器的第一个...

    一个词法分析器构造过程模拟器的设计与实现_孙文明.caj

    一个词法分析器构造过程模拟器的设计与实现_孙文明.caj一个词法分析器构造过程模拟器的设计与实现_孙文明.caj一个词法分析器构造过程模拟器的设计与实现_孙文明.caj一个词法分析器构造过程模拟器的设计与实现_孙文明...

    编译原理实验一——C 语言词法分析器设计与实现

    本实验“C语言词法分析器设计与实现”旨在深入理解词法分析原理,并掌握如何构建一个能正确处理源程序中单词的程序。 在编译原理中,词法分析器(也称为扫描器)是第一个处理源代码的组件。它的主要任务是: 1. **...

    词法分析器的设计与实现

    实验原理是基于扫描到的单词符号的第一个字符的种类,分别转到相应的程序进行处理。这些程序的功能就是识别以相应字符开头的各类单词符号。 词法分析器的作用 词法分析器的作用是将源代码分解成单词符号,以便后续...

    词法分析器的设计与实现.doc

    词法分析器的实现可以分为三个步骤:扫描预处理、词法分析和输出结果。 扫描预处理的目的是将源代码转换为可供词法分析器处理的形式。这个步骤包括将源代码分割成单词符号、去除注释和空白符号等。 词法分析的目的...

    java 实现词法分析器以及语法分析器

    例如,`WordThink3.java`可能就是一个实现了词法分析功能的类,它能够识别关键字、标识符、常量、运算符等不同的Token类型。 语法分析,紧接着词法分析,是将词法分析产生的Token流转换成抽象语法树(AST)的过程。...

    本实验实现了一个c语言词法分析器,内容说明注释完整,包含可运行代码

    在这个实验中,我们关注的是如何使用C语言实现一个词法分析器,这通常是编译器设计的第一步。词法分析器的主要任务是从源代码中识别出有意义的单元,即单词,这些单词包括关键字、标识符、常量和界符。 1. **实验...

    课程设计基于C语言子集的词法分析器

    在本课程设计中,我们将专注于一个基于C语言子集的词法分析器。C语言是一门广泛使用的、静态类型的、编译型的、过程化的、通用的、大小写敏感的、不规则的编程语言,特别强调性能和可移植性。在C语言子集中,我们...

    基于java实现的语法分析器及词法分析器

    在这个项目中,我们关注的是一个基于Java实现的语法分析器和词法分析器。Java是一种广泛使用的编程语言,具有跨平台、面向对象和丰富的类库等特性,使得它成为构建这种复杂工具的理想选择。 首先,让我们深入了解...

    使用flex编写一个词法分析器

    "使用flex编写一个词法分析器" 在编译原理的实验报告中,我们需要使用flex语言编写一个词法分析器,该词法分析器能够读进一个文件,对该文件进行词法分析,并统计各类型数据的个数。 词法分析器是编译器的第一阶段...

    编译原理词法分析器源程序C语言实现

    本资源是一个使用C语言实现的编译原理词法分析器源程序,主要功能是对输入的源程序进行词法分析,识别出关键字、标识符、数字等 token,并将其输出。 1. 编译原理 编译原理是计算机科学中的一门学科,研究的是如何...

    Python 实现的 C 词法分析器

    Python 语言写的 C 语言的词法分析器,是实验报告的一个实验实现,写的很粗糙,简单看看就好了,不保证最终效果

    java实现C语言的词法分析器

    在这个项目中,我们使用Java实现了一个针对C语言的词法分析器。以下是这个实现涉及的核心知识点: 1. **词法分析**:词法分析(Lexical Analysis)是编译器前端的第一个阶段,其任务是读取源代码,识别出由字符组成...

    java实现词法分析器

    对于压缩包中的`WordsAnalyze`文件,这可能是一个包含词法分析器实现的Java源代码文件。它可能定义了一个类,用于读取输入源,识别词法单元,如关键字、标识符、常量、注释等,并将它们封装为自定义的Token对象。在...

    C++实现词法分析器.zip

    在这个名为"C++实现词法分析器"的实验中,我们将深入理解词法分析的原理,并学习如何使用C++来构建一个词法分析器。 词法分析的目的是将源代码文本转换为一系列的标记,这些标记通常包括关键字、标识符、常量、...

    Java词法分析器——C语言实现

    在这个特定的案例中,我们讨论的是一个使用C语言手动实现的Java词法分析器,而非依赖于像LEX这样的自动化工具自动生成。 词法分析器,又称为扫描器或词法分析程序,它的主要任务是识别源代码中的标识符、关键字、...

Global site tag (gtag.js) - Google Analytics