Skip to content

Commit

Permalink
Parse returns error instead of terminating with log.Fatalf
Browse files Browse the repository at this point in the history
  • Loading branch information
its-luca committed Aug 4, 2022
1 parent c4b3d54 commit 84ede81
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 78 deletions.
19 changes: 13 additions & 6 deletions bibtex.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package bibtex
import (
"bytes"
"fmt"
"log"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -272,16 +271,24 @@ func (bib *BibTex) AddStringVar(key string, val BibString) {
}

// GetStringVar looks up a string by its key.
func (bib *BibTex) GetStringVar(key string) *BibVar {
func (bib *BibTex) GetStringVar(key string) (*BibVar, error) {
if bv, ok := bib.StringVar[key]; ok {
return bv
return bv, nil
}
if v, ok := bib.getDefaultVar(key); ok {
return v
return v, nil
}
// This is undefined.
log.Fatalf("%s: %s", ErrUnknownStringVar, key)
return nil
return nil, fmt.Errorf("%s: %s", ErrUnknownStringVar, key)
}

// MustGetStringVar is like GetStringVar but panics on errors
func (bib *BibTex) MustGetStringVar(key string) *BibVar {
v, err := bib.GetStringVar(key)
if err != nil {
panic(err)
}
return v
}

// getDefaultVar is a fallback for looking up keys (e.g. 3-character month)
Expand Down
17 changes: 13 additions & 4 deletions bibtex.y
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bibtex

import (
"io"
"fmt"
)

type bibTag struct {
Expand Down Expand Up @@ -60,9 +61,9 @@ preambleentry : tATSIGN tPREAMBLE tLBRACE longstring tRBRACE { $$ = $4 }
;

longstring : tIDENT { $$ = NewBibConst($1) }
| tBAREIDENT { $$ = bib.GetStringVar($1) }
| tBAREIDENT { v,err := bib.GetStringVar($1); if err != nil { bibtexlex.Error(fmt.Sprintf("%v",err)) } else {$$ = v} }
| longstring tPOUND tIDENT { $$ = NewBibComposite($1); $$.(*BibComposite).Append(NewBibConst($3))}
| longstring tPOUND tBAREIDENT { $$ = NewBibComposite($1); $$.(*BibComposite).Append(bib.GetStringVar($3)) }
| longstring tPOUND tBAREIDENT { $$ = NewBibComposite($1); v,err := bib.GetStringVar($3); if err != nil {bibtexlex.Error(fmt.Sprintf("%v",err))} else {$$.(*BibComposite).Append(v)} }
;

tag : /* empty */ { }
Expand All @@ -82,8 +83,16 @@ func Parse(r io.Reader) (*BibTex, error) {
select {
case err := <-l.Errors: // Non-yacc errors
return nil, err
case err := <-l.ParseErrors:
return nil, err
case err := <-l.ParseErrors: //yacc errors
//It can happen that both channels contain an error. In that scenario, l.Errors usually contains
//the more user friendly version. Thus we suppress the other error
select {
case err := <-l.Errors:
return nil,err
default :
return nil, err

}
default:
return bib, nil
}
Expand Down
Loading

0 comments on commit 84ede81

Please sign in to comment.