登录
首页 >  Golang >  Go问答

错误遇见 - 在 golang 中实现词法分析器时,所有 goroutine 均处于休眠状态

来源:stackoverflow

时间:2024-02-23 16:18:24 101浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《错误遇见 - 在 golang 中实现词法分析器时,所有 goroutine 均处于休眠状态》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在尝试用 go 编写一个扫描器/词法分析器,我想我会弄清楚它,在尝试实现之后我遇到了标题中提到的错误。有什么建议吗?

本质上,我正在尝试根据 rob pike 在 2011 年 go 会议上演讲中的信息来实现一个扫描器。他谈到使用有限状态机以类似于以下的方式实现扫描器: p>

输入状态函数(s *扫描仪)状态

基本上是一个递归结构,在我的状态实现中,在我的发射函数中,我试图打印有关正在接收的令牌的详细信息。

package scanner

/*
a scanner initializes itself to scan a string/file, then launches a goroutine
that returns the scanner and a channel of items to be tokenized! 
*/
import (
    t "cprl/token"
    "fmt"
    "io/ioutil"
    "log"
    "strings"
    // "unicode"
)

//scanner - performs lexical analysis

    type scanner struct {
        ch rune //character examined

        file  string //the name of our current file, used for error reporting
        input string //the string currently being scanned

        start int //start position of our token
        curr  int //current position in input
        line  int //current line we are scanning
        width int //the size of last rune read

        tokens chan t.token //channel of scanned tokens!

    }


    func (s scanner) string() string {
        var str []string

        if s.file != "" {
            str = append(str, s.file+": ")
        }

        return strings.join(str, "")
    }

//scan - create a new scanner for current input
func scan(file string) *scanner {
    buf, err := ioutil.readfile(file)
    if err != nil {
        log.fatal(err)
    }

    in := string(buf)
    s := &scanner{
        file:   file,
        input:  in,
        line:   1,
        tokens: make(chan t.token),
    }
    go s.init()
    return s
}

//init - initialize a created a scanner

    func (s *scanner) init() {
        for state := scanto; state != nil; {
            state = state(s)
            fmt.println("state entered")
        }
    }

我正在尝试将所有标记打印为字符串,并在另一个包中使用如下所示的代码

for tok := range t.Tokens {
  fmt.Println(tok.String())
}

这里,我们有 rob pike 在 go 会议上演讲的幻灯片: https://talks.golang.org/2011/lex.slide#1

这是我目前正在进行的项目。 https://github.com/apheuz/cprl


解决方案


频道被阻塞。

您的来电

for tok := range s.tokens

将阻塞,直到有人写入通道或关闭它..

但没有人会!

好了,本文到此结束,带大家了解了《错误遇见 - 在 golang 中实现词法分析器时,所有 goroutine 均处于休眠状态》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>