Add double-curly blocks

This commit is contained in:
Nigel Tao committed 2020-04-02 21:56:53 +11:00
1 parent 4cfc367a9b
commit 3fe3f84106
8 files changed
+107 -56

No files matched your search

+1
View File
@@ -14,6 +14,7 @@
- Added `std/wbmp`. - Added `std/wbmp`.
- Added `WUFFS_BASE__PIXEL_BLEND__SRC_OVER`. - Added `WUFFS_BASE__PIXEL_BLEND__SRC_OVER`.
- Added `WUFFS_BASE__PIXEL_FORMAT__BGR_565`. - Added `WUFFS_BASE__PIXEL_FORMAT__BGR_565`.
- Added double-curly blocks.
- Added interfaces. - Added interfaces.
- Added preprocessor. - Added preprocessor.
- Added single-quoted strings. - Added single-quoted strings.
+4
View File
@@ -30,6 +30,10 @@ Minor features or restrictions include:
- Labeled jumps look like `break.loopname` and `continue.loopname`, for a - Labeled jumps look like `break.loopname` and `continue.loopname`, for a
matching `while.loopname`. The `while.loopname`'s closing curly brace must be matching `while.loopname`. The `while.loopname`'s closing curly brace must be
followed by `endwhile.loopname`. followed by `endwhile.loopname`.
- A `while true` loop's block may use double-curly braces: `{{` and `}}`. The
formatter will not add an indent to the code inside the block. This is useful
when using `while true {{ etc; break; etc; break }}` to simulate what would
be a (forwards) `goto` in other languages' straight-line code.
Wuffs code is formatted by the Wuffs code is formatted by the
[`wuffsfmt`](https://godoc.org/github.com/google/wuffs/cmd/wuffsfmt) program. [`wuffsfmt`](https://godoc.org/github.com/google/wuffs/cmd/wuffsfmt) program.
+42 -13
View File
@@ -205,7 +205,7 @@ func (p *parser) parseTopLevelDecl() (*a.Node, error) {
} }
p.allowVar = true p.allowVar = true
body, err := p.parseBlock() body, err := p.parseBlock(false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -341,11 +341,13 @@ func (p *parser) parseList(stop t.ID, parseElem func(*parser) (*a.Node, error))
ret := []*a.Node(nil) ret := []*a.Node(nil)
for len(p.src) > 0 { for len(p.src) > 0 {
if p.src[0].ID == stop { if id := p.src[0].ID; id == stop {
if stop == t.IDCloseParen || stop == t.IDCloseBracket { if stop == t.IDCloseParen || stop == t.IDCloseBracket {
p.src = p.src[1:] p.src = p.src[1:]
} }
return ret, nil return ret, nil
} else if (stop == t.IDOpenDoubleCurly) && (id == t.IDOpenCurly) {
return ret, nil
} }
elem, err := parseElem(p) elem, err := parseElem(p)
@@ -531,18 +533,34 @@ func (p *parser) parseBracket(sep t.ID) (op t.ID, ei *a.Expr, ej *a.Expr, err er
return sep, ei, ej, nil return sep, ei, ej, nil
} }
func (p *parser) parseBlock() ([]*a.Node, error) { func (p *parser) parseBlock(doubleCurly bool) ([]*a.Node, error) {
if doubleCurly {
if x := p.peek1(); x != t.IDOpenDoubleCurly {
got := p.tm.ByID(x)
return nil, fmt.Errorf(`parse: expected "{{", got %q at %s:%d`, got, p.filename, p.line())
}
} else {
if x := p.peek1(); x != t.IDOpenCurly { if x := p.peek1(); x != t.IDOpenCurly {
got := p.tm.ByID(x) got := p.tm.ByID(x)
return nil, fmt.Errorf(`parse: expected "{", got %q at %s:%d`, got, p.filename, p.line()) return nil, fmt.Errorf(`parse: expected "{", got %q at %s:%d`, got, p.filename, p.line())
} }
}
p.src = p.src[1:] p.src = p.src[1:]
block := []*a.Node(nil) block := []*a.Node(nil)
for len(p.src) > 0 { for {
if len(p.src) == 0 {
return nil, fmt.Errorf(`parse: expected "}" or "}}" at %s:%d`, p.filename, p.line())
}
if doubleCurly {
if p.src[0].ID == t.IDCloseDoubleCurly {
break
}
} else {
if p.src[0].ID == t.IDCloseCurly { if p.src[0].ID == t.IDCloseCurly {
p.src = p.src[1:] break
return block, nil }
} }
s, err := p.parseStatement() s, err := p.parseStatement()
@@ -557,7 +575,9 @@ func (p *parser) parseBlock() ([]*a.Node, error) {
} }
p.src = p.src[1:] p.src = p.src[1:]
} }
return nil, fmt.Errorf(`parse: expected "}" at %s:%d`, p.filename, p.line())
p.src = p.src[1:]
return block, nil
} }
func (p *parser) assertsSorted(asserts []*a.Node) error { func (p *parser) assertsSorted(asserts []*a.Node) error {
@@ -735,7 +755,12 @@ func (p *parser) parseStatement1() (*a.Node, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
body, err := p.parseBlock() doubleCurly := p.peek1() == t.IDOpenDoubleCurly
if doubleCurly && ((condition.Operator() != 0) || (condition.Ident() != t.IDTrue)) {
return nil, fmt.Errorf(`parse: double {{ }} while loop condition isn't "true" at %s:%d`,
p.filename, p.line())
}
body, err := p.parseBlock(doubleCurly)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -747,6 +772,10 @@ func (p *parser) parseStatement1() (*a.Node, error) {
return nil, fmt.Errorf(`parse: expected endwhile%s at %s:%d`, return nil, fmt.Errorf(`parse: expected endwhile%s at %s:%d`,
dotLabel, p.filename, p.line()) dotLabel, p.filename, p.line())
} }
if doubleCurly && !a.Terminates(body) {
return nil, fmt.Errorf(`parse: double {{ }} while loop doesn't terminate at %s:%d`,
p.filename, p.line())
}
return a.NewWhile(label, condition, asserts, body).AsNode(), nil return a.NewWhile(label, condition, asserts, body).AsNode(), nil
} }
return p.parseAssignNode() return p.parseAssignNode()
@@ -838,7 +867,7 @@ func (p *parser) parseAsserts() ([]*a.Node, error) {
if p.peek1() == t.IDComma { if p.peek1() == t.IDComma {
p.src = p.src[1:] p.src = p.src[1:]
var err error var err error
if asserts, err = p.parseList(t.IDOpenCurly, (*parser).parseAssertNode); err != nil { if asserts, err = p.parseList(t.IDOpenDoubleCurly, (*parser).parseAssertNode); err != nil {
return nil, err return nil, err
} }
if err := p.assertsSorted(asserts); err != nil { if err := p.assertsSorted(asserts); err != nil {
@@ -916,7 +945,7 @@ func (p *parser) parseIOBindNode() (*a.Node, error) {
} }
p.src = p.src[1:] p.src = p.src[1:]
body, err := p.parseBlock() body, err := p.parseBlock(false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -938,7 +967,7 @@ func (p *parser) parseIf() (*a.If, error) {
return nil, fmt.Errorf(`parse: if-condition %q is not effect-free at %s:%d`, return nil, fmt.Errorf(`parse: if-condition %q is not effect-free at %s:%d`,
condition.Str(p.tm), p.filename, p.line()) condition.Str(p.tm), p.filename, p.line())
} }
bodyIfTrue, err := p.parseBlock() bodyIfTrue, err := p.parseBlock(false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -951,7 +980,7 @@ func (p *parser) parseIf() (*a.If, error) {
return nil, err return nil, err
} }
} else { } else {
bodyIfFalse, err = p.parseBlock() bodyIfFalse, err = p.parseBlock(false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1042,7 +1071,7 @@ func (p *parser) parseIterateBlock(label t.ID, assigns []*a.Node) (*a.Iterate, e
if err != nil { if err != nil {
return nil, err return nil, err
} }
body, err := p.parseBlock() body, err := p.parseBlock(false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+7 -3
View File
@@ -110,9 +110,11 @@ func Render(w io.Writer, tm *t.Map, src []t.Token, comments []string) (err error
// line containing the matching open token. // line containing the matching open token.
buf = buf[:0] buf = buf[:0]
indentAdjustment := 0 indentAdjustment := 0
if lineTokens[0].ID.IsClose() { if id := lineTokens[0].ID; id == t.IDCloseDoubleCurly {
// No-op.
} else if id.IsClose() {
indentAdjustment-- indentAdjustment--
} else if hanging && lineTokens[0].ID != t.IDOpenCurly { } else if hanging && ((id != t.IDOpenCurly) && (id != t.IDOpenDoubleCurly)) {
indentAdjustment++ indentAdjustment++
} }
buf = appendTabs(buf, indent+indentAdjustment) buf = appendTabs(buf, indent+indentAdjustment)
@@ -189,7 +191,9 @@ func Render(w io.Writer, tm *t.Map, src []t.Token, comments []string) (err error
} }
commentLine = line + 1 commentLine = line + 1
prevLine = line prevLine = line
prevLineHanging = prevLineHanging && lineTokens[len(lineTokens)-1].ID != t.IDOpenCurly lastID := lineTokens[len(lineTokens)-1].ID
prevLineHanging = prevLineHanging &&
(lastID != t.IDOpenCurly) && (lastID != t.IDOpenDoubleCurly)
} }
// Print any trailing comments. // Print any trailing comments.
+15 -5
View File
@@ -245,6 +245,7 @@ const (
IDOpenParen = ID(0x10) IDOpenParen = ID(0x10)
IDOpenBracket = ID(0x11) IDOpenBracket = ID(0x11)
IDOpenCurly = ID(0x12) IDOpenCurly = ID(0x12)
IDOpenDoubleCurly = ID(0x13)
minClose = 0x18 minClose = 0x18
maxClose = 0x1F maxClose = 0x1F
@@ -252,6 +253,7 @@ const (
IDCloseParen = ID(0x18) IDCloseParen = ID(0x18)
IDCloseBracket = ID(0x19) IDCloseBracket = ID(0x19)
IDCloseCurly = ID(0x1A) IDCloseCurly = ID(0x1A)
IDCloseDoubleCurly = ID(0x1B)
) )
const ( const (
@@ -671,12 +673,14 @@ var builtInsByID = [nBuiltInIDs]string{
IDColon: ":", IDColon: ":",
IDOpenParen: "(", IDOpenParen: "(",
IDCloseParen: ")",
IDOpenBracket: "[", IDOpenBracket: "[",
IDCloseBracket: "]",
IDOpenCurly: "{", IDOpenCurly: "{",
IDOpenDoubleCurly: "{{",
IDCloseParen: ")",
IDCloseBracket: "]",
IDCloseCurly: "}", IDCloseCurly: "}",
IDCloseDoubleCurly: "}}",
IDPlusEq: "+=", IDPlusEq: "+=",
IDMinusEq: "-=", IDMinusEq: "-=",
@@ -1029,8 +1033,6 @@ var squiggles = [256]ID{
')': IDCloseParen, ')': IDCloseParen,
'[': IDOpenBracket, '[': IDOpenBracket,
']': IDCloseBracket, ']': IDCloseBracket,
'{': IDOpenCurly,
'}': IDCloseCurly,
',': IDComma, ',': IDComma,
'!': IDExclam, '!': IDExclam,
@@ -1105,6 +1107,14 @@ var lexers = [256][]suffixLexer{
{"=", IDGreaterEq}, {"=", IDGreaterEq},
{"", IDGreaterThan}, {"", IDGreaterThan},
}, },
'{': {
{"{", IDOpenDoubleCurly},
{"", IDOpenCurly},
},
'}': {
{"}", IDCloseDoubleCurly},
{"", IDCloseCurly},
},
'~': { '~': {
{"mod<<=", IDTildeModShiftLEq}, {"mod<<=", IDTildeModShiftLEq},
{"mod<<", IDTildeModShiftL}, {"mod<<", IDTildeModShiftL},
+3 -2
View File
@@ -544,7 +544,7 @@ pri func config_decoder.decode_ae?(src: base.io_reader) {
var is_iccp : base.bool var is_iccp : base.bool
var is_xmp : base.bool var is_xmp : base.bool
while.goto_done true { while.goto_done true {{
block_size = args.src.read_u8?() block_size = args.src.read_u8?()
if block_size == 0 { if block_size == 0 {
return ok return ok
@@ -642,7 +642,8 @@ pri func config_decoder.decode_ae?(src: base.io_reader) {
} }
break.goto_done break.goto_done
} endwhile.goto_done }} endwhile.goto_done
this.skip_blocks?(src: args.src) this.skip_blocks?(src: args.src)
} }
+3 -2
View File
@@ -619,7 +619,7 @@ pri func decoder.decode_ae?(src: base.io_reader) {
var is_iccp : base.bool var is_iccp : base.bool
var is_xmp : base.bool var is_xmp : base.bool
while.goto_done true { while.goto_done true {{
block_size = args.src.read_u8?() block_size = args.src.read_u8?()
if block_size == 0 { if block_size == 0 {
return ok return ok
@@ -717,7 +717,8 @@ pri func decoder.decode_ae?(src: base.io_reader) {
} }
break.goto_done break.goto_done
} endwhile.goto_done }} endwhile.goto_done
this.skip_blocks?(src: args.src) this.skip_blocks?(src: args.src)
} }
+32 -31
View File
@@ -157,7 +157,7 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
expect = 0x1EB2 // EXPECT_VALUE expect = 0x1EB2 // EXPECT_VALUE
while.outer true { while.outer true {
while.goto_parsed_a_leaf_value true { while.goto_parsed_a_leaf_value true {{
if args.dst.available() <= 0 { if args.dst.available() <= 0 {
yield? base."$short write" yield? base."$short write"
continue.outer continue.outer
@@ -225,10 +225,10 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
return "#bad input" return "#bad input"
} }
// These assertions are redundant (the Wuffs compiler should // These assertions are redundant (the Wuffs compiler should already
// already know these facts; deleting these assertions should still // know these facts; deleting these assertions should still compile)
// compile) but are listed explicitly to guard against future edits // but are listed explicitly to guard against future edits to the code
// to the code above inadvertently invalidating these assertions. // above inadvertently invalidating these assertions.
assert args.dst.available() > 0 assert args.dst.available() > 0
assert args.src.available() > 0 assert args.src.available() > 0
@@ -269,7 +269,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
continue.string_loop_outer continue.string_loop_outer
} }
// As an optimization, consume non-special ASCII 4 bytes at a time. // As an optimization, consume non-special ASCII 4 bytes at
// a time.
while args.src.available() > 4, while args.src.available() > 4,
inv args.dst.available() > 0, inv args.dst.available() > 0,
inv args.src.available() > 0, inv args.src.available() > 0,
@@ -397,9 +398,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
uni4_value |= ((c & 0x0F) as base.u32) << 0 uni4_value |= ((c & 0x0F) as base.u32) << 0
if uni4_ok == 0 { if uni4_ok == 0 {
// It wasn't 4 hexadecimal digits. No-op // It wasn't 4 hexadecimal digits. No-op (and
// (and fall through to "#bad // fall through to "#bad backslash-escape").
// backslash-escape").
} else if (uni4_value < 0xD800) or (0xDFFF < uni4_value) { } else if (uni4_value < 0xD800) or (0xDFFF < uni4_value) {
// Not a Unicode surrogate. We're good. // Not a Unicode surrogate. We're good.
@@ -412,15 +412,15 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
continue.string_loop_outer continue.string_loop_outer
} else if uni4_value >= 0xDC00 { } else if uni4_value >= 0xDC00 {
// Low surrogate. No-op (and fall through // Low surrogate. No-op (and fall through to
// to "#bad backslash-escape"). // "#bad backslash-escape").
} else { } else {
// High surrogate, which needs to be // High surrogate, which needs to be followed
// followed by a "\\u1234" low surrogate. // by a "\\u1234" low surrogate. We've already
// We've already peeked 6 bytes for the // peeked 6 bytes for the high surrogate. We
// high surrogate. We need 12 in total: // need 12 in total: another 8 bytes at an
// another 8 bytes at an offset of 4. // offset of 4.
if args.src.available() < 12 { if args.src.available() < 12 {
if args.src.is_closed() { if args.src.is_closed() {
if this.quirk_enabled_replace_invalid_unicode { if this.quirk_enabled_replace_invalid_unicode {
@@ -472,7 +472,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
if (uni4_ok <> 0) and if (uni4_ok <> 0) and
(0xDC00 <= uni4_value) and (uni4_value <= 0xDFFF) { (0xDC00 <= uni4_value) and (uni4_value <= 0xDFFF) {
// Emit a single token for the surrogate pair. // Emit a single token for the surrogate
// pair.
uni4_value -= 0xDC00 uni4_value -= 0xDC00
args.src.skip32_fast!(actual: 12, worst_case: 12) args.src.skip32_fast!(actual: 12, worst_case: 12)
args.dst.write_simple_token_fast!( args.dst.write_simple_token_fast!(
@@ -540,9 +541,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
uni8_value |= ((c & 0x0F) as base.u32) << 0 uni8_value |= ((c & 0x0F) as base.u32) << 0
if uni8_ok == 0 { if uni8_ok == 0 {
// It wasn't 8 hexadecimal digits. No-op // It wasn't 8 hexadecimal digits. No-op (and
// (and fall through to "#bad // fall through to "#bad backslash-escape").
// backslash-escape").
} else if (uni8_value < 0xD800) or ( } else if (uni8_value < 0xD800) or (
(0xDFFF < uni8_value) and (uni8_value <= 0x10_FFFF)) { (0xDFFF < uni8_value) and (uni8_value <= 0x10_FFFF)) {
@@ -592,8 +592,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
if (backslash_x_ok == 0) or if (backslash_x_ok == 0) or
((backslash_x_string & 0xFFFF) <> 0x785C) { ((backslash_x_string & 0xFFFF) <> 0x785C) {
// It wasn't "\\x34", for some // It wasn't "\\x34", for some hexadecimal
// hexadecimal digits "34". // digits "34".
break break
} }
args.src.skip32_fast!(actual: 4, worst_case: 4) args.src.skip32_fast!(actual: 4, worst_case: 4)
@@ -817,9 +817,9 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
break break
} endwhile } endwhile
// As above, expect must have contained EXPECT_STRING. If it // As above, expect must have contained EXPECT_STRING. If it didn't
// didn't also contain EXPECT_NUMBER then we were parsing an // also contain EXPECT_NUMBER then we were parsing an object key
// object key and the next token should be ':'. // and the next token should be ':'.
if 0 == (expect & 0x0010) { // 0x0010 is (1 << CLASS_NUMBER). if 0 == (expect & 0x0010) { // 0x0010 is (1 << CLASS_NUMBER).
expect = 0x1008 // 0x1008 is EXPECT_COLON. expect = 0x1008 // 0x1008 is EXPECT_COLON.
continue.outer continue.outer
@@ -835,8 +835,8 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
value_minor: 0, value_minor: 0,
link: 0x0, link: 0x0,
length: 1) length: 1)
// What's valid after a comma depends on whether or not we're // What's valid after a comma depends on whether or not we're in an
// in an array or an object. // array or an object.
if 0 == (expect & 0x0100) { // 0x0100 is (1 << CLASS_CLOSE_SQUARE_BRACKET). if 0 == (expect & 0x0100) { // 0x0100 is (1 << CLASS_CLOSE_SQUARE_BRACKET).
if this.quirk_enabled_allow_extra_comma { if this.quirk_enabled_allow_extra_comma {
expect = 0x1042 // 0x1042 is EXPECT_STRING | EXPECT_CLOSE_CURLY_BRACE. expect = 0x1042 // 0x1042 is EXPECT_STRING | EXPECT_CLOSE_CURLY_BRACE.
@@ -1102,7 +1102,7 @@ pub func decoder.decode_tokens?(dst: base.token_writer, src: base.io_reader, wor
} }
return "#bad input" return "#bad input"
} endwhile.goto_parsed_a_leaf_value }} endwhile.goto_parsed_a_leaf_value
// We've just parsed a leaf (non-container) value: literal (null, // We've just parsed a leaf (non-container) value: literal (null,
// false, true), number or string. // false, true), number or string.
@@ -1124,7 +1124,7 @@ pri func decoder.decode_number!(src: base.io_reader) base.u32[..= 0x3FF] {
var n : base.u32[..= 0x3FF] var n : base.u32[..= 0x3FF]
var floating_point : base.u32[..= 0x80] var floating_point : base.u32[..= 0x80]
while.goto_done true { while.goto_done true {{
n = 0 n = 0
// Peek. // Peek.
@@ -1251,7 +1251,8 @@ pri func decoder.decode_number!(src: base.io_reader) base.u32[..= 0x3FF] {
n = this.decode_digits!(src: args.src, n: n) n = this.decode_digits!(src: args.src, n: n)
break.goto_done break.goto_done
} endwhile.goto_done }} endwhile.goto_done
return n | floating_point return n | floating_point
} }
@@ -1299,6 +1300,7 @@ pri func decoder.decode_leading?(dst: base.token_writer, src: base.io_reader) {
this.allow_leading_ars = this.quirk_enabled_allow_leading_ascii_record_separator this.allow_leading_ars = this.quirk_enabled_allow_leading_ascii_record_separator
this.allow_leading_ubom = this.quirk_enabled_allow_leading_unicode_byte_order_mark this.allow_leading_ubom = this.quirk_enabled_allow_leading_unicode_byte_order_mark
while this.allow_leading_ars or this.allow_leading_ubom { while this.allow_leading_ars or this.allow_leading_ubom {
if args.dst.available() <= 0 { if args.dst.available() <= 0 {
yield? base."$short write" yield? base."$short write"
@@ -1634,5 +1636,4 @@ pri func decoder.decode_trailing_new_line?(dst: base.token_writer, src: base.io_
whitespace_length += 1 whitespace_length += 1
} endwhile.inner } endwhile.inner
} endwhile.outer } endwhile.outer
} }