Skip to content
Merged
48 changes: 10 additions & 38 deletions typespec-extension/src/code-model-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ import {
getOverloadedOperation,
getProjectedName,
getSummary,
getTypeName,
getVisibility,
ignoreDiagnostics,
isArrayModelType,
Expand Down Expand Up @@ -156,8 +155,6 @@ import {
ProcessingCache,
getAccess,
getDurationFormatFromSdkType,
getNameForTemplate,
getNamePrefixForProperty,
getUnionDescription,
getUsage,
hasScalarAsBase,
Expand Down Expand Up @@ -1350,7 +1347,8 @@ export class CodeModelBuilder {
}

const isAnonymousModel = sdkType.kind === "model" && sdkType.isGeneratedName === true;
const parameter = new Parameter(this.getName(body), this.getDoc(body), schema, {
const parameterName = body.kind === "Model" ? (sdkType.kind === "model" ? sdkType.name : "") : this.getName(body);
const parameter = new Parameter(parameterName, this.getDoc(body), schema, {
summary: this.getSummary(body),
implementation: ImplementationLocation.Method,
required: body.kind === "Model" || !body.optional,
Expand Down Expand Up @@ -1598,10 +1596,10 @@ export class CodeModelBuilder {
}
if (match) {
schema = candidateResponseSchema;
const sdkType = getClientType(this.sdkContext, bodyType);
const modelName = sdkType.kind === "model" ? sdkType.name : undefined;
this.trace(
`Replace TypeSpec model '${this.getName(bodyType)}' with '${
candidateResponseSchema.language.default.name
}'`,
`Replace TypeSpec model '${modelName}' with '${candidateResponseSchema.language.default.name}'`,
);
}
}
Expand Down Expand Up @@ -1890,7 +1888,7 @@ export class CodeModelBuilder {

const schemaType = type.isFixed ? SealedChoiceSchema : ChoiceSchema;

const schema = new schemaType(type.name ? type.name : name, type.details ?? "", {
const schema = new schemaType(type.name ?? name, type.details ?? "", {
summary: type.description,
choiceType: valueType as any,
choices: choices,
Expand All @@ -1911,7 +1909,7 @@ export class CodeModelBuilder {
const valueType = this.processSchemaFromSdkType(type.valueType, type.valueType.kind);

return this.codeModel.schemas.add(
new ConstantSchema(name, type.details ?? "", {
new ConstantSchema(type.name ?? name, type.details ?? "", {
summary: type.description,
valueType: valueType,
value: new ConstantValue(type.value),
Expand All @@ -1923,7 +1921,7 @@ export class CodeModelBuilder {
const valueType = this.processSchemaFromSdkType(type.enumType, type.enumType.name);

return this.codeModel.schemas.add(
new ConstantSchema(name, type.details ?? "", {
new ConstantSchema(type.name ?? name, type.details ?? "", {
summary: type.description,
valueType: valueType,
value: new ConstantValue(type.value ?? type.name),
Expand Down Expand Up @@ -2091,10 +2089,7 @@ export class CodeModelBuilder {
}

private processModelPropertyFromSdkType(prop: SdkModelPropertyType): Property {
const rawModelPropertyType = prop.__raw as ModelProperty | undefined;
// TODO: This case is related with literal.tsp, once TCGC supports giving a name, we can use TCGC generatedName
const schemaNameHint = pascalCase(getNamePrefixForProperty(rawModelPropertyType)) + pascalCase(prop.name);
let schema = this.processSchemaFromSdkType(prop.type, schemaNameHint);
let schema = this.processSchemaFromSdkType(prop.type, "");
let nullable = prop.nullable;

let extensions: Record<string, any> | undefined = undefined;
Expand Down Expand Up @@ -2133,7 +2128,6 @@ export class CodeModelBuilder {
throw new Error(`Invalid type for union: '${type.kind}'.`);
}
const rawUnionType: Union = type.__raw as Union;
// TODO: name from typespec-client-generator-core
const namespace = getNamespace(rawUnionType);
const baseName = type.name ?? pascalCase(name) + "Model";
this.logWarning(
Expand Down Expand Up @@ -2265,13 +2259,9 @@ export class CodeModelBuilder {
}

private getName(
target: Model | Union | UnionVariant | Enum | EnumMember | ModelProperty | Scalar | Operation | undefined,
target: Union | UnionVariant | Enum | EnumMember | ModelProperty | Operation,
nameHint: string | undefined = undefined,
): string {
if (!target) {
return nameHint || "";
}

// TODO: once getLibraryName API in typespec-client-generator-core can get projected name from language and client, as well as can handle template case, use getLibraryName API
const emitterClientName = getClientNameOverride(this.sdkContext, target);
if (emitterClientName && typeof emitterClientName === "string") {
Expand All @@ -2293,24 +2283,6 @@ export class CodeModelBuilder {
return friendlyName;
}

// if no projectedName and friendlyName found, return the name of the target (including special handling for template)
if (
target.kind === "Model" &&
target.templateMapper &&
target.templateMapper.args &&
target.templateMapper.args.length > 0
) {
const tspName = getTypeName(target, this.typeNameOptions);
const newName = getNameForTemplate(target);
this.logWarning(`Rename TypeSpec Model '${tspName}' to '${newName}'`);
return newName;
}

if (!target.name && nameHint) {
const newName = nameHint;
this.logWarning(`Rename anonymous TypeSpec ${target.kind} to '${newName}'`);
return newName;
}
if (typeof target.name === "symbol") {
return "";
}
Expand Down
48 changes: 1 addition & 47 deletions typespec-extension/src/type-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
EnumMember,
IntrinsicScalarName,
Model,
ModelProperty,
Program,
Scalar,
StringLiteral,
Expand All @@ -21,7 +20,7 @@ import {
} from "@typespec/compiler";
import { SchemaContext } from "@autorest/codemodel";
import { DurationSchema } from "./common/schemas/time.js";
import { getNamespace, pascalCase } from "./utils.js";
import { getNamespace } from "./utils.js";
import { getUnionAsEnum } from "@azure-tools/typespec-azure-core";
import { SdkDurationType, isSdkFloatKind, isSdkIntKind } from "@azure-tools/typespec-client-generator-core";
import { Version } from "@typespec/versioning";
Expand Down Expand Up @@ -83,24 +82,6 @@ export function isModelReferredInTemplate(template: TemplatedTypeBase, target: M
);
}

export function getNameForTemplate(target: Type): string {
switch (target.kind) {
case "Model": {
let name = target.name;
if (target.templateMapper && target.templateMapper.args) {
name = name + target.templateMapper.args.map((it) => ("kind" in it ? getNameForTemplate(it) : "")).join("");
}
return name;
}

case "String":
return target.value;

default:
return "";
}
}

export function isNullableType(type: Type): boolean {
if (type.kind === "Union") {
const nullVariants = Array.from(type.variants.values()).filter((it) => isNullType(it.type));
Expand Down Expand Up @@ -222,33 +203,6 @@ export function getUnionDescription(union: Union, typeNameOptions: TypeNameOptio
return name;
}

export function getNamePrefixForProperty(property: ModelProperty | undefined): string {
if (property && property.model) {
if (property.model.name) {
return property.model.name;
} else if (property.model.namespace) {
for (const model of property.model.namespace.models.values()) {
for (const prop of model.properties.values()) {
const candidateModel = prop.type;
// find the property that refers to the unnamed property.model
if (
candidateModel.kind === "Model" &&
(candidateModel === property.model || candidateModel.indexer?.value === property.model)
) {
return getNamePrefixForProperty(prop) + pascalCase(prop.name);
} else if (
candidateModel.kind === "Union" &&
Array.from(candidateModel.variants.values()).find((it) => it.type === property.model)
) {
return getNamePrefixForProperty(prop) + pascalCase(prop.name);
}
}
}
}
}
return "";
}

export function modelIs(model: Model, name: string, namespace: string): boolean {
let currentModel: Model | undefined = model;
while (currentModel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import com.azure.core.util.FluxUtil;
import com.cadl.literalservice.implementation.LiteralOpsImpl;
import com.cadl.literalservice.models.Model;
import com.cadl.literalservice.models.OptionalLiteralParam;
import com.cadl.literalservice.models.PutRequestOptionalLiteralParam;
import reactor.core.publisher.Mono;

/**
Expand Down Expand Up @@ -96,7 +96,7 @@ public Mono<Response<BinaryData>> putWithResponse(BinaryData model, RequestOptio
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Model> put(Model model, OptionalLiteralParam optionalLiteralParam) {
public Mono<Model> put(Model model, PutRequestOptionalLiteralParam optionalLiteralParam) {
// Generated convenience method for putWithResponse
RequestOptions requestOptions = new RequestOptions();
if (optionalLiteralParam != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import com.azure.core.util.BinaryData;
import com.cadl.literalservice.implementation.LiteralOpsImpl;
import com.cadl.literalservice.models.Model;
import com.cadl.literalservice.models.OptionalLiteralParam;
import com.cadl.literalservice.models.PutRequestOptionalLiteralParam;

/**
* Initializes a new instance of the synchronous LiteralServiceClient type.
Expand Down Expand Up @@ -94,7 +94,7 @@ public Response<BinaryData> putWithResponse(BinaryData model, RequestOptions req
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Model put(Model model, OptionalLiteralParam optionalLiteralParam) {
public Model put(Model model, PutRequestOptionalLiteralParam optionalLiteralParam) {
// Generated convenience method for putWithResponse
RequestOptions requestOptions = new RequestOptions();
if (optionalLiteralParam != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public final class Model implements JsonSerializable<Model> {
* The optionalLiteral property.
*/
@Generated
private ModelOptionalLiteral optionalLiteral;
private ModelOptionalLiteralOptionalLiteral optionalLiteral;

/**
* Creates an instance of Model class.
Expand All @@ -52,7 +52,7 @@ public String getLiteral() {
* @return the optionalLiteral value.
*/
@Generated
public ModelOptionalLiteral getOptionalLiteral() {
public ModelOptionalLiteralOptionalLiteral getOptionalLiteral() {
return this.optionalLiteral;
}

Expand All @@ -63,7 +63,7 @@ public ModelOptionalLiteral getOptionalLiteral() {
* @return the Model object itself.
*/
@Generated
public Model setOptionalLiteral(ModelOptionalLiteral optionalLiteral) {
public Model setOptionalLiteral(ModelOptionalLiteralOptionalLiteral optionalLiteral) {
this.optionalLiteral = optionalLiteral;
return this;
}
Expand Down Expand Up @@ -99,7 +99,8 @@ public static Model fromJson(JsonReader jsonReader) throws IOException {
reader.nextToken();

if ("optionalLiteral".equals(fieldName)) {
deserializedModel.optionalLiteral = ModelOptionalLiteral.fromString(reader.getString());
deserializedModel.optionalLiteral
= ModelOptionalLiteralOptionalLiteral.fromString(reader.getString());
} else {
reader.skipChildren();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,35 @@
package com.cadl.literalservice.models;

/**
* Defines values for ModelOptionalLiteral.
* Defines values for ModelOptionalLiteralOptionalLiteral.
*/
public enum ModelOptionalLiteral {
public enum ModelOptionalLiteralOptionalLiteral {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @srnagar, we now leverage TCGC to generate the name for optional literal enum. And their logic is to concat the literal value to the enum's name. e.g. the definitiion is optionalLiteral?: "optionalLiteral", so another OptionalLiteral is append to the name. Please let me know if this is acceptable or not.

/**
* Enum value optionalLiteral.
*/
OPTIONAL_LITERAL("optionalLiteral");

/**
* The actual serialized value for a ModelOptionalLiteral instance.
* The actual serialized value for a ModelOptionalLiteralOptionalLiteral instance.
*/
private final String value;

ModelOptionalLiteral(String value) {
ModelOptionalLiteralOptionalLiteral(String value) {
this.value = value;
}

/**
* Parses a serialized value to a ModelOptionalLiteral instance.
* Parses a serialized value to a ModelOptionalLiteralOptionalLiteral instance.
*
* @param value the serialized value to parse.
* @return the parsed ModelOptionalLiteral object, or null if unable to parse.
* @return the parsed ModelOptionalLiteralOptionalLiteral object, or null if unable to parse.
*/
public static ModelOptionalLiteral fromString(String value) {
public static ModelOptionalLiteralOptionalLiteral fromString(String value) {
if (value == null) {
return null;
}
ModelOptionalLiteral[] items = ModelOptionalLiteral.values();
for (ModelOptionalLiteral item : items) {
ModelOptionalLiteralOptionalLiteral[] items = ModelOptionalLiteralOptionalLiteral.values();
for (ModelOptionalLiteralOptionalLiteral item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,35 @@
package com.cadl.literalservice.models;

/**
* Defines values for OptionalLiteralParam.
* Defines values for PutRequestOptionalLiteralParam.
*/
public enum OptionalLiteralParam {
public enum PutRequestOptionalLiteralParam {
/**
* Enum value optionalLiteralParam.
*/
OPTIONAL_LITERAL_PARAM("optionalLiteralParam");

/**
* The actual serialized value for a OptionalLiteralParam instance.
* The actual serialized value for a PutRequestOptionalLiteralParam instance.
*/
private final String value;

OptionalLiteralParam(String value) {
PutRequestOptionalLiteralParam(String value) {
this.value = value;
}

/**
* Parses a serialized value to a OptionalLiteralParam instance.
* Parses a serialized value to a PutRequestOptionalLiteralParam instance.
*
* @param value the serialized value to parse.
* @return the parsed OptionalLiteralParam object, or null if unable to parse.
* @return the parsed PutRequestOptionalLiteralParam object, or null if unable to parse.
*/
public static OptionalLiteralParam fromString(String value) {
public static PutRequestOptionalLiteralParam fromString(String value) {
if (value == null) {
return null;
}
OptionalLiteralParam[] items = OptionalLiteralParam.values();
for (OptionalLiteralParam item : items) {
PutRequestOptionalLiteralParam[] items = PutRequestOptionalLiteralParam.values();
for (PutRequestOptionalLiteralParam item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public final class SpecialCharsAsyncClient {
* }
* }</pre>
*
* @param request The request parameter.
* @param readRequest The readRequest parameter.
* @param requestOptions The options to configure the HTTP request before HTTP client sends it.
* @throws HttpResponseException thrown if the request is rejected by server.
* @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
Expand All @@ -71,8 +71,8 @@ public final class SpecialCharsAsyncClient {
*/
@Generated
@ServiceMethod(returns = ReturnType.SINGLE)
public Mono<Response<BinaryData>> readWithResponse(BinaryData request, RequestOptions requestOptions) {
return this.serviceClient.readWithResponseAsync(request, requestOptions);
public Mono<Response<BinaryData>> readWithResponse(BinaryData readRequest, RequestOptions requestOptions) {
return this.serviceClient.readWithResponseAsync(readRequest, requestOptions);
}

/**
Expand All @@ -92,9 +92,9 @@ public Mono<Response<BinaryData>> readWithResponse(BinaryData request, RequestOp
public Mono<Resource> read(String id) {
// Generated convenience method for readWithResponse
RequestOptions requestOptions = new RequestOptions();
ReadRequest requestObj = new ReadRequest(id);
BinaryData request = BinaryData.fromObject(requestObj);
return readWithResponse(request, requestOptions).flatMap(FluxUtil::toMono)
ReadRequest readRequestObj = new ReadRequest(id);
BinaryData readRequest = BinaryData.fromObject(readRequestObj);
return readWithResponse(readRequest, requestOptions).flatMap(FluxUtil::toMono)
.map(protocolMethodData -> protocolMethodData.toObject(Resource.class));
}
}
Loading