gantt.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // Package parser provides Gantt chart parsing based on gantt.jison
  2. package parser
  3. import (
  4. "fmt"
  5. "strings"
  6. "mermaid-go/pkg/ast"
  7. "mermaid-go/pkg/lexer"
  8. )
  9. // GanttParser implements Gantt chart parsing following gantt.jison
  10. type GanttParser struct {
  11. tokens []lexer.Token
  12. current int
  13. diagram *ast.GanttDiagram
  14. }
  15. // NewGanttParser creates a new Gantt parser
  16. func NewGanttParser() *GanttParser {
  17. return &GanttParser{
  18. diagram: &ast.GanttDiagram{
  19. DateFormat: "YYYY-MM-DD",
  20. AxisFormat: "%Y-%m-%d",
  21. Sections: make([]*ast.GanttSection, 0),
  22. Tasks: make([]*ast.GanttTask, 0),
  23. Config: make(map[string]any),
  24. },
  25. }
  26. }
  27. // Parse parses Gantt chart syntax
  28. func (p *GanttParser) Parse(input string) (*ast.GanttDiagram, error) {
  29. // Tokenize
  30. l := lexer.NewLexer(input)
  31. tokens, err := l.Tokenize()
  32. if err != nil {
  33. return nil, fmt.Errorf("lexical analysis failed: %w", err)
  34. }
  35. // Filter tokens
  36. p.tokens = lexer.FilterTokens(tokens)
  37. p.current = 0
  38. p.diagram = &ast.GanttDiagram{
  39. DateFormat: "YYYY-MM-DD",
  40. AxisFormat: "%Y-%m-%d",
  41. Sections: make([]*ast.GanttSection, 0),
  42. Tasks: make([]*ast.GanttTask, 0),
  43. Config: make(map[string]any),
  44. }
  45. // Parse document
  46. err = p.parseDocument()
  47. if err != nil {
  48. return nil, fmt.Errorf("syntax analysis failed: %w", err)
  49. }
  50. return p.diagram, nil
  51. }
  52. // parseDocument parses the Gantt chart document
  53. func (p *GanttParser) parseDocument() error {
  54. // Expect gantt
  55. if !p.check(lexer.TokenID) || p.peek().Value != "gantt" {
  56. return p.error("expected 'gantt'")
  57. }
  58. p.advance()
  59. // Parse statements
  60. for !p.isAtEnd() {
  61. if err := p.parseStatement(); err != nil {
  62. return err
  63. }
  64. }
  65. return nil
  66. }
  67. // parseStatement parses individual Gantt chart statements
  68. func (p *GanttParser) parseStatement() error {
  69. if p.isAtEnd() {
  70. return nil
  71. }
  72. switch {
  73. case p.check(lexer.TokenNewline):
  74. p.advance() // Skip newlines
  75. return nil
  76. case p.checkKeyword("title"):
  77. return p.parseTitle()
  78. case p.checkKeyword("dateFormat"):
  79. return p.parseDateFormat()
  80. case p.checkKeyword("axisFormat"):
  81. return p.parseAxisFormat()
  82. case p.checkKeyword("section"):
  83. return p.parseSection()
  84. case p.check(lexer.TokenID):
  85. // Task definition
  86. return p.parseTask()
  87. default:
  88. token := p.peek()
  89. return p.error(fmt.Sprintf("unexpected token: %s", token.Value))
  90. }
  91. }
  92. // parseTitle parses title statements
  93. func (p *GanttParser) parseTitle() error {
  94. p.advance() // consume 'title'
  95. var titleParts []string
  96. for !p.check(lexer.TokenNewline) && !p.isAtEnd() {
  97. titleParts = append(titleParts, p.advance().Value)
  98. }
  99. if len(titleParts) > 0 {
  100. title := strings.TrimSpace(strings.Join(titleParts, " "))
  101. p.diagram.Title = &title
  102. }
  103. return nil
  104. }
  105. // parseDateFormat parses dateFormat statements
  106. func (p *GanttParser) parseDateFormat() error {
  107. p.advance() // consume 'dateFormat'
  108. var formatParts []string
  109. for !p.check(lexer.TokenNewline) && !p.isAtEnd() {
  110. formatParts = append(formatParts, p.advance().Value)
  111. }
  112. if len(formatParts) > 0 {
  113. p.diagram.DateFormat = strings.TrimSpace(strings.Join(formatParts, " "))
  114. }
  115. return nil
  116. }
  117. // parseAxisFormat parses axisFormat statements
  118. func (p *GanttParser) parseAxisFormat() error {
  119. p.advance() // consume 'axisFormat'
  120. var formatParts []string
  121. for !p.check(lexer.TokenNewline) && !p.isAtEnd() {
  122. formatParts = append(formatParts, p.advance().Value)
  123. }
  124. if len(formatParts) > 0 {
  125. p.diagram.AxisFormat = strings.TrimSpace(strings.Join(formatParts, " "))
  126. }
  127. return nil
  128. }
  129. // parseSection parses section statements
  130. func (p *GanttParser) parseSection() error {
  131. p.advance() // consume 'section'
  132. var sectionParts []string
  133. for !p.check(lexer.TokenNewline) && !p.isAtEnd() {
  134. sectionParts = append(sectionParts, p.advance().Value)
  135. }
  136. if len(sectionParts) > 0 {
  137. sectionName := strings.TrimSpace(strings.Join(sectionParts, " "))
  138. section := &ast.GanttSection{
  139. Name: sectionName,
  140. Tasks: make([]*ast.GanttTask, 0),
  141. }
  142. p.diagram.Sections = append(p.diagram.Sections, section)
  143. }
  144. return nil
  145. }
  146. // parseTask parses task definitions
  147. func (p *GanttParser) parseTask() error {
  148. // Parse task name (may be multiple words)
  149. var taskNameParts []string
  150. for !p.check(lexer.TokenColon) && !p.isAtEnd() {
  151. if p.check(lexer.TokenID) || p.check(lexer.TokenNumber) {
  152. taskNameParts = append(taskNameParts, p.advance().Value)
  153. } else {
  154. break
  155. }
  156. }
  157. if len(taskNameParts) == 0 {
  158. return p.error("expected task name")
  159. }
  160. taskName := strings.Join(taskNameParts, " ")
  161. // Expect colon
  162. if !p.check(lexer.TokenColon) {
  163. return p.error("expected ':' after task name")
  164. }
  165. p.advance()
  166. // Check if there's a task ID immediately after colon
  167. var taskID string
  168. if p.check(lexer.TokenID) && !p.checkKeyword("after") && !p.checkKeyword("done") && !p.checkKeyword("active") && !p.checkKeyword("crit") {
  169. taskID = p.advance().Value
  170. // Skip comma if present
  171. if p.check(lexer.TokenComma) {
  172. p.advance()
  173. }
  174. }
  175. // Parse task data
  176. var taskDataParts []string
  177. for !p.check(lexer.TokenNewline) && !p.isAtEnd() {
  178. taskDataParts = append(taskDataParts, p.advance().Value)
  179. }
  180. taskData := strings.TrimSpace(strings.Join(taskDataParts, " "))
  181. // Parse task data components
  182. task := &ast.GanttTask{
  183. ID: generateTaskID(taskName),
  184. Name: taskName,
  185. Status: ast.GanttStatusActive,
  186. Dependencies: make([]string, 0),
  187. }
  188. // Use taskID if provided
  189. if taskID != "" {
  190. task.Dependencies = append(task.Dependencies, taskID)
  191. }
  192. // Parse task data (status, dates, dependencies)
  193. if taskData != "" {
  194. // Split by comma first, then by spaces within each part
  195. parts := strings.Split(taskData, ",")
  196. for _, part := range parts {
  197. part = strings.TrimSpace(part)
  198. if part == "" {
  199. continue
  200. }
  201. // Check for status keywords
  202. switch strings.ToLower(part) {
  203. case "active":
  204. task.Status = ast.GanttStatusActive
  205. case "done":
  206. task.Status = ast.GanttStatusDone
  207. case "crit":
  208. task.Status = ast.GanttStatusCrit
  209. default:
  210. // Try to parse as date or duration
  211. if strings.Contains(part, "-") && len(part) >= 8 {
  212. // Looks like a date
  213. if task.Start == nil {
  214. task.Start = &part
  215. } else if task.End == nil {
  216. task.End = &part
  217. }
  218. } else if strings.HasSuffix(part, "d") || strings.HasSuffix(part, "w") || strings.HasSuffix(part, "m") || strings.HasSuffix(part, "y") {
  219. // Looks like a duration
  220. task.Duration = &part
  221. } else if strings.HasPrefix(part, "after") {
  222. // This is a dependency
  223. task.Dependencies = append(task.Dependencies, part)
  224. } else {
  225. // Could be a task ID or other identifier
  226. task.Dependencies = append(task.Dependencies, part)
  227. }
  228. }
  229. }
  230. }
  231. // Add task to current section or global tasks
  232. if len(p.diagram.Sections) > 0 {
  233. currentSection := p.diagram.Sections[len(p.diagram.Sections)-1]
  234. currentSection.Tasks = append(currentSection.Tasks, task)
  235. }
  236. p.diagram.Tasks = append(p.diagram.Tasks, task)
  237. return nil
  238. }
  239. // generateTaskID generates a unique task ID from task name
  240. func generateTaskID(name string) string {
  241. // Simple ID generation - replace spaces with underscores and make lowercase
  242. id := strings.ToLower(strings.ReplaceAll(name, " ", "_"))
  243. return id
  244. }
  245. // Helper methods
  246. func (p *GanttParser) check(tokenType lexer.TokenType) bool {
  247. if p.isAtEnd() {
  248. return false
  249. }
  250. return p.peek().Type == tokenType
  251. }
  252. func (p *GanttParser) checkKeyword(keyword string) bool {
  253. if p.isAtEnd() {
  254. return false
  255. }
  256. token := p.peek()
  257. return token.Type == lexer.TokenID && strings.ToLower(token.Value) == strings.ToLower(keyword)
  258. }
  259. func (p *GanttParser) advance() lexer.Token {
  260. if !p.isAtEnd() {
  261. p.current++
  262. }
  263. return p.previous()
  264. }
  265. func (p *GanttParser) isAtEnd() bool {
  266. return p.current >= len(p.tokens) || p.peek().Type == lexer.TokenEOF
  267. }
  268. func (p *GanttParser) peek() lexer.Token {
  269. if p.current >= len(p.tokens) {
  270. return lexer.Token{Type: lexer.TokenEOF}
  271. }
  272. return p.tokens[p.current]
  273. }
  274. func (p *GanttParser) previous() lexer.Token {
  275. if p.current <= 0 {
  276. return lexer.Token{Type: lexer.TokenEOF}
  277. }
  278. return p.tokens[p.current-1]
  279. }
  280. func (p *GanttParser) error(message string) error {
  281. token := p.peek()
  282. return fmt.Errorf("parse error at line %d, column %d: %s (got %s)",
  283. token.Line, token.Column, message, token.Type.String())
  284. }