main.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //Copyright 2013 GoGraphviz Authors
  2. //
  3. //Licensed under the Apache License, Version 2.0 (the "License");
  4. //you may not use this file except in compliance with the License.
  5. //You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. //Unless required by applicable law or agreed to in writing, software
  10. //distributed under the License is distributed on an "AS IS" BASIS,
  11. //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. //See the License for the specific language governing permissions and
  13. //limitations under the License.
  14. //A parser for the DOT grammar.
  15. package parser
  16. import (
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "github.com/awalterschulze/gographviz/ast"
  22. "github.com/awalterschulze/gographviz/internal/lexer"
  23. )
  24. //Parses a DOT string and outputs the
  25. //abstract syntax tree representing the graph.
  26. func ParseString(dotString string) (*ast.Graph, error) {
  27. return ParseBytes([]byte(dotString))
  28. }
  29. //Parses the bytes representing a DOT string
  30. //and outputs the abstract syntax tree representing the graph.
  31. func ParseBytes(dotBytes []byte) (*ast.Graph, error) {
  32. lex := lexer.NewLexer(dotBytes)
  33. parser := NewParser()
  34. st, err := parser.Parse(lex)
  35. if err != nil {
  36. return nil, err
  37. }
  38. g, ok := st.(*ast.Graph)
  39. if !ok {
  40. panic(fmt.Sprintf("Parser did not return an *ast.Graph, but rather a %T", st))
  41. }
  42. return g, nil
  43. }
  44. //Parses a reader which contains a DOT string
  45. //and outputs the abstract syntax tree representing the graph.
  46. func Parse(r io.Reader) (*ast.Graph, error) {
  47. bytes, err := ioutil.ReadAll(r)
  48. if err != nil {
  49. return nil, err
  50. }
  51. return ParseBytes(bytes)
  52. }
  53. //Parses a file which contains a DOT string
  54. //and outputs the abstract syntax tree representing the graph.
  55. func ParseFile(filename string) (*ast.Graph, error) {
  56. f, err := os.Open(filename)
  57. if err != nil {
  58. return nil, err
  59. }
  60. g, err := Parse(f)
  61. if err := f.Close(); err != nil {
  62. return nil, err
  63. }
  64. return g, err
  65. }