Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | 11x 11x 3x 3x 4x 4x 4x 1x 3x 2x 74x 74x 74x 3x 3x 3x 3x 3x 3x 3x 71x 71x 71x 71x 3x 68x 68x 68x 74x 74x 74x 5x 68x 2x 2x 2x 2x 2x 68x 35x 33x 68x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 1x 1x 1x 106x 2x 2x 2x 6x 6x 6x 6x 3x 3x 3x 6x 6x 6x 2x 239x 239x 239x 74x 74x 74x 165x 109x 109x 56x 6x 6x 50x 6x 6x 44x 2x 2x 2x 42x 5x 5x 37x 13x 165x 165x 165x 165x 165x 239x 161x 161x 161x 6x 6x 6x 6x 4x 4x 9x 9x 9x 9x 2x 6x 6x 6x 6x 5x 6x 1x 2x 1x 1x 5x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 6x 6x 6x 6x 6x 6x 6x 1x 5x 6x 6x 5x 5x 5x 6x 6x 6x 6x 6x 1x 6x 1x 1x 1x 1x 1x 6x 5x 5x | /**
* ScopeGenerator - ADR-016 Scope Declaration Generation
*
* Generates C code from C-Next scope declarations with visibility control.
* Scopes provide namespace prefixing and static/extern visibility.
*
* Example:
* scope Driver {
* private u32 counter;
* public fn init() -> void { counter <- 0; }
* }
* ->
* // Scope: Driver
* static uint32_t Driver_counter = 0;
* void Driver_init(void) { Driver_counter = 0; }
*/
import * as Parser from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IGeneratorOutput from "../IGeneratorOutput";
import IOrchestrator from "../IOrchestrator";
import TGeneratorFn from "../TGeneratorFn";
import generateScopedRegister from "./ScopedRegisterGenerator";
import BitmapCommentUtils from "./BitmapCommentUtils";
/**
* Extract scoped name from a declaration node.
* Returns both the local name and the fully qualified scoped name.
*/
function getScopedName(
node: { IDENTIFIER(): { getText(): string } },
scopeName: string,
): { name: string; fullName: string } {
const name = node.IDENTIFIER().getText();
return { name, fullName: `${scopeName}_${name}` };
}
/**
* Validate and resolve constructor arguments, ensuring each is const.
* Returns array of scope-prefixed argument names.
*/
function resolveConstructorArgs(
argIdentifiers: { getText(): string }[],
scopeName: string,
line: number,
orchestrator: IOrchestrator,
): string[] {
const resolvedArgs: string[] = [];
for (const argNode of argIdentifiers) {
const argName = argNode.getText();
// Arguments must be resolved with scope prefix
const scopedArgName = `${scopeName}_${argName}`;
// Check if it's const using orchestrator
if (!orchestrator.isConstValue(scopedArgName)) {
throw new Error(
`Error at line ${line}: Constructor argument '${argName}' must be const. ` +
`C++ constructors in C-Next only accept const variables.`,
);
}
resolvedArgs.push(scopedArgName);
}
return resolvedArgs;
}
/**
* Generate a scope variable declaration.
* Returns the declaration string, or null if the variable should be skipped.
*/
function generateScopeVariable(
varDecl: Parser.VariableDeclarationContext,
scopeName: string,
isPrivate: boolean,
orchestrator: IOrchestrator,
): string | null {
const varName = varDecl.IDENTIFIER().getText();
// Issue #375: Check for constructor syntax
const constructorArgList = varDecl.constructorArgumentList();
if (constructorArgList) {
// ADR-016: All scope variables are emitted at file scope
const type = orchestrator.generateType(varDecl.type());
const fullName = `${scopeName}_${varName}`;
const prefix = isPrivate ? "static " : "";
// Validate and resolve constructor arguments
const argIdentifiers = constructorArgList.IDENTIFIER();
const line = varDecl.start?.line ?? 0;
const resolvedArgs = resolveConstructorArgs(
argIdentifiers,
scopeName,
line,
orchestrator,
);
return `${prefix}${type} ${fullName}(${resolvedArgs.join(", ")});`;
}
// Issue #282: Check if this is a const variable - const values should be inlined
const isConst = varDecl.constModifier() !== null;
// Issue #500: Check if array before skipping - arrays must be emitted
const arrayDims = varDecl.arrayDimension();
const isArray = arrayDims.length > 0;
// Issue #282: Private const variables should be inlined, not emitted at file scope
// Issue #500: EXCEPT arrays - arrays must be emitted as static const
// The inlining happens in CodeGenerator when resolving this.CONST_NAME
if (isPrivate && isConst && !isArray) {
return null;
}
// ADR-016: All scope variables are emitted at file scope (static-like persistence)
const type = orchestrator.generateType(varDecl.type());
const fullName = `${scopeName}_${varName}`;
// Issue #282: Add 'const' modifier for const variables
const constPrefix = isConst ? "const " : "";
const prefix = isPrivate ? "static " : "";
// ADR-036: arrayDimension() now returns an array (arrayDims defined above)
let decl = `${prefix}${constPrefix}${type} ${fullName}`;
if (isArray) {
decl += orchestrator.generateArrayDimensions(arrayDims);
}
// ADR-045: Add string capacity dimension for string arrays
if (varDecl.type().stringType()) {
const stringCtx = varDecl.type().stringType()!;
const intLiteral = stringCtx.INTEGER_LITERAL();
Eif (intLiteral) {
const capacity = Number.parseInt(intLiteral.getText(), 10);
decl += `[${capacity + 1}]`;
}
}
if (varDecl.expression()) {
decl += ` = ${orchestrator.generateExpression(varDecl.expression()!)}`;
} else {
// ADR-015: Zero initialization for uninitialized scope variables
decl += ` = ${orchestrator.getZeroInitializer(varDecl.type(), isArray)}`;
}
return decl + ";";
}
/**
* Generate a scope function declaration.
* Returns array of output lines (function definition + optional callback typedef).
*/
function generateScopeFunction(
funcDecl: Parser.FunctionDeclarationContext,
scopeName: string,
isPrivate: boolean,
orchestrator: IOrchestrator,
): string[] {
const returnType = orchestrator.generateType(funcDecl.type());
const funcName = funcDecl.IDENTIFIER().getText();
const fullName = `${scopeName}_${funcName}`;
const prefix = isPrivate ? "static " : "";
// Issue #269: Set current function name for pass-by-value lookup
orchestrator.setCurrentFunctionName(fullName);
// Track parameters for ADR-006 pointer semantics
orchestrator.setParameters(funcDecl.parameterList() ?? null);
// ADR-016: Enter function body context (also clears modifiedParameters for Issue #281)
orchestrator.enterFunctionBody();
// Issue #281: Generate body FIRST to track parameter modifications,
// then generate parameter list using that tracking info
const body = orchestrator.generateBlock(funcDecl.block());
// Issue #281: Update symbol's parameter info with auto-const before generating params
orchestrator.updateFunctionParamsAutoConst(fullName);
// Now generate parameter list (can use modifiedParameters for auto-const)
const params = funcDecl.parameterList()
? orchestrator.generateParameterList(funcDecl.parameterList()!)
: "void";
// ADR-016: Exit function body context
orchestrator.exitFunctionBody();
orchestrator.setCurrentFunctionName(null); // Issue #269: Clear function name
orchestrator.clearParameters();
const lines: string[] = [];
lines.push("", `${prefix}${returnType} ${fullName}(${params}) ${body}`);
// ADR-029: Generate callback typedef only if used as a type
if (orchestrator.isCallbackTypeUsedAsFieldType(fullName)) {
const typedef = orchestrator.generateCallbackTypedef(fullName);
Eif (typedef) {
lines.push(typedef);
}
}
return lines;
}
/**
* Generate enum members from AST when symbol info is not available.
* Returns array of formatted enum member lines.
*/
function generateEnumMembersFromAST(
members: Parser.EnumMemberContext[],
fullName: string,
orchestrator: IOrchestrator,
): string[] {
const lines: string[] = [];
let currentValue = 0;
for (let i = 0; i < members.length; i++) {
const member = members[i];
const memberName = member.IDENTIFIER().getText();
const fullMemberName = `${fullName}_${memberName}`;
if (member.expression()) {
const constValue = orchestrator.tryEvaluateConstant(member.expression()!);
Eif (constValue !== undefined) {
currentValue = constValue;
}
}
const comma = i < members.length - 1 ? "," : "";
lines.push(` ${fullMemberName} = ${currentValue}${comma}`);
currentValue++;
}
return lines;
}
/**
* Process a single scope member and return lines to add.
*/
function processScopeMember(
member: Parser.ScopeMemberContext,
scopeName: string,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): string[] {
const visibility = member.visibilityModifier()?.getText() || "private";
const isPrivate = visibility === "private";
// Handle variable declarations
if (member.variableDeclaration()) {
const varDecl = member.variableDeclaration()!;
const result = generateScopeVariable(
varDecl,
scopeName,
isPrivate,
orchestrator,
);
return result === null ? [] : [result];
}
// Handle function declarations
if (member.functionDeclaration()) {
const funcDecl = member.functionDeclaration()!;
return generateScopeFunction(funcDecl, scopeName, isPrivate, orchestrator);
}
// ADR-017: Handle enum declarations inside scopes
// Issue #369: Skip enum definition if self-include was added (it will be in the header)
if (member.enumDeclaration() && !state.selfIncludeAdded) {
const enumDecl = member.enumDeclaration()!;
return [
"",
generateScopedEnumInline(enumDecl, scopeName, input, orchestrator),
];
}
// ADR-034: Handle bitmap declarations inside scopes
// Issue #369: Skip bitmap definition if self-include was added (it will be in the header)
if (member.bitmapDeclaration() && !state.selfIncludeAdded) {
const bitmapDecl = member.bitmapDeclaration()!;
return ["", generateScopedBitmapInline(bitmapDecl, scopeName, input)];
}
// Handle register declarations inside scopes
if (member.registerDeclaration()) {
const regDecl = member.registerDeclaration()!;
const result = generateScopedRegister(
regDecl,
scopeName,
input,
state,
orchestrator,
);
return ["", result.code];
}
// Handle struct declarations inside scopes
// Issue #369: Skip struct definition if self-include was added (it will be in the header)
if (member.structDeclaration() && !state.selfIncludeAdded) {
const structDecl = member.structDeclaration()!;
return [
"",
generateScopedStructInline(structDecl, scopeName, input, orchestrator),
];
}
return [];
}
/**
* Generate C code from a C-Next scope declaration.
*
* ADR-016: Scopes provide:
* - Namespace prefixing (Scope_member)
* - Visibility control (private -> static, public -> extern)
* - Organization without runtime overhead
*/
const generateScope: TGeneratorFn<Parser.ScopeDeclarationContext> = (
node: Parser.ScopeDeclarationContext,
input: IGeneratorInput,
state: IGeneratorState,
orchestrator: IOrchestrator,
): IGeneratorOutput => {
const name = node.IDENTIFIER().getText();
// Set current scope for nested generation (imperative, not effect-based)
orchestrator.setCurrentScope(name);
const lines: string[] = [];
lines.push(`/* Scope: ${name} */`);
for (const member of node.scopeMember()) {
lines.push(...processScopeMember(member, name, input, state, orchestrator));
}
lines.push("");
// Clear scope at end
orchestrator.setCurrentScope(null);
return {
code: lines.join("\n"),
effects: [],
};
};
/**
* Generate enum inside a scope with proper prefixing.
* Uses symbol info for enum members if available.
*/
function generateScopedEnumInline(
node: Parser.EnumDeclarationContext,
scopeName: string,
input: IGeneratorInput,
orchestrator: IOrchestrator,
): string {
const { fullName } = getScopedName(node, scopeName);
const lines: string[] = [`typedef enum {`];
// Try to get members from symbol info first
const symbolMembers = input.symbols?.enumMembers.get(fullName);
if (symbolMembers) {
const memberEntries = Array.from(symbolMembers.entries());
for (let i = 0; i < memberEntries.length; i++) {
const [memberName, value] = memberEntries[i];
const fullMemberName = `${fullName}_${memberName}`;
const comma = i < memberEntries.length - 1 ? "," : "";
lines.push(` ${fullMemberName} = ${value}${comma}`);
}
} else {
// Fall back to AST parsing
lines.push(
...generateEnumMembersFromAST(node.enumMember(), fullName, orchestrator),
);
}
lines.push(`} ${fullName};`, "");
return lines.join("\n");
}
/**
* Resolve bitmap backing type from symbols or keyword
*/
function _getBitmapBackingType(
fullName: string,
node: Parser.BitmapDeclarationContext,
input: IGeneratorInput,
): string {
const symbolType = input.symbols?.bitmapBackingType.get(fullName);
if (symbolType) return symbolType;
const bitmapKeyword = node.getChild(0)?.getText() || "bitmap32";
switch (bitmapKeyword) {
case "bitmap8":
return "uint8_t";
case "bitmap16":
return "uint16_t";
case "bitmap64":
return "uint64_t";
default:
return "uint32_t";
}
}
/**
* Generate bitmap field comments from AST (fallback when symbols unavailable)
*/
function _generateBitmapFieldCommentsFromAST(
fields: Parser.BitmapMemberContext[],
): string[] {
if (fields.length === 0) return [];
const lines: string[] = ["/* Fields:"];
let bitOffset = 0;
for (const field of fields) {
const fieldName = field.IDENTIFIER().getText();
const width = field.INTEGER_LITERAL()
? Number.parseInt(field.INTEGER_LITERAL()!.getText(), 10)
: 1;
const endBit = bitOffset + width - 1;
const bitRange =
width === 1 ? `bit ${bitOffset}` : `bits ${bitOffset}-${endBit}`;
lines.push(
` * ${fieldName}: ${bitRange} (${width} bit${width > 1 ? "s" : ""})`,
);
bitOffset += width;
}
lines.push(" */");
return lines;
}
/**
* Generate bitmap inside a scope with proper prefixing.
* Uses symbol info for backing type if available.
*/
function generateScopedBitmapInline(
node: Parser.BitmapDeclarationContext,
scopeName: string,
input: IGeneratorInput,
): string {
const name = node.IDENTIFIER().getText();
const fullName = `${scopeName}_${name}`;
const backingType = _getBitmapBackingType(fullName, node, input);
const lines: string[] = [];
lines.push(`/* Bitmap: ${fullName} */`);
// Issue #707: Use shared utility for bitmap field comments
const symbolFields = input.symbols?.bitmapFields.get(fullName);
if (symbolFields) {
lines.push(...BitmapCommentUtils.generateBitmapFieldComments(symbolFields));
} else {
lines.push(..._generateBitmapFieldCommentsFromAST(node.bitmapMember()));
}
lines.push(`typedef ${backingType} ${fullName};`, "");
return lines.join("\n");
}
/**
* Generate struct inside a scope with proper prefixing.
* Struct fields maintain their original types.
*/
function generateScopedStructInline(
node: Parser.StructDeclarationContext,
scopeName: string,
_input: IGeneratorInput,
orchestrator: IOrchestrator,
): string {
const { fullName } = getScopedName(node, scopeName);
const lines: string[] = [`typedef struct ${fullName} {`];
// Process struct members
for (const member of node.structMember()) {
const fieldName = member.IDENTIFIER().getText();
const fieldType = orchestrator.generateType(member.type());
// Handle array dimensions if present
const arrayDims = member.arrayDimension();
let dimStr = "";
if (arrayDims.length > 0) {
dimStr = orchestrator.generateArrayDimensions(arrayDims);
}
// Handle string capacity for string fields
if (member.type().stringType()) {
const stringCtx = member.type().stringType()!;
const intLiteral = stringCtx.INTEGER_LITERAL();
Eif (intLiteral) {
const capacity = Number.parseInt(intLiteral.getText(), 10);
dimStr += `[${capacity + 1}]`;
}
}
lines.push(` ${fieldType} ${fieldName}${dimStr};`);
}
lines.push(`} ${fullName};`, "");
return lines.join("\n");
}
export default generateScope;
|