util.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "fmt"
  8. "go/token"
  9. "os"
  10. "os/exec"
  11. )
  12. // run runs the command argv, feeding in stdin on standard input.
  13. // It returns the output to standard output and standard error.
  14. // ok indicates whether the command exited successfully.
  15. func run(stdin []byte, argv []string) (stdout, stderr []byte, ok bool) {
  16. p := exec.Command(argv[0], argv[1:]...)
  17. p.Stdin = bytes.NewReader(stdin)
  18. var bout, berr bytes.Buffer
  19. p.Stdout = &bout
  20. p.Stderr = &berr
  21. err := p.Run()
  22. if _, ok := err.(*exec.ExitError); err != nil && !ok {
  23. fatalf("%s", err)
  24. }
  25. ok = p.ProcessState.Success()
  26. stdout, stderr = bout.Bytes(), berr.Bytes()
  27. return
  28. }
  29. func lineno(pos token.Pos) string {
  30. return fset.Position(pos).String()
  31. }
  32. // Die with an error message.
  33. func fatalf(msg string, args ...interface{}) {
  34. // If we've already printed other errors, they might have
  35. // caused the fatal condition. Assume they're enough.
  36. if nerrors == 0 {
  37. fmt.Fprintf(os.Stderr, msg+"\n", args...)
  38. }
  39. os.Exit(2)
  40. }
  41. var nerrors int
  42. func error_(pos token.Pos, msg string, args ...interface{}) {
  43. nerrors++
  44. if pos.IsValid() {
  45. fmt.Fprintf(os.Stderr, "%s: ", fset.Position(pos).String())
  46. }
  47. fmt.Fprintf(os.Stderr, msg, args...)
  48. fmt.Fprintf(os.Stderr, "\n")
  49. }
  50. // isName returns true if s is a valid C identifier
  51. func isName(s string) bool {
  52. for i, v := range s {
  53. if v != '_' && (v < 'A' || v > 'Z') && (v < 'a' || v > 'z') && (v < '0' || v > '9') {
  54. return false
  55. }
  56. if i == 0 && '0' <= v && v <= '9' {
  57. return false
  58. }
  59. }
  60. return s != ""
  61. }
  62. func creat(name string) *os.File {
  63. f, err := os.Create(name)
  64. if err != nil {
  65. fatalf("%s", err)
  66. }
  67. return f
  68. }
  69. func slashToUnderscore(c rune) rune {
  70. if c == '/' || c == '\\' || c == ':' {
  71. c = '_'
  72. }
  73. return c
  74. }