imports.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package generator
  2. import (
  3. "github.com/jcla1/gisp/parser"
  4. "go/ast"
  5. "go/token"
  6. )
  7. func getImports(node *parser.CallNode) ast.Decl {
  8. if len(node.Args) < 2 {
  9. return nil
  10. }
  11. imports := node.Args[1:]
  12. specs := make([]ast.Spec, len(imports))
  13. for i, imp := range imports {
  14. if t := imp.Type(); t == parser.NodeVector {
  15. specs[i] = makeImportSpecFromVector(imp.(*parser.VectorNode))
  16. } else if t == parser.NodeString {
  17. path := makeBasicLit(token.STRING, imp.(*parser.StringNode).Value)
  18. specs[i] = makeImportSpec(path, nil)
  19. } else {
  20. panic("invalid import!")
  21. }
  22. }
  23. decl := makeGeneralDecl(token.IMPORT, specs)
  24. decl.Lparen = token.Pos(1) // Need this so we can have multiple imports
  25. return decl
  26. }
  27. func makeImportSpecFromVector(vect *parser.VectorNode) *ast.ImportSpec {
  28. if len(vect.Nodes) < 3 {
  29. panic("invalid use of import!")
  30. }
  31. if vect.Nodes[0].Type() != parser.NodeString {
  32. panic("invalid use of import!")
  33. }
  34. pathString := vect.Nodes[0].(*parser.StringNode).Value
  35. path := makeBasicLit(token.STRING, pathString)
  36. if vect.Nodes[1].Type() != parser.NodeIdent || vect.Nodes[1].(*parser.IdentNode).Ident != ":as" {
  37. panic("invalid use of import! expecting: \":as\"!!!")
  38. }
  39. name := ast.NewIdent(vect.Nodes[2].(*parser.IdentNode).Ident)
  40. return makeImportSpec(path, name)
  41. }
  42. func makeImportSpec(path *ast.BasicLit, name *ast.Ident) *ast.ImportSpec {
  43. return &ast.ImportSpec{
  44. Path: path,
  45. Name: name,
  46. }
  47. }