Skip to content

Instantly share code, notes, and snippets.

@blanchonvincent
Created September 8, 2019 04:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blanchonvincent/1f1cb850a436ffbb81df14eb586f52df to your computer and use it in GitHub Desktop.
Save blanchonvincent/1f1cb850a436ffbb81df14eb586f52df to your computer and use it in GitHub Desktop.
Medium - Compiler
package main
import (
"fmt"
"go/scanner"
"go/token"
"io/ioutil"
)
func main() {
// src is the input that we want to tokenize.
src, _ := ioutil.ReadFile(`main.go`)
// Initialize the scanner.
var s scanner.Scanner
fset := token.NewFileSet() // positions are relative to fset
file := fset.AddFile("", fset.Base(), len(src)) // register input "file"
s.Init(file, src, nil /* no error handler */, scanner.ScanComments)
// Repeated calls to Scan yield the token sequence found in the input.
for {
pos, tok, lit := s.Scan()
if tok == token.EOF {
break
}
fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment