hcl/json/parse.y

185 lines
2.4 KiB
Plaintext
Raw Normal View History

2014-08-02 18:38:41 +00:00
// This is the yacc input for creating the parser for HCL JSON.
%{
package json
import (
"fmt"
"strconv"
2014-08-02 18:38:41 +00:00
"github.com/hashicorp/hcl/ast"
)
%}
%union {
array ast.ListNode
assign ast.AssignmentNode
item ast.Node
2014-08-04 04:56:50 +00:00
klist []ast.AssignmentNode
2014-08-02 18:38:41 +00:00
list []ast.Node
num int
str string
obj ast.ObjectNode
}
%type <array> array
%type <assign> pair
%type <item> value number
2014-08-02 22:44:45 +00:00
%type <klist> members
%type <list> elements
%type <num> int
2014-08-02 18:38:41 +00:00
%type <obj> object
%type <str> frac
2014-08-02 18:38:41 +00:00
%token <num> NUMBER
%token <str> COLON COMMA IDENTIFIER EQUAL NEWLINE STRING
%token <str> LEFTBRACE RIGHTBRACE LEFTBRACKET RIGHTBRACKET
%token <str> TRUE FALSE NULL MINUS PERIOD
2014-08-02 18:38:41 +00:00
%%
top:
object
{
obj := $1
jsonResult = &obj
}
object:
LEFTBRACE members RIGHTBRACE
{
$$ = ast.ObjectNode{Elem: $2}
}
| LEFTBRACE RIGHTBRACE
{
$$ = ast.ObjectNode{}
}
members:
pair
{
2014-08-04 04:56:50 +00:00
$$ = []ast.AssignmentNode{$1}
2014-08-02 18:38:41 +00:00
}
2014-08-05 04:53:39 +00:00
| members COMMA pair
2014-08-02 18:38:41 +00:00
{
2014-08-05 04:53:39 +00:00
$$ = append($1, $3)
2014-08-02 18:38:41 +00:00
}
pair:
STRING COLON value
{
2014-08-08 22:58:34 +00:00
value := $3
if obj, ok := value.(ast.ObjectNode); ok {
obj.K = $1
value = obj
}
2014-08-02 18:38:41 +00:00
$$ = ast.AssignmentNode{
2014-08-02 22:44:45 +00:00
K: $1,
2014-08-08 22:58:34 +00:00
Value: value,
2014-08-02 18:38:41 +00:00
}
}
value:
STRING
{
$$ = ast.LiteralNode{
Type: ast.ValueTypeString,
Value: $1,
}
}
| number
2014-08-02 18:38:41 +00:00
{
$$ = $1
2014-08-02 18:38:41 +00:00
}
| object
{
$$ = $1
}
| array
{
$$ = $1
}
| TRUE
{
$$ = ast.LiteralNode{
Type: ast.ValueTypeBool,
Value: true,
}
}
| FALSE
{
$$ = ast.LiteralNode{
Type: ast.ValueTypeBool,
Value: false,
}
}
| NULL
{
$$ = ast.LiteralNode{
Type: ast.ValueTypeNil,
Value: nil,
}
}
array:
LEFTBRACKET RIGHTBRACKET
{
$$ = ast.ListNode{}
}
| LEFTBRACKET elements RIGHTBRACKET
{
$$ = ast.ListNode{Elem: $2}
}
elements:
value
{
$$ = []ast.Node{$1}
}
2014-08-05 04:53:39 +00:00
| elements COMMA value
2014-08-02 18:38:41 +00:00
{
2014-08-05 04:53:39 +00:00
$$ = append($1, $3)
2014-08-02 18:38:41 +00:00
}
number:
int
{
$$ = ast.LiteralNode{
Type: ast.ValueTypeInt,
Value: $1,
}
}
| int frac
{
fs := fmt.Sprintf("%d.%s", $1, $2)
f, err := strconv.ParseFloat(fs, 64)
if err != nil {
panic(err)
}
$$ = ast.LiteralNode{
Type: ast.ValueTypeFloat,
Value: f,
}
}
int:
MINUS int
{
$$ = $2 * -1
}
| NUMBER
{
$$ = $1
}
frac:
PERIOD NUMBER
{
$$ = strconv.FormatInt(int64($2), 10)
}
2014-08-02 18:38:41 +00:00
%%