repos / gbc

GBC - Go B Compiler
git clone https://github.com/xplshn/gbc.git

commit
f5d87de
parent
3a9a9ac
author
xplshn
date
2025-09-10 04:35:35 +0000 UTC
Fix short decls

Signed-off-by: xplshn <[email protected]>
5 files changed,  +84, -36
M README.md
+40, -33
 1@@ -14,58 +14,65 @@ This compiler is a project aiming to make a valid B compiler, with _optional_ sy
 2     For more details refer to <https://github.com/xplshn/gbc>
 3 
 4     Synopsis
 5-        gbc [options] <input.b> ...
 6+        gbc <options> <input.b> ...
 7 
 8     Description
 9-        A compiler for the B programming language and its extensions, written in Go.
10+        A compiler for the B programming language with modern extensions. Like stepping into a time machine, but with better error messages.
11 
12     Options
13         -C <arg>, --compiler-arg <arg>                 Pass a compiler-specific argument (e.g., -C linker_args='-s').
14+        -d, --dump-ir                                  Dump the intermediate representation and exit.
15         -h, --help                                     Display this information
16         -I <path>, --include <path>                    Add a directory to the include path.
17         -L <arg>, --linker-arg <arg>                   Pass an argument to the linker.
18-        -o <file>, --output <file>                     Place the output into <file>.                                       |a.out|
19+        -o <file>, --output <file>                     Place the output into <file>.                                          |a.out|
20         --pedantic                                     Issue all warnings demanded by the current B std.
21-        --std<std>                                     Specify language standard (B, Bx)                                   |Bx|
22-        -t <backend/target>, --target <backend/target> Set the backend and target ABI.                                     |qbe|
23+        --std=std                                      Specify language standard (B, Bx)                                      |Bx|
24+        -t <backend/target>, --target <backend/target> Set the backend and target ABI.                                        |qbe|
25 
26     Feature Flags
27         -F<feature flag>                               Enable a specific feature flag
28         -Fno-<feature flag>                            Disable a specific feature flag
29     Available feature flags:
30-        allow-uninitialized                            Allow declarations without an initializer (`var;` or `auto var;`).  |x|
31-        asm                                            Allow `__asm__` blocks for inline assembly.                         |x|
32-        b-esc                                          Recognize B-style '*' character escapes.                            |-|
33-        b-ops                                          Recognize B-style assignment operators like '=+'.                   |-|
34-        bx-decl                                        Enable Bx-style `auto name = val` declarations.                     |x|
35-        c-comments                                     Recognize C-style '//' line comments.                               |x|
36-        c-esc                                          Recognize C-style '\' character escapes.                            |x|
37-        c-ops                                          Recognize C-style assignment operators like '+='.                   |x|
38-        continue                                       Allow the Bx keyword `continue` to be used.                         |x|
39-        extrn                                          Allow the 'extrn' keyword.                                          |x|
40-        no-directives                                  Disable `// [b]:` directives.                                       |-|
41-        short-decl                                     Enable Bx-style short declaration `:=`.                             |x|
42-        strict-decl                                    Require all declarations to be initialized.                         |-|
43-        typed                                          Enable the Bx opt-in & backwards-compatible type system.            |x|
44+        allow-uninitialized                            Allow declarations without an initializer (`var;` or `auto var;`)      |x|
45+        asm                                            Allow `__asm__` blocks for inline assembly                             |x|
46+        b-esc                                          Recognize B-style '*' character escapes                                |-|
47+        b-ops                                          Recognize B-style assignment operators like '=+'                       |-|
48+        bx-decl                                        Enable Bx-style `auto name = val` declarations                         |x|
49+        c-comments                                     Recognize C-style '//' line comments                                   |x|
50+        c-esc                                          Recognize C-style '\' character escapes                                |x|
51+        c-ops                                          Recognize C-style assignment operators like '+='                       |x|
52+        continue                                       Allow the Bx keyword `continue` to be used                             |x|
53+        extrn                                          Allow the 'extrn' keyword                                              |x|
54+        float                                          Enable support for floating-point numbers                              |x|
55+        no-directives                                  Disable `// [b]:` directives                                           |-|
56+        prom-types                                     Enable type promotions - promote untyped literals to compatible types  |-|
57+        short-decl                                     Enable Bx-style short declaration `:=`                                 |x|
58+        strict-decl                                    Require all declarations to be initialized                             |-|
59+        strict-types                                   Disallow all incompatible type operations                              |-|
60+        typed                                          Enable the Bx opt-in & backwards-compatible type system                |x|
61 
62     Warning Flags
63         -W<warning flag>                               Enable a specific warning flag
64         -Wno-<warning flag>                            Disable a specific warning flag
65     Available Warning Flags:
66-        b-esc                                          Warn on usage of B-style '*' escapes.                               |x|
67-        b-ops                                          Warn on usage of B-style assignment operators like '=+'.            |x|
68-        c-comments                                     Warn on usage of non-standard C-style '//' comments.                |-|
69-        c-esc                                          Warn on usage of C-style '\' escapes.                               |-|
70-        c-ops                                          Warn on usage of C-style assignment operators like '+='.            |-|
71-        extra                                          Enable extra miscellaneous warnings.                                |x|
72-        implicit-decl                                  Warn about implicit function or variable declarations.              |x|
73-        long-char-const                                Warn when a multi-character constant is too long for a word.        |x|
74-        overflow                                       Warn when an integer constant is out of range for its type.         |x|
75-        pedantic                                       Issue all warnings demanded by the strict standard.                 |-|
76-        truncated-char                                 Warn when a character escape value is truncated.                    |x|
77-        type                                           Warn about type mismatches in expressions and assignments.          |x|
78-        u-esc                                          Warn on unrecognized character escape sequences.                    |x|
79-        unreachable-code                               Warn about code that will never be executed.                        |x|
80+        b-esc                                          Warn on usage of B-style '*' escapes                                   |x|
81+        b-ops                                          Warn on usage of B-style assignment operators like '=+'                |x|
82+        c-comments                                     Warn on usage of non-standard C-style '//' comments                    |-|
83+        c-esc                                          Warn on usage of C-style '\' escapes                                   |-|
84+        c-ops                                          Warn on usage of C-style assignment operators like '+='                |-|
85+        debug-comp                                     Debug warning for type promotions and conversions                      |-|
86+        extra                                          Enable extra miscellaneous warnings                                    |x|
87+        float                                          Warn when floating-point numbers are used                              |-|
88+        implicit-decl                                  Warn about implicit function or variable declarations                  |x|
89+        local-address                                  Warn when the address of a local variable is returned                  |x|
90+        long-char-const                                Warn when a multi-character constant is too long for a word            |x|
91+        overflow                                       Warn when an integer constant is out of range for its type             |x|
92+        pedantic                                       Issue all warnings demanded by the strict standard                     |-|
93+        prom-types                                     Warn when type promotions occur                                        |x|
94+        truncated-char                                 Warn when a character escape value is truncated                        |x|
95+        u-esc                                          Warn on unrecognized character escape sequences                        |x|
96+        unreachable-code                               Warn about code that will never be executed                            |x|
97 ]~/Documents/TrulyMine/gbc@
98 ```
99 
M pkg/codegen/codegen.go
+5, -0
 1@@ -821,6 +821,11 @@ func (ctx *Context) codegenStmt(node *ast.Node) (terminates bool) {
 2 		return false
 3 
 4 	default:
 5+		// Expression statements are not allowed at global scope
 6+		if ctx.currentFunc == nil {
 7+			util.Error(node.Tok, "Expression statements are not allowed at global scope")
 8+			return false
 9+		}
10 		_, terminates := ctx.codegenExpr(node)
11 		return terminates
12 	}
M pkg/parser/parser.go
+33, -0
 1@@ -167,6 +167,11 @@ func (p *Parser) parseTopLevel() *ast.Node {
 2 			stmt = p.parseTypedVarOrFuncDecl(true)
 3 		} else if p.isBxDeclarationAhead() {
 4 			stmt = p.parseDeclaration(false)
 5+		} else if p.isMultiAssignmentAhead() {
 6+			stmt = p.parseExpr()
 7+			if stmt != nil {
 8+				p.expect(token.Semi, "Expected ';' after multi-assignment statement")
 9+			}
10 		} else {
11 			stmt = p.parseUntypedGlobalDefinition(identTok)
12 		}
13@@ -212,6 +217,27 @@ func (p *Parser) isBxDeclarationAhead() bool {
14 	return false
15 }
16 
17+func (p *Parser) isMultiAssignmentAhead() bool {
18+	originalPos, originalCurrent := p.pos, p.current
19+	defer func() { p.pos, p.current = originalPos, originalCurrent }()
20+
21+	if !p.check(token.Ident) {
22+		return false
23+	}
24+	p.advance()
25+
26+	hasMultipleVars := false
27+	for p.match(token.Comma) {
28+		hasMultipleVars = true
29+		if !p.check(token.Ident) {
30+			return false
31+		}
32+		p.advance()
33+	}
34+
35+	return hasMultipleVars && p.check(token.Eq)
36+}
37+
38 func (p *Parser) isBuiltinType(tok token.Token) bool {
39 	return tok.Type >= token.Void && tok.Type <= token.Any
40 }
41@@ -442,6 +468,10 @@ func (p *Parser) parseDeclaration(hasAuto bool) *ast.Node {
42 	isDefine := false
43 
44 	if p.match(token.Define) {
45+		if hasAuto {
46+			util.Error(p.previous, "Cannot use ':=' in a typed declaration; use '=' instead")
47+			return ast.NewVarDecl(declTok, "", ast.TypeUntyped, nil, nil, false, false, false)
48+		}
49 		op, isDefine = token.Define, true
50 	} else if p.match(token.Eq) {
51 		op = token.Eq
52@@ -826,6 +856,9 @@ func (p *Parser) parseTypedVarDeclBody(startTok token.Token, declType *ast.BxTyp
53 		var initList []*ast.Node
54 		if p.match(token.Eq) {
55 			initList = append(initList, p.parseAssignmentExpr())
56+		} else if p.check(token.Define) {
57+			util.Error(p.current, "Cannot use ':=' in a typed declaration; use '=' instead")
58+			return ast.NewVarDecl(currentNameToken, name, finalType, nil, sizeExpr, isArr, isBracketed, false)
59 		} else if !p.cfg.IsFeatureEnabled(config.FeatAllowUninitialized) {
60 			util.Error(nameToken, "Initialized typed declaration is required in this mode")
61 		}
M tests/arrays.bx
+1, -1
1@@ -210,7 +210,7 @@ void demo_enum_arrays() {
2 void demo_struct_pointer_arrays() {
3     printf("\nStruct pointer arrays:\n");
4 
5-    Point* point_ptr_array[2];
6+    Point *point_ptr_array[2];
7 
8     point_ptr_array[0] = malloc(sizeof(Point));
9     point_ptr_array[1] = malloc(sizeof(Point));
M tests/bxDecls.bx
+5, -2
 1@@ -5,8 +5,11 @@ puts(arg string){
 2 }
 3 
 4 global_short := 10;
 5-auto global_auto := 20;
 6-auto global_multi_1, global_multi_2 := 30, 40;
 7+
 8+auto global_auto = 20;
 9+auto global_multi_1, global_multi_2 = 30, 40;
10+
11+auto global_multi_3, global_multi_4 = 80, 100;
12 
13 main() {
14     auto local_auto;