Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .chronus/changes/go-ptr-2026-8-8-10-5-9.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: internal
packages:
- "@azure-tools/typespec-go"
---

Add Ptr<T> to the code model to explicitly model pointer types.
22 changes: 11 additions & 11 deletions packages/typespec-go/src/codegen/core/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function generateExamples(
});
}
}
exampleText += `${indent.get()}clientFactory, err := ${go.getPackageName(pkg.src)}.NewClientFactory(${clientFactoryParamsExample.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.byValue)).join(", ")}, nil)\n`;
exampleText += `${indent.get()}clientFactory, err := ${go.getPackageName(pkg.src)}.NewClientFactory(${clientFactoryParamsExample.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.type.kind !== "ptr")).join(", ")}, nil)\n`;
exampleText += `${indent.get()}if err != nil {\n`;
exampleText += `${indent.push().get()}log.Fatalf("failed to create client: %v", err)\n`;
exampleText += `${indent.pop().get()}}\n`;
Expand All @@ -141,11 +141,11 @@ export function generateExamples(
}
}
if (clientPrivateParameters.length > 0) {
clientRef += `${clientPrivateParameters.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.byValue).slice(1)).join(", ")}`;
clientRef += `${clientPrivateParameters.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.type.kind !== "ptr").slice(1)).join(", ")}`;
}
clientRef += `)`;
} else {
exampleText += `${indent.get()}client, err := ${go.getPackageName(client.instance.constructors[0].pkg)}.${client.instance.constructors[0].name}(${clientParameters.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.byValue).slice(1)).join(", ")}, cred, nil)\n`;
exampleText += `${indent.get()}client, err := ${go.getPackageName(client.instance.constructors[0].pkg)}.${client.instance.constructors[0].name}(${clientParameters.map((p) => getExampleValue(pkg, p.value, "\t", imports, p.parameter.type.kind !== "ptr").slice(1)).join(", ")}, cred, nil)\n`;
exampleText += `${indent.get()}if err != nil {\n`;
exampleText += `${indent.push().get()}log.Fatalf("failed to create client: %v", err)\n`;
exampleText += `${indent.pop().get()}}\n`;
Expand Down Expand Up @@ -281,7 +281,7 @@ export function generateExamples(
? fieldName
: (example.responseEnvelope?.result.type as go.Model).name;
if (method.returns.result?.kind === "monomorphicResult") {
resultByValue = method.returns.result.byValue;
resultByValue = method.returns.result.monomorphicType.kind !== "ptr";
} else if (method.returns.result?.kind === "polymorphicResult") {
resultFieldName = method.returns.result.interface.name;
resultByValue = false;
Expand Down Expand Up @@ -365,7 +365,7 @@ function getExampleValue(
case "any":
return jsonToGo(example.value, indent);
case "array": {
const isElementByValue = example.type.elementTypeByValue;
const isElementByValue = example.type.elementType.kind !== "ptr";
// if polymorphic, need to add type name in array, so inArray will be set to false
// if other case, no need to add type name in array, so inArray will be set to true
const isElementPolymorphic = example.type.elementType.kind === "interface";
Expand All @@ -378,7 +378,7 @@ function getExampleValue(
}
case "dictionary": {
let exampleText = `${indent}${getRef(byValue)}${go.getTypeDeclaration(example.type, pkg)}{\n`;
const isValueByValue = example.type.valueTypeByValue;
const isValueByValue = example.type.valueType.kind !== "ptr";
const isValuePolymorphic = example.type.valueType.kind === "interface";
for (const key in example.value) {
exampleText += `${indent}\t"${key}": ${getExampleValue(pkg, example.value[key], indent + "\t", imports, isValueByValue && !isValuePolymorphic).slice(indent.length + 1)},\n`;
Expand All @@ -393,7 +393,7 @@ function getExampleValue(
}
for (const field in example.value) {
const goField = example.type.fields.find((f) => f.name === field)!;
const isFieldByValue = goField.byValue ?? false;
const isFieldByValue = goField.type.kind !== "ptr";
const isFieldPolymorphic = goField.type.kind === "interface";
exampleText += `${indent}\t${field}: ${getExampleValue(pkg, example.value[field], indent + "\t", imports, isFieldByValue && !isFieldPolymorphic).slice(indent.length + 1)},\n`;
}
Expand All @@ -402,10 +402,10 @@ function getExampleValue(
go.isAdditionalProperties(f),
)!;
const isAdditionalPropertiesFieldByValue =
additionalPropertiesField.type.valueTypeByValue ?? false;
additionalPropertiesField.type.valueType.kind !== "ptr";
const isAdditionalPropertiesPolymorphic =
additionalPropertiesField.type.valueType.kind === "interface";
exampleText += `${indent}\t${additionalPropertiesField.name}: ${getRef(additionalPropertiesField.byValue)}${go.getTypeDeclaration(additionalPropertiesField.type, pkg)}{\n`;
exampleText += `${indent}\t${additionalPropertiesField.name}: ${getRef(isAdditionalPropertiesFieldByValue)}${go.getTypeDeclaration(additionalPropertiesField.type, pkg)}{\n`;
for (const key in example.additionalProperties) {
exampleText += `${indent}\t"${key}": ${getExampleValue(pkg, example.additionalProperties[key], indent + "\t", imports, isAdditionalPropertiesFieldByValue && !isAdditionalPropertiesPolymorphic).slice(indent.length + 1)},\n`;
}
Expand Down Expand Up @@ -805,7 +805,7 @@ function isParamByValue(p: go.ParameterExample): boolean {
case "interface":
return p.value.kind === "null";
default:
return p.parameter.byValue;
return p.parameter.type.kind !== "ptr";
}
}

Expand Down Expand Up @@ -841,5 +841,5 @@ function getParamExampleValue(
).slice(1);
}
const fakeValue = generateFakeExample(param.type, param.name);
return getExampleValue(pkg, fakeValue, "\t", imports, param.byValue).slice(1);
return getExampleValue(pkg, fakeValue, "\t", imports, param.type.kind !== "ptr").slice(1);
}
79 changes: 28 additions & 51 deletions packages/typespec-go/src/codegen/core/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,25 +121,16 @@ export function formatParameterTypeName(
param: go.ClientOptionsType | go.ClientParameter | go.ParameterGroup,
): string {
let typeName: string;
let required: boolean;
switch (param.kind) {
case "armClientOptions":
typeName = go.getTypeDeclaration(param, scope);
required = false;
break;
case "clientOptions":
typeName = go.getTypeDeclaration(param, scope);
required = false;
break;
case "paramGroup":
typeName = go.getTypeDeclaration(param, scope);
required = param.required;
break;
default:
typeName = go.getTypeDeclaration(param.type, scope);
required = param.byValue;
}
return required ? typeName : `*${typeName}`;
return typeName;
}

// sorts parameters by their required state, ordering required before optional
Expand Down Expand Up @@ -333,12 +324,7 @@ export function getParamName(param: go.MethodParameter): string {
if (param.location === "client") {
paramName = `client.${paramName}`;
}
// client parameters with default values aren't emitted as pointer-to-type
if (
!go.isRequiredParameter(param.style) &&
!(param.location === "client" && go.isClientSideDefault(param.style)) &&
!param.byValue
) {
if (param.type.kind === "ptr") {
paramName = `*${paramName}`;
}
return paramName;
Expand Down Expand Up @@ -406,26 +392,25 @@ export function formatParamValue(
return content;
};

switch (param.type.elementType.kind) {
const unwrappedElement = go.unwrapPtr(param.type.elementType);
switch (unwrappedElement.kind) {
case "encodedBytes":
imports.add("encoding/base64");
imports.add("strings");
return emitConvertOver(
param.name,
`base64.${formatBytesEncoding(param.type.elementType.encoding)}Encoding.EncodeToString(${param.name}[i])`,
`base64.${formatBytesEncoding(unwrappedElement.encoding)}Encoding.EncodeToString(${param.name}[i])`,
);
case "string":
imports.add("strings");
return `strings.Join(${paramName}, "${separator}")`;
case "time": {
imports.add("strings");
imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
const elemVal = param.type.elementType.utc
? `${param.name}[i].UTC()`
: `${param.name}[i]`;
const elemVal = unwrappedElement.utc ? `${param.name}[i].UTC()` : `${param.name}[i]`;
return emitConvertOver(
param.name,
`datetime.${param.type.elementType.format}(${elemVal}).String()`,
`datetime.${unwrappedElement.format}(${elemVal}).String()`,
);
}
default:
Expand All @@ -436,7 +421,9 @@ export function formatParamValue(
}
}

return formatValue(paramName, param.type, imports);
// when we called getParamName it includes any dereference for a Ptr
// parameter, so we unwrap it here else we end up with a double deref
return formatValue(paramName, go.unwrapPtr(param.type), imports);
}

/**
Expand Down Expand Up @@ -559,43 +546,36 @@ export function emitTimeParsing(
return text;
}

export function formatValue(
paramName: string,
type: go.WireType,
imports: ImportManager,
deref?: boolean,
): string {
export function formatValue(paramName: string, type: go.WireType, imports: ImportManager): string {
// callers don't have enough context to know if paramName needs to be
// dereferenced so we track that here when specified. note that not all
// cases will require paramName to be dereferenced.
let star = "";
if (deref === true) {
star = "*";
}
const star = deref(type);

switch (type.kind) {
const unwrappedType = go.unwrapPtr(type);
switch (unwrappedType.kind) {
case "constant":
if (type.type === "string") {
if (unwrappedType.type === "string") {
return `string(${star}${paramName})`;
}
imports.add("fmt");
return `fmt.Sprintf("%v", ${star}${paramName})`;
case "encodedBytes":
// a base-64 encoded value in string format
imports.add("encoding/base64");
return `base64.${formatBytesEncoding(type.encoding)}Encoding.EncodeToString(${paramName})`;
return `base64.${formatBytesEncoding(unwrappedType.encoding)}Encoding.EncodeToString(${paramName})`;
case "etag":
return `string(${star}${paramName})`;
case "literal":
// cannot use formatLiteralValue() since all values are treated as strings
switch (type.type.kind) {
switch (unwrappedType.type.kind) {
case "constantDef":
return type.type.name;
return unwrappedType.type.name;
default:
return `"${type.literal}"`;
return `"${unwrappedType.literal}"`;
}
case "scalar":
switch (type.type) {
switch (unwrappedType.type) {
case "bool":
imports.add("strconv");
return `strconv.FormatBool(${star}${paramName})`;
Expand All @@ -612,12 +592,12 @@ export function formatValue(
imports.add("strconv");
return `strconv.FormatInt(${star}${paramName}, 10)`;
default:
throw new CodegenError("InternalError", `unhandled scalar type ${type.type}`);
throw new CodegenError("InternalError", `unhandled scalar type ${unwrappedType.type}`);
}
case "time": {
imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
const timeVal = type.utc ? `(${star}${paramName}).UTC()` : `${star}${paramName}`;
return `datetime.${type.format}(${timeVal}).String()`;
const timeVal = unwrappedType.utc ? `(${star}${paramName}).UTC()` : `${star}${paramName}`;
return `datetime.${unwrappedType.format}(${timeVal}).String()`;
}
default:
return `${star}${paramName}`;
Expand Down Expand Up @@ -1013,21 +993,18 @@ export function recursiveUnwrapMapSlice(item: go.WireType): go.WireType {
switch (item.kind) {
case "map":
return recursiveUnwrapMapSlice(item.valueType);
case "ptr":
return recursiveUnwrapMapSlice(item.ptrType);
case "slice":
return recursiveUnwrapMapSlice(item.elementType);
default:
return item;
}
}

/**
* returns a * character when byValue is false
*
* @param byValue indicates if the type is passed by value
* @returns a * or the empty string
*/
export function star(byValue: boolean): string {
return byValue ? "" : "*";
/** returns a * character when needing to dereference */
export function deref(type: go.WireType): "*" | "" {
return type.kind === "ptr" ? "*" : "";
}

/**
Expand Down
3 changes: 3 additions & 0 deletions packages/typespec-go/src/codegen/core/imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ export class ImportManager {
case "map":
this.addForType(type.valueType);
break;
case "ptr":
this.addForType(type.ptrType);
break;
case "slice":
this.addForType(type.elementType);
break;
Expand Down
Loading
Loading