c-next 0.1.70 → 0.1.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/lib/__tests__/parseCHeader.mocked.test.ts +69 -54
- package/src/lib/parseCHeader.ts +56 -23
- package/src/lib/parseWithSymbols.ts +195 -53
- package/src/transpiler/Transpiler.ts +180 -63
- package/src/transpiler/logic/analysis/FunctionCallAnalyzer.ts +1 -2
- package/src/transpiler/logic/analysis/InitializationAnalyzer.ts +1 -2
- package/src/transpiler/logic/analysis/PassByValueAnalyzer.ts +51 -2
- package/src/transpiler/logic/analysis/__tests__/FunctionCallAnalyzer.test.ts +18 -12
- package/src/transpiler/logic/analysis/__tests__/InitializationAnalyzer.test.ts +9 -9
- package/src/transpiler/logic/analysis/__tests__/runAnalyzers.test.ts +5 -5
- package/src/transpiler/logic/symbols/SymbolTable.ts +729 -265
- package/src/transpiler/logic/symbols/SymbolUtils.ts +2 -2
- package/src/transpiler/logic/symbols/__tests__/SymbolTable.test.ts +415 -751
- package/src/transpiler/logic/symbols/c/__tests__/CResolver.integration.test.ts +573 -0
- package/src/transpiler/logic/symbols/c/__tests__/testHelpers.ts +20 -0
- package/src/transpiler/logic/symbols/c/collectors/EnumCollector.ts +82 -0
- package/src/transpiler/logic/symbols/c/collectors/FunctionCollector.ts +106 -0
- package/src/transpiler/logic/symbols/c/collectors/StructCollector.ts +173 -0
- package/src/transpiler/logic/symbols/c/collectors/TypedefCollector.ts +35 -0
- package/src/transpiler/logic/symbols/c/collectors/VariableCollector.ts +80 -0
- package/src/transpiler/logic/symbols/c/index.ts +333 -0
- package/src/transpiler/logic/symbols/c/utils/DeclaratorUtils.ts +269 -0
- package/src/transpiler/logic/symbols/cnext/__tests__/BitmapCollector.test.ts +50 -11
- package/src/transpiler/logic/symbols/cnext/__tests__/CNextResolver.integration.test.ts +45 -34
- package/src/transpiler/logic/symbols/cnext/__tests__/EnumCollector.test.ts +30 -13
- package/src/transpiler/logic/symbols/cnext/__tests__/FunctionCollector.test.ts +279 -64
- package/src/transpiler/logic/symbols/cnext/__tests__/RegisterCollector.test.ts +60 -13
- package/src/transpiler/logic/symbols/cnext/__tests__/ScopeCollector.test.ts +40 -37
- package/src/transpiler/logic/symbols/cnext/__tests__/StructCollector.test.ts +131 -45
- package/src/transpiler/logic/symbols/cnext/__tests__/TSymbolInfoAdapter.test.ts +223 -139
- package/src/transpiler/logic/symbols/cnext/__tests__/VariableCollector.test.ts +79 -25
- package/src/transpiler/logic/symbols/cnext/__tests__/testUtils.ts +53 -0
- package/src/transpiler/logic/symbols/cnext/adapters/TSymbolInfoAdapter.ts +83 -43
- package/src/transpiler/logic/symbols/cnext/collectors/BitmapCollector.ts +14 -13
- package/src/transpiler/logic/symbols/cnext/collectors/EnumCollector.ts +11 -10
- package/src/transpiler/logic/symbols/cnext/collectors/FunctionCollector.ts +83 -34
- package/src/transpiler/logic/symbols/cnext/collectors/RegisterCollector.ts +22 -18
- package/src/transpiler/logic/symbols/cnext/collectors/ScopeCollector.ts +53 -35
- package/src/transpiler/logic/symbols/cnext/collectors/StructCollector.ts +30 -23
- package/src/transpiler/logic/symbols/cnext/collectors/VariableCollector.ts +18 -19
- package/src/transpiler/logic/symbols/cnext/index.ts +36 -14
- package/src/transpiler/logic/symbols/cnext/types/IScopeCollectorResult.ts +2 -2
- package/src/transpiler/logic/symbols/cnext/utils/SymbolNameUtils.ts +27 -0
- package/src/transpiler/logic/symbols/cpp/__tests__/CppResolver.integration.test.ts +270 -0
- package/src/transpiler/logic/symbols/cpp/__tests__/testHelpers.ts +20 -0
- package/src/transpiler/logic/symbols/cpp/collectors/ClassCollector.ts +317 -0
- package/src/transpiler/logic/symbols/cpp/collectors/EnumCollector.ts +71 -0
- package/src/transpiler/logic/symbols/cpp/collectors/FunctionCollector.ts +155 -0
- package/src/transpiler/logic/symbols/cpp/collectors/NamespaceCollector.ts +65 -0
- package/src/transpiler/logic/symbols/cpp/collectors/TypeAliasCollector.ts +46 -0
- package/src/transpiler/logic/symbols/cpp/collectors/VariableCollector.ts +54 -0
- package/src/transpiler/logic/symbols/cpp/index.ts +366 -0
- package/src/transpiler/logic/symbols/cpp/utils/DeclaratorUtils.ts +248 -0
- package/src/transpiler/logic/symbols/shared/IExtractedParameter.ts +18 -0
- package/src/transpiler/logic/symbols/shared/ParameterExtractorUtils.ts +73 -0
- package/src/transpiler/output/codegen/CodeGenerator.ts +268 -1674
- package/src/transpiler/output/codegen/__tests__/CodeGenerator.test.ts +7 -1
- package/src/transpiler/output/codegen/assignment/AssignmentClassifier.ts +2 -1
- package/src/transpiler/output/codegen/assignment/handlers/AssignmentHandlerUtils.ts +7 -1
- package/src/transpiler/output/codegen/assignment/handlers/BitmapHandlers.ts +6 -2
- package/src/transpiler/output/codegen/assignment/handlers/RegisterHandlers.ts +2 -1
- package/src/transpiler/output/codegen/generators/declarationGenerators/ScopeGenerator.ts +21 -8
- package/src/transpiler/output/codegen/generators/declarationGenerators/ScopedRegisterGenerator.ts +3 -2
- package/src/transpiler/output/codegen/generators/expressions/CallExprUtils.ts +9 -3
- package/src/transpiler/output/codegen/generators/expressions/__tests__/CallExprGenerator.test.ts +3 -4
- package/src/transpiler/output/codegen/generators/expressions/__tests__/CallExprUtils.test.ts +4 -8
- package/src/transpiler/output/codegen/helpers/ArgumentGenerator.ts +236 -0
- package/src/transpiler/output/codegen/helpers/CppConstructorHelper.ts +3 -3
- package/src/transpiler/output/codegen/helpers/FunctionContextManager.ts +435 -0
- package/src/transpiler/output/codegen/helpers/StringOperationsHelper.ts +203 -0
- package/src/transpiler/output/codegen/helpers/SymbolLookupHelper.ts +8 -12
- package/src/transpiler/output/codegen/helpers/TypeRegistrationEngine.ts +520 -0
- package/src/transpiler/output/codegen/helpers/VariableDeclHelper.ts +735 -0
- package/src/transpiler/output/codegen/helpers/VariableDeclarationFormatter.ts +1 -1
- package/src/transpiler/output/codegen/helpers/__tests__/ArgumentGenerator.test.ts +521 -0
- package/src/transpiler/output/codegen/helpers/__tests__/CppConstructorHelper.test.ts +4 -5
- package/src/transpiler/output/codegen/helpers/__tests__/FunctionContextManager.test.ts +983 -0
- package/src/transpiler/output/codegen/helpers/__tests__/StringOperationsHelper.test.ts +269 -0
- package/src/transpiler/output/codegen/helpers/__tests__/SymbolLookupHelper.test.ts +31 -32
- package/src/transpiler/output/codegen/helpers/__tests__/TypeRegistrationEngine.test.ts +186 -0
- package/src/transpiler/output/codegen/helpers/__tests__/VariableDeclHelper.test.ts +460 -0
- package/src/transpiler/output/codegen/helpers/types/IArgumentGeneratorCallbacks.ts +32 -0
- package/src/transpiler/output/codegen/resolution/EnumTypeResolver.ts +5 -1
- package/src/transpiler/output/codegen/types/IFunctionContextCallbacks.ts +12 -0
- package/src/transpiler/output/codegen/types/IVariableFormatInput.ts +1 -1
- package/src/transpiler/output/codegen/utils/QualifiedNameGenerator.ts +114 -0
- package/src/transpiler/output/codegen/utils/__tests__/QualifiedNameGenerator.test.ts +183 -0
- package/src/transpiler/output/headers/BaseHeaderGenerator.ts +4 -4
- package/src/transpiler/output/headers/ExternalTypeHeaderBuilder.ts +7 -7
- package/src/transpiler/output/headers/HeaderGenerator.ts +9 -7
- package/src/transpiler/output/headers/HeaderGeneratorUtils.ts +19 -20
- package/src/transpiler/output/headers/__tests__/BaseHeaderGenerator.test.ts +15 -18
- package/src/transpiler/output/headers/__tests__/CHeaderGenerator.test.ts +63 -64
- package/src/transpiler/output/headers/__tests__/CppHeaderGenerator.test.ts +36 -32
- package/src/transpiler/output/headers/__tests__/ExternalTypeHeaderBuilder.test.ts +26 -26
- package/src/transpiler/output/headers/__tests__/HeaderGenerator.test.ts +87 -59
- package/src/transpiler/output/headers/__tests__/HeaderGeneratorUtils.test.ts +57 -58
- package/src/transpiler/output/headers/adapters/HeaderSymbolAdapter.ts +222 -0
- package/src/transpiler/output/headers/adapters/__tests__/HeaderSymbolAdapter.test.ts +538 -0
- package/src/transpiler/output/headers/types/IGroupedSymbols.ts +8 -8
- package/src/transpiler/output/headers/types/IHeaderSymbol.ts +62 -0
- package/src/transpiler/state/CodeGenState.ts +20 -33
- package/src/transpiler/state/SymbolRegistry.ts +181 -0
- package/src/transpiler/{types → state}/TranspilerState.ts +1 -1
- package/src/transpiler/state/__tests__/CodeGenState.test.ts +67 -59
- package/src/transpiler/state/__tests__/SymbolRegistry.test.ts +249 -0
- package/src/transpiler/{types → state}/__tests__/TranspilerState.test.ts +1 -1
- package/src/transpiler/types/ICachedFileEntry.ts +1 -1
- package/src/transpiler/types/IConflict.ts +14 -0
- package/src/transpiler/types/IPipelineInput.ts +0 -3
- package/src/transpiler/types/ISerializedSymbol.ts +11 -0
- package/src/transpiler/types/TPrimitiveKind.ts +20 -0
- package/src/transpiler/types/TType.ts +103 -0
- package/src/transpiler/types/TVisibility.ts +6 -0
- package/src/transpiler/types/symbol-kinds/TSymbolKind.ts +10 -0
- package/src/transpiler/types/symbol-kinds/TSymbolKindC.ts +12 -0
- package/src/transpiler/types/symbol-kinds/TSymbolKindCNext.ts +16 -0
- package/src/transpiler/types/symbol-kinds/TSymbolKindCpp.ts +14 -0
- package/src/transpiler/types/symbols/IBaseSymbol.ts +31 -0
- package/src/transpiler/{logic/symbols/types → types/symbols}/IBitmapFieldInfo.ts +2 -2
- package/src/transpiler/types/symbols/IBitmapSymbol.ts +21 -0
- package/src/transpiler/{logic/symbols/types → types/symbols}/IEnumSymbol.ts +5 -6
- package/src/transpiler/types/symbols/IFieldInfo.ts +26 -0
- package/src/transpiler/types/symbols/IFunctionSymbol.ts +30 -0
- package/src/transpiler/types/symbols/IParameterInfo.ts +26 -0
- package/src/transpiler/{logic/symbols/types → types/symbols}/IRegisterMemberInfo.ts +4 -4
- package/src/transpiler/types/symbols/IRegisterSymbol.ts +18 -0
- package/src/transpiler/types/symbols/IScopeSymbol.ts +32 -0
- package/src/transpiler/{logic/symbols/types → types/symbols}/IStructFieldInfo.ts +2 -1
- package/src/transpiler/types/symbols/IStructSymbol.ts +15 -0
- package/src/transpiler/types/symbols/IVariableSymbol.ts +30 -0
- package/src/transpiler/types/symbols/SymbolGuards.ts +43 -0
- package/src/transpiler/types/symbols/TAnySymbol.ts +22 -0
- package/src/transpiler/types/symbols/TSymbol.ts +32 -0
- package/src/transpiler/types/symbols/__tests__/IBaseSymbol.test.ts +56 -0
- package/src/transpiler/types/symbols/__tests__/SymbolGuards.test.ts +57 -0
- package/src/transpiler/types/symbols/c/ICBaseSymbol.ts +28 -0
- package/src/transpiler/types/symbols/c/ICEnumMemberSymbol.ts +17 -0
- package/src/transpiler/types/symbols/c/ICEnumSymbol.ts +17 -0
- package/src/transpiler/types/symbols/c/ICFieldInfo.ts +16 -0
- package/src/transpiler/types/symbols/c/ICFunctionSymbol.ts +21 -0
- package/src/transpiler/types/symbols/c/ICParameterInfo.ts +19 -0
- package/src/transpiler/types/symbols/c/ICStructSymbol.ts +21 -0
- package/src/transpiler/types/symbols/c/ICTypedefSymbol.ts +14 -0
- package/src/transpiler/types/symbols/c/ICVariableSymbol.ts +26 -0
- package/src/transpiler/types/symbols/c/TCSymbol.ts +26 -0
- package/src/transpiler/types/symbols/cpp/ICppBaseSymbol.ts +31 -0
- package/src/transpiler/types/symbols/cpp/ICppClassSymbol.ts +15 -0
- package/src/transpiler/types/symbols/cpp/ICppEnumMemberSymbol.ts +14 -0
- package/src/transpiler/types/symbols/cpp/ICppEnumSymbol.ts +14 -0
- package/src/transpiler/types/symbols/cpp/ICppFieldInfo.ts +16 -0
- package/src/transpiler/types/symbols/cpp/ICppFunctionSymbol.ts +21 -0
- package/src/transpiler/types/symbols/cpp/ICppNamespaceSymbol.ts +11 -0
- package/src/transpiler/types/symbols/cpp/ICppParameterInfo.ts +19 -0
- package/src/transpiler/types/symbols/cpp/ICppStructSymbol.ts +16 -0
- package/src/transpiler/types/symbols/cpp/ICppTypeAliasSymbol.ts +14 -0
- package/src/transpiler/types/symbols/cpp/ICppVariableSymbol.ts +23 -0
- package/src/transpiler/types/symbols/cpp/TCppSymbol.ts +30 -0
- package/src/utils/CppNamespaceUtils.ts +3 -4
- package/src/utils/FunctionUtils.ts +92 -0
- package/src/utils/ParameterUtils.ts +55 -0
- package/src/utils/PrimitiveKindUtils.ts +33 -0
- package/src/utils/ScopeUtils.ts +105 -0
- package/src/utils/TTypeUtils.ts +159 -0
- package/src/utils/TypeResolver.ts +132 -0
- package/src/utils/__tests__/CppNamespaceUtils.test.ts +92 -99
- package/src/utils/__tests__/FunctionUtils.test.ts +284 -0
- package/src/utils/__tests__/ParameterUtils.test.ts +174 -0
- package/src/utils/__tests__/PrimitiveKindUtils.test.ts +59 -0
- package/src/utils/__tests__/ScopeUtils.test.ts +53 -0
- package/src/utils/__tests__/TTypeUtils.test.ts +245 -0
- package/src/utils/__tests__/TypeResolver.test.ts +332 -0
- package/src/utils/cache/CacheManager.ts +91 -50
- package/src/utils/cache/__tests__/CacheManager.test.ts +180 -114
- package/src/transpiler/logic/symbols/AutoConstUpdater.ts +0 -93
- package/src/transpiler/logic/symbols/CSymbolCollector.ts +0 -648
- package/src/transpiler/logic/symbols/CppSymbolCollector.ts +0 -874
- package/src/transpiler/logic/symbols/SymbolCollectorContext.ts +0 -68
- package/src/transpiler/logic/symbols/__tests__/AutoConstUpdater.test.ts +0 -418
- package/src/transpiler/logic/symbols/__tests__/CSymbolCollector.test.ts +0 -685
- package/src/transpiler/logic/symbols/__tests__/CppSymbolCollector.test.ts +0 -1146
- package/src/transpiler/logic/symbols/__tests__/SymbolCollectorContext.test.ts +0 -290
- package/src/transpiler/logic/symbols/__tests__/cTestHelpers.ts +0 -43
- package/src/transpiler/logic/symbols/__tests__/cppTestHelpers.ts +0 -40
- package/src/transpiler/logic/symbols/cnext/__tests__/TSymbolAdapter.test.ts +0 -595
- package/src/transpiler/logic/symbols/cnext/adapters/TSymbolAdapter.ts +0 -345
- package/src/transpiler/logic/symbols/types/IBaseSymbol.ts +0 -27
- package/src/transpiler/logic/symbols/types/IBitmapSymbol.ts +0 -23
- package/src/transpiler/logic/symbols/types/ICollectorContext.ts +0 -19
- package/src/transpiler/logic/symbols/types/IConflict.ts +0 -20
- package/src/transpiler/logic/symbols/types/IFieldInfo.ts +0 -18
- package/src/transpiler/logic/symbols/types/IFunctionSymbol.ts +0 -25
- package/src/transpiler/logic/symbols/types/IParameterInfo.ts +0 -24
- package/src/transpiler/logic/symbols/types/IRegisterSymbol.ts +0 -20
- package/src/transpiler/logic/symbols/types/IScopeSymbol.ts +0 -19
- package/src/transpiler/logic/symbols/types/IStructSymbol.ts +0 -16
- package/src/transpiler/logic/symbols/types/IVariableSymbol.ts +0 -30
- package/src/transpiler/logic/symbols/types/TSymbol.ts +0 -36
- package/src/transpiler/logic/symbols/types/__tests__/SymbolGuards.test.ts +0 -244
- package/src/transpiler/logic/symbols/types/typeGuards.ts +0 -44
- package/src/utils/types/ESymbolKind.ts +0 -19
- package/src/utils/types/ISymbol.ts +0 -64
- /package/src/transpiler/{types → constants}/BITMAP_BACKING_TYPE.ts +0 -0
- /package/src/transpiler/{types → constants}/BITMAP_SIZE.ts +0 -0
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VariableDeclHelper - Generates variable declarations
|
|
3
|
+
*
|
|
4
|
+
* Issue #792: Extracted from CodeGenerator to reduce file size.
|
|
5
|
+
*
|
|
6
|
+
* Handles:
|
|
7
|
+
* - Variable declarations with initializers
|
|
8
|
+
* - Array declarations with dimension parsing
|
|
9
|
+
* - Array syntax validation (C-Next style vs C-style)
|
|
10
|
+
* - Integer initializer validation
|
|
11
|
+
* - C++ constructor declarations
|
|
12
|
+
*
|
|
13
|
+
* Uses CodeGenState for shared state and callback interfaces for
|
|
14
|
+
* CodeGenerator dependencies.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import * as Parser from "../../../logic/parser/grammar/CNextParser.js";
|
|
18
|
+
import CodeGenState from "../../../state/CodeGenState.js";
|
|
19
|
+
import TypeResolver from "../TypeResolver.js";
|
|
20
|
+
import ArrayInitHelper from "./ArrayInitHelper.js";
|
|
21
|
+
import EnumAssignmentValidator from "./EnumAssignmentValidator.js";
|
|
22
|
+
import IntegerLiteralValidator from "./IntegerLiteralValidator.js";
|
|
23
|
+
import StringDeclHelper from "./StringDeclHelper.js";
|
|
24
|
+
import VariableModifierBuilder from "./VariableModifierBuilder.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Callbacks for integer validation in variable declarations.
|
|
28
|
+
*/
|
|
29
|
+
interface IIntegerValidationCallbacks {
|
|
30
|
+
/** Get expression type for validation */
|
|
31
|
+
getExpressionType: (ctx: Parser.ExpressionContext) => string | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Callbacks for C++ class assignment finalization.
|
|
36
|
+
*/
|
|
37
|
+
interface ICppAssignmentCallbacks {
|
|
38
|
+
/** Get type name from type context */
|
|
39
|
+
getTypeName: (ctx: Parser.TypeContext) => string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Callbacks for array type dimension generation.
|
|
44
|
+
*/
|
|
45
|
+
interface IArrayTypeDimCallbacks {
|
|
46
|
+
/** Try to evaluate expression as constant value */
|
|
47
|
+
tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined;
|
|
48
|
+
/** Generate expression code */
|
|
49
|
+
generateExpression: (ctx: Parser.ExpressionContext) => string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Callbacks for array declaration handling.
|
|
54
|
+
*/
|
|
55
|
+
interface IArrayDeclCallbacks {
|
|
56
|
+
/** Generate expression code */
|
|
57
|
+
generateExpression: (ctx: Parser.ExpressionContext) => string;
|
|
58
|
+
/** Get type name from type context */
|
|
59
|
+
getTypeName: (ctx: Parser.TypeContext) => string;
|
|
60
|
+
/** Generate array dimensions from contexts */
|
|
61
|
+
generateArrayDimensions: (dims: Parser.ArrayDimensionContext[]) => string;
|
|
62
|
+
/** Try to evaluate expression as constant value */
|
|
63
|
+
tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Callbacks for variable initializer generation.
|
|
68
|
+
*/
|
|
69
|
+
interface IVariableInitCallbacks {
|
|
70
|
+
/** Generate expression code */
|
|
71
|
+
generateExpression: (ctx: Parser.ExpressionContext) => string;
|
|
72
|
+
/** Get type name from type context */
|
|
73
|
+
getTypeName: (ctx: Parser.TypeContext) => string;
|
|
74
|
+
/** Get zero initializer for a type */
|
|
75
|
+
getZeroInitializer: (ctx: Parser.TypeContext, isArray: boolean) => string;
|
|
76
|
+
/** Get expression type for validation */
|
|
77
|
+
getExpressionType: (ctx: Parser.ExpressionContext) => string | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Result from handling array declaration.
|
|
82
|
+
*/
|
|
83
|
+
interface IArrayDeclResult {
|
|
84
|
+
/** Whether array init was fully handled (early return) */
|
|
85
|
+
handled: boolean;
|
|
86
|
+
/** Generated code if handled */
|
|
87
|
+
code: string;
|
|
88
|
+
/** Updated declaration string */
|
|
89
|
+
decl: string;
|
|
90
|
+
/** Whether this is an array type */
|
|
91
|
+
isArray: boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* String concatenation operands extracted from expression.
|
|
96
|
+
*/
|
|
97
|
+
interface IStringConcatOps {
|
|
98
|
+
left: string;
|
|
99
|
+
right: string;
|
|
100
|
+
leftCapacity: number;
|
|
101
|
+
rightCapacity: number;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Substring extraction operands extracted from expression.
|
|
106
|
+
*/
|
|
107
|
+
interface ISubstringOps {
|
|
108
|
+
source: string;
|
|
109
|
+
start: string;
|
|
110
|
+
length: string;
|
|
111
|
+
sourceCapacity: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Callbacks for the full variable declaration orchestrator.
|
|
116
|
+
*/
|
|
117
|
+
interface IVariableDeclCallbacks {
|
|
118
|
+
/** Generate expression code */
|
|
119
|
+
generateExpression: (ctx: Parser.ExpressionContext) => string;
|
|
120
|
+
/** Generate type code from type context */
|
|
121
|
+
generateType: (ctx: Parser.TypeContext) => string;
|
|
122
|
+
/** Get type name from type context */
|
|
123
|
+
getTypeName: (ctx: Parser.TypeContext) => string;
|
|
124
|
+
/** Generate array dimensions from contexts */
|
|
125
|
+
generateArrayDimensions: (dims: Parser.ArrayDimensionContext[]) => string;
|
|
126
|
+
/** Try to evaluate expression as constant value */
|
|
127
|
+
tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined;
|
|
128
|
+
/** Get zero initializer for a type */
|
|
129
|
+
getZeroInitializer: (ctx: Parser.TypeContext, isArray: boolean) => string;
|
|
130
|
+
/** Get expression type for validation */
|
|
131
|
+
getExpressionType: (ctx: Parser.ExpressionContext) => string | null;
|
|
132
|
+
/** Infer variable type with C pointer handling */
|
|
133
|
+
inferVariableType: (
|
|
134
|
+
ctx: Parser.VariableDeclarationContext,
|
|
135
|
+
name: string,
|
|
136
|
+
) => string;
|
|
137
|
+
/** Track local variable metadata */
|
|
138
|
+
trackLocalVariable: (
|
|
139
|
+
ctx: Parser.VariableDeclarationContext,
|
|
140
|
+
name: string,
|
|
141
|
+
) => void;
|
|
142
|
+
/** Get string concatenation operands */
|
|
143
|
+
getStringConcatOperands: (
|
|
144
|
+
ctx: Parser.ExpressionContext,
|
|
145
|
+
) => IStringConcatOps | null;
|
|
146
|
+
/** Get substring extraction operands */
|
|
147
|
+
getSubstringOperands: (ctx: Parser.ExpressionContext) => ISubstringOps | null;
|
|
148
|
+
/** Get string expression capacity */
|
|
149
|
+
getStringExprCapacity: (exprCode: string) => number | null;
|
|
150
|
+
/** Request include for string operations */
|
|
151
|
+
requireStringInclude: () => void;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Generates variable declarations in C.
|
|
156
|
+
*/
|
|
157
|
+
class VariableDeclHelper {
|
|
158
|
+
// ========================================================================
|
|
159
|
+
// Tier 1: Pure Utilities (no dependencies)
|
|
160
|
+
// ========================================================================
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Parse first array dimension from arrayType syntax for size validation.
|
|
164
|
+
* Returns numeric value if dimension is a literal, null otherwise.
|
|
165
|
+
*
|
|
166
|
+
* @param typeCtx - Type context containing potential arrayType
|
|
167
|
+
* @returns First dimension as number, or null if not available/numeric
|
|
168
|
+
*/
|
|
169
|
+
static parseArrayTypeDimension(typeCtx: Parser.TypeContext): number | null {
|
|
170
|
+
if (!typeCtx.arrayType()) {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const dims = typeCtx.arrayType()!.arrayTypeDimension();
|
|
174
|
+
if (dims.length === 0) {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
const sizeExpr = dims[0].expression();
|
|
178
|
+
if (!sizeExpr) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
const sizeText = sizeExpr.getText();
|
|
182
|
+
const digitRegex = /^\d+$/;
|
|
183
|
+
if (digitRegex.exec(sizeText)) {
|
|
184
|
+
return Number.parseInt(sizeText, 10);
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Parse first array dimension from arrayDimension contexts for validation.
|
|
191
|
+
* Returns numeric value if dimension is a literal, null otherwise.
|
|
192
|
+
*
|
|
193
|
+
* @param arrayDims - Array dimension contexts
|
|
194
|
+
* @returns First dimension as number, or null if not available/numeric
|
|
195
|
+
*/
|
|
196
|
+
static parseFirstArrayDimension(
|
|
197
|
+
arrayDims: Parser.ArrayDimensionContext[],
|
|
198
|
+
): number | null {
|
|
199
|
+
if (arrayDims.length === 0 || !arrayDims[0].expression()) {
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
const sizeText = arrayDims[0].expression()!.getText();
|
|
203
|
+
if (/^\d+$/.exec(sizeText)) {
|
|
204
|
+
return Number.parseInt(sizeText, 10);
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Extract base type name from type context for error messages.
|
|
211
|
+
* Handles primitive types, user types, and array types.
|
|
212
|
+
*
|
|
213
|
+
* @param typeCtx - Type context
|
|
214
|
+
* @returns Base type name as string
|
|
215
|
+
*/
|
|
216
|
+
static extractBaseTypeName(typeCtx: Parser.TypeContext): string {
|
|
217
|
+
if (typeCtx.primitiveType()) {
|
|
218
|
+
return typeCtx.primitiveType()!.getText();
|
|
219
|
+
}
|
|
220
|
+
if (typeCtx.userType()) {
|
|
221
|
+
return typeCtx.userType()!.getText();
|
|
222
|
+
}
|
|
223
|
+
if (typeCtx.arrayType()) {
|
|
224
|
+
const arrCtx = typeCtx.arrayType()!;
|
|
225
|
+
if (arrCtx.primitiveType()) {
|
|
226
|
+
return arrCtx.primitiveType()!.getText();
|
|
227
|
+
}
|
|
228
|
+
if (arrCtx.userType()) {
|
|
229
|
+
return arrCtx.userType()!.getText();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return typeCtx.getText();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ========================================================================
|
|
236
|
+
// Tier 2: Simple Operations (CodeGenState + simple callbacks)
|
|
237
|
+
// ========================================================================
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Validate array declaration syntax - reject C-style, require C-Next style.
|
|
241
|
+
* C-style: u16 arr[8] (all dimensions after identifier) - REJECTED
|
|
242
|
+
* C-Next style: u16[8] arr (first dimension in type) - REQUIRED
|
|
243
|
+
* Multi-dim C-Next: u16[4] arr[2] (first in type, rest after) - ALLOWED
|
|
244
|
+
*
|
|
245
|
+
* Exceptions (grammar limitations):
|
|
246
|
+
* - Empty dimensions for size inference: u8 arr[] <- [...]
|
|
247
|
+
* - Qualified types: SeaDash.Parse.Result arr[3] (no arrayType support)
|
|
248
|
+
* - Scoped/global types: this.Type arr[3], global.Type arr[3]
|
|
249
|
+
* - String types: string<N> arr[3]
|
|
250
|
+
*
|
|
251
|
+
* @param ctx - Variable declaration context
|
|
252
|
+
* @param typeCtx - Type context
|
|
253
|
+
* @param name - Variable name
|
|
254
|
+
* @throws Error if C-style array declaration detected
|
|
255
|
+
*/
|
|
256
|
+
static validateArrayDeclarationSyntax(
|
|
257
|
+
ctx: Parser.VariableDeclarationContext,
|
|
258
|
+
typeCtx: Parser.TypeContext,
|
|
259
|
+
name: string,
|
|
260
|
+
): void {
|
|
261
|
+
const arrayDims = ctx.arrayDimension();
|
|
262
|
+
if (arrayDims.length === 0) {
|
|
263
|
+
return; // Not an array declaration
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// If type already has arrayType, additional dimensions are allowed (multi-dim)
|
|
267
|
+
if (typeCtx.arrayType()) {
|
|
268
|
+
return; // Valid C-Next style: u16[4] arr[2] -> uint16_t arr[4][2]
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Allow empty first dimension for size inference: u8 arr[] <- [1, 2, 3]
|
|
272
|
+
// The grammar doesn't support u8[] arr syntax, so this is the only way
|
|
273
|
+
if (arrayDims.length === 1 && !arrayDims[0].expression()) {
|
|
274
|
+
return; // Size inference pattern allowed
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Allow C-style for multi-dimensional arrays: u8 matrix[4][4]
|
|
278
|
+
// The arrayType grammar only supports single dimension, so multi-dim needs C-style
|
|
279
|
+
if (arrayDims.length > 1) {
|
|
280
|
+
return; // Multi-dimensional arrays need C-style
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Allow C-style for types that don't support arrayType syntax:
|
|
284
|
+
// - Qualified types (Scope.Type, Namespace::Type)
|
|
285
|
+
// - Scoped types (this.Type)
|
|
286
|
+
// - Global types (global.Type)
|
|
287
|
+
// - String types (string<N>)
|
|
288
|
+
// - Bitmap types (code generator doesn't yet handle arrayType for bitmaps)
|
|
289
|
+
if (
|
|
290
|
+
typeCtx.qualifiedType() ||
|
|
291
|
+
typeCtx.scopedType() ||
|
|
292
|
+
typeCtx.globalType() ||
|
|
293
|
+
typeCtx.stringType()
|
|
294
|
+
) {
|
|
295
|
+
return; // Grammar limitation - these can't use arrayType
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// C-style array declaration detected - reject with helpful error
|
|
299
|
+
const baseType = VariableDeclHelper.extractBaseTypeName(typeCtx);
|
|
300
|
+
const dimensions = arrayDims
|
|
301
|
+
.map((dim) => `[${dim.expression()?.getText() ?? ""}]`)
|
|
302
|
+
.join("");
|
|
303
|
+
const line = ctx.start?.line ?? 0;
|
|
304
|
+
const col = ctx.start?.column ?? 0;
|
|
305
|
+
|
|
306
|
+
throw new Error(
|
|
307
|
+
`${line}:${col} C-style array declaration is not allowed. ` +
|
|
308
|
+
`Use '${baseType}${dimensions} ${name}' instead of '${baseType} ${name}${dimensions}'`,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Validate integer initializer using type validation helpers.
|
|
314
|
+
* Checks that literal values fit in target type and validates type conversions.
|
|
315
|
+
*
|
|
316
|
+
* Delegates to IntegerLiteralValidator for the actual validation logic.
|
|
317
|
+
*
|
|
318
|
+
* @param ctx - Variable declaration context (must have expression)
|
|
319
|
+
* @param typeName - Target type name
|
|
320
|
+
* @param callbacks - Callbacks for expression type resolution
|
|
321
|
+
* @throws Error if value doesn't fit in type or conversion is invalid
|
|
322
|
+
*/
|
|
323
|
+
static validateIntegerInitializer(
|
|
324
|
+
ctx: Parser.VariableDeclarationContext,
|
|
325
|
+
typeName: string,
|
|
326
|
+
callbacks: IIntegerValidationCallbacks,
|
|
327
|
+
): void {
|
|
328
|
+
const exprText = ctx.expression()!.getText();
|
|
329
|
+
const line = ctx.start?.line ?? 0;
|
|
330
|
+
const col = ctx.start?.column ?? 0;
|
|
331
|
+
|
|
332
|
+
const validator = new IntegerLiteralValidator({
|
|
333
|
+
isIntegerType: TypeResolver.isIntegerType,
|
|
334
|
+
validateLiteralFitsType: TypeResolver.validateLiteralFitsType,
|
|
335
|
+
getExpressionType: (_text: string) => {
|
|
336
|
+
// IntegerLiteralValidator passes text, but our callback uses the context
|
|
337
|
+
return callbacks.getExpressionType(ctx.expression()!);
|
|
338
|
+
},
|
|
339
|
+
validateTypeConversion: TypeResolver.validateTypeConversion,
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
validator.validateIntegerAssignment(typeName, exprText, line, col);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Handle pending C++ class field assignments.
|
|
347
|
+
* In function body, generates assignments after declaration.
|
|
348
|
+
* At global scope, throws error since assignments can't exist there.
|
|
349
|
+
*
|
|
350
|
+
* @param typeCtx - Type context for error messages
|
|
351
|
+
* @param name - Variable name
|
|
352
|
+
* @param decl - Current declaration string
|
|
353
|
+
* @param callbacks - Callbacks for type name generation
|
|
354
|
+
* @returns Final declaration with semicolon and any pending assignments
|
|
355
|
+
* @throws Error if C++ class with constructor at global scope
|
|
356
|
+
*/
|
|
357
|
+
static finalizeCppClassAssignments(
|
|
358
|
+
typeCtx: Parser.TypeContext,
|
|
359
|
+
name: string,
|
|
360
|
+
decl: string,
|
|
361
|
+
callbacks: ICppAssignmentCallbacks,
|
|
362
|
+
): string {
|
|
363
|
+
if (CodeGenState.pendingCppClassAssignments.length === 0) {
|
|
364
|
+
return `${decl};`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (CodeGenState.inFunctionBody) {
|
|
368
|
+
const assignments = CodeGenState.pendingCppClassAssignments
|
|
369
|
+
.map((a) => `${name}.${a}`)
|
|
370
|
+
.join("\n");
|
|
371
|
+
CodeGenState.pendingCppClassAssignments = [];
|
|
372
|
+
return `${decl};\n${assignments}`;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// At global scope, we can't emit assignment statements.
|
|
376
|
+
CodeGenState.pendingCppClassAssignments = [];
|
|
377
|
+
throw new Error(
|
|
378
|
+
`Error: C++ class '${callbacks.getTypeName(typeCtx)}' with constructor cannot use struct initializer ` +
|
|
379
|
+
`syntax at global scope. Use constructor syntax or initialize fields separately.`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ========================================================================
|
|
384
|
+
// Tier 3: Complex Operations (callbacks + ArrayInitHelper)
|
|
385
|
+
// ========================================================================
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Get array dimension string from arrayType syntax.
|
|
389
|
+
* Evaluates const expressions to their numeric values for C compatibility.
|
|
390
|
+
* Example: u16[8] -> "[8]", u16[4][4] -> "[4][4]"
|
|
391
|
+
*
|
|
392
|
+
* @param typeCtx - Type context containing arrayType
|
|
393
|
+
* @param callbacks - Callbacks for expression evaluation
|
|
394
|
+
* @returns Dimension string like "[8]" or "" if no arrayType
|
|
395
|
+
*/
|
|
396
|
+
static getArrayTypeDimension(
|
|
397
|
+
typeCtx: Parser.TypeContext,
|
|
398
|
+
callbacks: IArrayTypeDimCallbacks,
|
|
399
|
+
): string {
|
|
400
|
+
if (!typeCtx.arrayType()) {
|
|
401
|
+
return "";
|
|
402
|
+
}
|
|
403
|
+
const dims = typeCtx.arrayType()!.arrayTypeDimension();
|
|
404
|
+
let result = "";
|
|
405
|
+
for (const dim of dims) {
|
|
406
|
+
const sizeExpr = dim.expression();
|
|
407
|
+
if (!sizeExpr) {
|
|
408
|
+
result += "[]";
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
// Try to evaluate as constant first (required for C file-scope arrays)
|
|
412
|
+
// Fall back to expression text for macros, enums, etc.
|
|
413
|
+
const dimValue =
|
|
414
|
+
callbacks.tryEvaluateConstant(sizeExpr) ??
|
|
415
|
+
callbacks.generateExpression(sizeExpr);
|
|
416
|
+
result += `[${dimValue}]`;
|
|
417
|
+
}
|
|
418
|
+
return result;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Handle array declaration with dimension parsing and initialization.
|
|
423
|
+
* Handles both C-Next style arrayType syntax (u16[8] myArray) and
|
|
424
|
+
* traditional arrayDimension syntax.
|
|
425
|
+
*
|
|
426
|
+
* @param ctx - Variable declaration context
|
|
427
|
+
* @param typeCtx - Type context
|
|
428
|
+
* @param name - Variable name
|
|
429
|
+
* @param decl - Current declaration string
|
|
430
|
+
* @param callbacks - Callbacks for code generation
|
|
431
|
+
* @returns Result indicating if handled and any generated code
|
|
432
|
+
*/
|
|
433
|
+
static handleArrayDeclaration(
|
|
434
|
+
ctx: Parser.VariableDeclarationContext,
|
|
435
|
+
typeCtx: Parser.TypeContext,
|
|
436
|
+
name: string,
|
|
437
|
+
decl: string,
|
|
438
|
+
callbacks: IArrayDeclCallbacks,
|
|
439
|
+
): IArrayDeclResult {
|
|
440
|
+
const arrayDims = ctx.arrayDimension();
|
|
441
|
+
const hasArrayTypeSyntax = typeCtx.arrayType() !== null;
|
|
442
|
+
const isArray = arrayDims.length > 0 || hasArrayTypeSyntax;
|
|
443
|
+
|
|
444
|
+
if (!isArray) {
|
|
445
|
+
return { handled: false, code: "", decl, isArray: false };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Generate dimension string from arrayType syntax (u16[8] myArray)
|
|
449
|
+
const arrayTypeDimStr = VariableDeclHelper.getArrayTypeDimension(
|
|
450
|
+
typeCtx,
|
|
451
|
+
callbacks,
|
|
452
|
+
);
|
|
453
|
+
|
|
454
|
+
const hasEmptyArrayDim = arrayDims.some((dim) => !dim.expression());
|
|
455
|
+
const declaredSize =
|
|
456
|
+
VariableDeclHelper.parseArrayTypeDimension(typeCtx) ??
|
|
457
|
+
VariableDeclHelper.parseFirstArrayDimension(arrayDims);
|
|
458
|
+
|
|
459
|
+
// ADR-035: Handle array initializers with size inference
|
|
460
|
+
if (ctx.expression()) {
|
|
461
|
+
const arrayInitResult = ArrayInitHelper.processArrayInit(
|
|
462
|
+
name,
|
|
463
|
+
typeCtx,
|
|
464
|
+
ctx.expression()!,
|
|
465
|
+
arrayDims,
|
|
466
|
+
hasEmptyArrayDim,
|
|
467
|
+
declaredSize,
|
|
468
|
+
{
|
|
469
|
+
generateExpression: (exprCtx) =>
|
|
470
|
+
callbacks.generateExpression(exprCtx),
|
|
471
|
+
getTypeName: (typeCtxParam) => callbacks.getTypeName(typeCtxParam),
|
|
472
|
+
generateArrayDimensions: (dims) =>
|
|
473
|
+
callbacks.generateArrayDimensions(dims),
|
|
474
|
+
},
|
|
475
|
+
);
|
|
476
|
+
if (arrayInitResult) {
|
|
477
|
+
// Track as local array for type resolution
|
|
478
|
+
CodeGenState.localArrays.add(name);
|
|
479
|
+
// Include arrayType dimension before arrayDimension dimensions
|
|
480
|
+
const fullDimSuffix = arrayTypeDimStr + arrayInitResult.dimensionSuffix;
|
|
481
|
+
return {
|
|
482
|
+
handled: true,
|
|
483
|
+
code: `${decl}${fullDimSuffix} = ${arrayInitResult.initValue};`,
|
|
484
|
+
decl,
|
|
485
|
+
isArray: true,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// Generate dimensions: arrayType dimension first, then arrayDimension dimensions
|
|
491
|
+
const newDecl =
|
|
492
|
+
decl + arrayTypeDimStr + callbacks.generateArrayDimensions(arrayDims);
|
|
493
|
+
CodeGenState.localArrays.add(name);
|
|
494
|
+
|
|
495
|
+
return { handled: false, code: "", decl: newDecl, isArray: true };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Generate variable initializer with validation.
|
|
500
|
+
* Handles zero initialization for uninitialized variables and
|
|
501
|
+
* validates enum and integer assignments.
|
|
502
|
+
*
|
|
503
|
+
* @param ctx - Variable declaration context
|
|
504
|
+
* @param typeCtx - Type context
|
|
505
|
+
* @param decl - Current declaration string
|
|
506
|
+
* @param isArray - Whether this is an array type
|
|
507
|
+
* @param callbacks - Callbacks for code generation and validation
|
|
508
|
+
* @returns Declaration string with initializer
|
|
509
|
+
*/
|
|
510
|
+
static generateVariableInitializer(
|
|
511
|
+
ctx: Parser.VariableDeclarationContext,
|
|
512
|
+
typeCtx: Parser.TypeContext,
|
|
513
|
+
decl: string,
|
|
514
|
+
isArray: boolean,
|
|
515
|
+
callbacks: IVariableInitCallbacks,
|
|
516
|
+
): string {
|
|
517
|
+
if (!ctx.expression()) {
|
|
518
|
+
// ADR-015: Zero initialization for uninitialized variables
|
|
519
|
+
return `${decl} = ${callbacks.getZeroInitializer(typeCtx, isArray)}`;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const typeName = callbacks.getTypeName(typeCtx);
|
|
523
|
+
const savedExpectedType = CodeGenState.expectedType;
|
|
524
|
+
CodeGenState.expectedType = typeName;
|
|
525
|
+
|
|
526
|
+
// ADR-017: Validate enum type for initialization
|
|
527
|
+
EnumAssignmentValidator.validateEnumAssignment(typeName, ctx.expression()!);
|
|
528
|
+
|
|
529
|
+
// ADR-024: Validate integer literals and type conversions
|
|
530
|
+
VariableDeclHelper.validateIntegerInitializer(ctx, typeName, {
|
|
531
|
+
getExpressionType: callbacks.getExpressionType,
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
const result = `${decl} = ${callbacks.generateExpression(ctx.expression()!)}`;
|
|
535
|
+
CodeGenState.expectedType = savedExpectedType;
|
|
536
|
+
|
|
537
|
+
return result;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// ========================================================================
|
|
541
|
+
// Tier 4: Orchestrators (main entry points)
|
|
542
|
+
// ========================================================================
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Generate a complete variable declaration.
|
|
546
|
+
* This is the main entry point for variable declaration generation.
|
|
547
|
+
*
|
|
548
|
+
* Handles:
|
|
549
|
+
* - C++ constructor syntax
|
|
550
|
+
* - String declarations
|
|
551
|
+
* - Array declarations
|
|
552
|
+
* - Regular variable declarations with initializers
|
|
553
|
+
* - C++ class field assignments
|
|
554
|
+
*
|
|
555
|
+
* @param ctx - Variable declaration context
|
|
556
|
+
* @param callbacks - Callbacks for code generation
|
|
557
|
+
* @returns Complete variable declaration code
|
|
558
|
+
*/
|
|
559
|
+
static generateVariableDecl(
|
|
560
|
+
ctx: Parser.VariableDeclarationContext,
|
|
561
|
+
callbacks: IVariableDeclCallbacks,
|
|
562
|
+
): string {
|
|
563
|
+
// Issue #375: Check for C++ constructor syntax - early return
|
|
564
|
+
const constructorArgList = ctx.constructorArgumentList();
|
|
565
|
+
if (constructorArgList) {
|
|
566
|
+
return VariableDeclHelper.generateConstructorDecl(
|
|
567
|
+
ctx,
|
|
568
|
+
constructorArgList,
|
|
569
|
+
{ generateType: callbacks.generateType },
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Issue #696: Use helper for modifier extraction and validation
|
|
574
|
+
const modifiers = VariableModifierBuilder.build(
|
|
575
|
+
ctx,
|
|
576
|
+
CodeGenState.inFunctionBody,
|
|
577
|
+
);
|
|
578
|
+
|
|
579
|
+
const name = ctx.IDENTIFIER().getText();
|
|
580
|
+
const typeCtx = ctx.type();
|
|
581
|
+
|
|
582
|
+
// Reject C-style array declarations (u16 arr[8]) - require C-Next style (u16[8] arr)
|
|
583
|
+
VariableDeclHelper.validateArrayDeclarationSyntax(ctx, typeCtx, name);
|
|
584
|
+
|
|
585
|
+
const type = callbacks.inferVariableType(ctx, name);
|
|
586
|
+
|
|
587
|
+
// Track local variable metadata
|
|
588
|
+
callbacks.trackLocalVariable(ctx, name);
|
|
589
|
+
|
|
590
|
+
// ADR-045: Handle bounded string type specially - early return
|
|
591
|
+
const stringResult = StringDeclHelper.generateStringDecl(
|
|
592
|
+
typeCtx,
|
|
593
|
+
name,
|
|
594
|
+
ctx.expression() ?? null,
|
|
595
|
+
ctx.arrayDimension(),
|
|
596
|
+
modifiers,
|
|
597
|
+
ctx.constModifier() !== null,
|
|
598
|
+
{
|
|
599
|
+
generateExpression: (exprCtx) => callbacks.generateExpression(exprCtx),
|
|
600
|
+
generateArrayDimensions: (dims) =>
|
|
601
|
+
callbacks.generateArrayDimensions(dims),
|
|
602
|
+
getStringConcatOperands: (concatCtx) =>
|
|
603
|
+
callbacks.getStringConcatOperands(concatCtx),
|
|
604
|
+
getSubstringOperands: (substrCtx) =>
|
|
605
|
+
callbacks.getSubstringOperands(substrCtx),
|
|
606
|
+
getStringExprCapacity: (exprCode) =>
|
|
607
|
+
callbacks.getStringExprCapacity(exprCode),
|
|
608
|
+
requireStringInclude: () => callbacks.requireStringInclude(),
|
|
609
|
+
},
|
|
610
|
+
);
|
|
611
|
+
if (stringResult.handled) {
|
|
612
|
+
return stringResult.code;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Build base declaration
|
|
616
|
+
const modifierPrefix = VariableModifierBuilder.toPrefix(modifiers);
|
|
617
|
+
let decl = `${modifierPrefix}${type} ${name}`;
|
|
618
|
+
|
|
619
|
+
// Handle array declarations - early return if array init handled
|
|
620
|
+
const arrayResult = VariableDeclHelper.handleArrayDeclaration(
|
|
621
|
+
ctx,
|
|
622
|
+
typeCtx,
|
|
623
|
+
name,
|
|
624
|
+
decl,
|
|
625
|
+
{
|
|
626
|
+
generateExpression: callbacks.generateExpression,
|
|
627
|
+
getTypeName: callbacks.getTypeName,
|
|
628
|
+
generateArrayDimensions: callbacks.generateArrayDimensions,
|
|
629
|
+
tryEvaluateConstant: callbacks.tryEvaluateConstant,
|
|
630
|
+
},
|
|
631
|
+
);
|
|
632
|
+
if (arrayResult.handled) {
|
|
633
|
+
return arrayResult.code;
|
|
634
|
+
}
|
|
635
|
+
decl = arrayResult.decl;
|
|
636
|
+
|
|
637
|
+
// Handle initialization
|
|
638
|
+
decl = VariableDeclHelper.generateVariableInitializer(
|
|
639
|
+
ctx,
|
|
640
|
+
typeCtx,
|
|
641
|
+
decl,
|
|
642
|
+
arrayResult.isArray,
|
|
643
|
+
{
|
|
644
|
+
generateExpression: callbacks.generateExpression,
|
|
645
|
+
getTypeName: callbacks.getTypeName,
|
|
646
|
+
getZeroInitializer: callbacks.getZeroInitializer,
|
|
647
|
+
getExpressionType: callbacks.getExpressionType,
|
|
648
|
+
},
|
|
649
|
+
);
|
|
650
|
+
|
|
651
|
+
// Handle pending C++ class field assignments
|
|
652
|
+
return VariableDeclHelper.finalizeCppClassAssignments(typeCtx, name, decl, {
|
|
653
|
+
getTypeName: callbacks.getTypeName,
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Generate C++ constructor-style declaration.
|
|
659
|
+
* Validates that all arguments are const variables.
|
|
660
|
+
*
|
|
661
|
+
* Example: `Adafruit_MAX31856 thermocouple(pinConst);`
|
|
662
|
+
*
|
|
663
|
+
* @param ctx - Variable declaration context
|
|
664
|
+
* @param argListCtx - Constructor argument list context
|
|
665
|
+
* @param callbacks - Callbacks for type generation
|
|
666
|
+
* @returns Constructor declaration code
|
|
667
|
+
* @throws Error if argument not declared or not const
|
|
668
|
+
*/
|
|
669
|
+
static generateConstructorDecl(
|
|
670
|
+
ctx: Parser.VariableDeclarationContext,
|
|
671
|
+
argListCtx: Parser.ConstructorArgumentListContext,
|
|
672
|
+
callbacks: Pick<IVariableDeclCallbacks, "generateType">,
|
|
673
|
+
): string {
|
|
674
|
+
const type = callbacks.generateType(ctx.type());
|
|
675
|
+
const name = ctx.IDENTIFIER().getText();
|
|
676
|
+
const line = ctx.start?.line ?? 0;
|
|
677
|
+
|
|
678
|
+
// Collect and validate all arguments
|
|
679
|
+
const argIdentifiers = argListCtx.IDENTIFIER();
|
|
680
|
+
const resolvedArgs: string[] = [];
|
|
681
|
+
|
|
682
|
+
for (const argNode of argIdentifiers) {
|
|
683
|
+
const argName = argNode.getText();
|
|
684
|
+
|
|
685
|
+
// Check if it exists in type registry
|
|
686
|
+
const typeInfo = CodeGenState.getVariableTypeInfo(argName);
|
|
687
|
+
|
|
688
|
+
// Also check scoped variables if inside a scope
|
|
689
|
+
let scopedArgName = argName;
|
|
690
|
+
let scopedTypeInfo = typeInfo;
|
|
691
|
+
if (!typeInfo && CodeGenState.currentScope) {
|
|
692
|
+
scopedArgName = `${CodeGenState.currentScope}_${argName}`;
|
|
693
|
+
scopedTypeInfo = CodeGenState.getVariableTypeInfo(scopedArgName);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
if (!typeInfo && !scopedTypeInfo) {
|
|
697
|
+
throw new Error(
|
|
698
|
+
`Error at line ${line}: Constructor argument '${argName}' is not declared`,
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
const finalTypeInfo = typeInfo ?? scopedTypeInfo!;
|
|
703
|
+
const finalArgName = typeInfo ? argName : scopedArgName;
|
|
704
|
+
|
|
705
|
+
// Check if it's const
|
|
706
|
+
if (!finalTypeInfo.isConst) {
|
|
707
|
+
throw new Error(
|
|
708
|
+
`Error at line ${line}: Constructor argument '${argName}' must be const. ` +
|
|
709
|
+
`C++ constructors in C-Next only accept const variables.`,
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
resolvedArgs.push(finalArgName);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// Track the variable in type registry (as an external C++ type)
|
|
717
|
+
CodeGenState.setVariableTypeInfo(name, {
|
|
718
|
+
baseType: type,
|
|
719
|
+
bitWidth: 0, // Unknown for C++ types
|
|
720
|
+
isArray: false,
|
|
721
|
+
arrayDimensions: [],
|
|
722
|
+
isConst: false,
|
|
723
|
+
isExternalCppType: true,
|
|
724
|
+
});
|
|
725
|
+
|
|
726
|
+
// Track as local variable if inside function body
|
|
727
|
+
if (CodeGenState.inFunctionBody) {
|
|
728
|
+
CodeGenState.localVariables.add(name);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
return `${type} ${name}(${resolvedArgs.join(", ")});`;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
export default VariableDeclHelper;
|