authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-09-05 18:51:48-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2017-09-05 18:51:48-04:00
log48c44615a4f03c105a8053db552320d26482436a
treea2fa30353c38f068ec5510b38ff3e4bb8df30477
parent1449e71de87891757b35302a73f9f1ad03429030
parent3ff465e2883b556cd08afc08b0a2098255314d4a

Merge branch 'c-to-zig'


21 files changed, 3251 insertions(+), 921 deletions(-)

src/all_types.hpp+7-2
......@@ -751,6 +751,7 @@ struct AstNodeContainerDecl {
751751 ZigList<AstNode *> fields;
752752 ZigList<AstNode *> decls;
753753 ContainerLayout layout;
754 AstNode *init_arg_expr; // enum(T) or struct(endianness)
754755};
755756
756757struct AstNodeStructField {
......@@ -833,7 +834,6 @@ struct AstNode {
833834 enum NodeType type;
834835 size_t line;
835836 size_t column;
836 uint32_t create_index; // for determinism purposes
837837 ImportTableEntry *owner;
838838 union {
839839 AstNodeRoot root;
......@@ -1253,6 +1253,7 @@ enum BuiltinFnId {
12531253 BuiltinFnIdShrExact,
12541254 BuiltinFnIdSetEvalBranchQuota,
12551255 BuiltinFnIdAlignCast,
1256 BuiltinFnIdOpaqueType,
12561257};
12571258
12581259struct BuiltinFnEntry {
......@@ -1523,7 +1524,6 @@ struct CodeGen {
15231524 LLVMValueRef return_address_fn_val;
15241525 LLVMValueRef frame_address_fn_val;
15251526 bool error_during_imports;
1526 uint32_t next_node_index;
15271527 TypeTableEntry *err_tag_type;
15281528
15291529 const char **clang_argv;
......@@ -1859,6 +1859,7 @@ enum IrInstructionId {
18591859 IrInstructionIdSetEvalBranchQuota,
18601860 IrInstructionIdPtrTypeOf,
18611861 IrInstructionIdAlignCast,
1862 IrInstructionIdOpaqueType,
18621863};
18631864
18641865struct IrInstruction {
......@@ -2649,6 +2650,10 @@ struct IrInstructionAlignCast {
26492650 IrInstruction *target;
26502651};
26512652
2653struct IrInstructionOpaqueType {
2654 IrInstruction base;
2655};
2656
26522657static const size_t slice_ptr_index = 0;
26532658static const size_t slice_len_index = 1;
26542659
src/analyze.cpp+8-5
......@@ -1180,7 +1180,8 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c
11801180 }
11811181 }
11821182
1183 fn_type_id.return_type = analyze_type_expr(g, child_scope, fn_proto->return_type);
1183 fn_type_id.return_type = (fn_proto->return_type == nullptr) ?
1184 g->builtin_types.entry_void : analyze_type_expr(g, child_scope, fn_proto->return_type);
11841185
11851186 switch (fn_type_id.return_type->id) {
11861187 case TypeTableEntryIdInvalid:
......@@ -2056,7 +2057,7 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
20562057 for (size_t i = 0; i < fn_proto->params.length; i += 1) {
20572058 AstNode *param_node = fn_proto->params.at(i);
20582059 assert(param_node->type == NodeTypeParamDecl);
2059 if (buf_len(param_node->data.param_decl.name) == 0) {
2060 if (param_node->data.param_decl.name == nullptr) {
20602061 add_node_error(g, param_node, buf_sprintf("missing parameter name"));
20612062 }
20622063 }
......@@ -2268,7 +2269,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
22682269 {
22692270 // if the name is missing, we immediately announce an error
22702271 Buf *fn_name = node->data.fn_proto.name;
2271 if (buf_len(fn_name) == 0) {
2272 if (fn_name == nullptr) {
22722273 add_node_error(g, node, buf_sprintf("missing function name"));
22732274 break;
22742275 }
......@@ -2950,6 +2951,9 @@ void define_local_param_variables(CodeGen *g, FnTableEntry *fn_table_entry, Vari
29502951 } else {
29512952 param_name = buf_sprintf("arg%" ZIG_PRI_usize "", i);
29522953 }
2954 if (param_name == nullptr) {
2955 continue;
2956 }
29532957
29542958 TypeTableEntry *param_type = param_info->type;
29552959 bool is_noalias = param_info->is_noalias;
......@@ -3163,8 +3167,7 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package, Buf *a
31633167 import_entry->line_offsets = tokenization.line_offsets;
31643168 import_entry->path = abs_full_path;
31653169
3166 import_entry->root = ast_parse(source_code, tokenization.tokens, import_entry, g->err_color,
3167 &g->next_node_index);
3170 import_entry->root = ast_parse(source_code, tokenization.tokens, import_entry, g->err_color);
31683171 assert(import_entry->root);
31693172 if (g->verbose) {
31703173 ast_print(stderr, import_entry->root, 0);
src/ast_render.cpp+26-161
......@@ -112,16 +112,16 @@ static const char *extern_string(bool is_extern) {
112112 return is_extern ? "extern " : "";
113113}
114114
115static const char *calling_convention_string(CallingConvention cc) {
116 switch (cc) {
117 case CallingConventionUnspecified: return "";
118 case CallingConventionC: return "extern ";
119 case CallingConventionCold: return "coldcc ";
120 case CallingConventionNaked: return "nakedcc ";
121 case CallingConventionStdcall: return "stdcallcc ";
122 }
123 zig_unreachable();
124}
115//static const char *calling_convention_string(CallingConvention cc) {
116// switch (cc) {
117// case CallingConventionUnspecified: return "";
118// case CallingConventionC: return "extern ";
119// case CallingConventionCold: return "coldcc ";
120// case CallingConventionNaked: return "nakedcc ";
121// case CallingConventionStdcall: return "stdcallcc ";
122// }
123// zig_unreachable();
124//}
125125
126126static const char *inline_string(bool is_inline) {
127127 return is_inline ? "inline " : "";
......@@ -412,14 +412,17 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
412412 const char *pub_str = visib_mod_string(node->data.fn_proto.visib_mod);
413413 const char *extern_str = extern_string(node->data.fn_proto.is_extern);
414414 const char *inline_str = inline_string(node->data.fn_proto.is_inline);
415 fprintf(ar->f, "%s%s%sfn ", pub_str, inline_str, extern_str);
416 print_symbol(ar, node->data.fn_proto.name);
415 fprintf(ar->f, "%s%s%sfn", pub_str, inline_str, extern_str);
416 if (node->data.fn_proto.name != nullptr) {
417 fprintf(ar->f, " ");
418 print_symbol(ar, node->data.fn_proto.name);
419 }
417420 fprintf(ar->f, "(");
418421 size_t arg_count = node->data.fn_proto.params.length;
419422 for (size_t arg_i = 0; arg_i < arg_count; arg_i += 1) {
420423 AstNode *param_decl = node->data.fn_proto.params.at(arg_i);
421424 assert(param_decl->type == NodeTypeParamDecl);
422 if (buf_len(param_decl->data.param_decl.name) > 0) {
425 if (param_decl->data.param_decl.name != nullptr) {
423426 const char *noalias_str = param_decl->data.param_decl.is_noalias ? "noalias " : "";
424427 const char *inline_str = param_decl->data.param_decl.is_inline ? "inline " : "";
425428 fprintf(ar->f, "%s%s", noalias_str, inline_str);
......@@ -439,8 +442,10 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
439442 fprintf(ar->f, ")");
440443
441444 AstNode *return_type_node = node->data.fn_proto.return_type;
442 fprintf(ar->f, " -> ");
443 render_node_grouped(ar, return_type_node);
445 if (return_type_node != nullptr) {
446 fprintf(ar->f, " -> ");
447 render_node_grouped(ar, return_type_node);
448 }
444449 break;
445450 }
446451 case NodeTypeFnDef:
......@@ -651,16 +656,19 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
651656 break;
652657 case NodeTypeContainerDecl:
653658 {
659 const char *layout_str = layout_string(node->data.container_decl.layout);
654660 const char *container_str = container_string(node->data.container_decl.kind);
655 fprintf(ar->f, "%s {\n", container_str);
661 fprintf(ar->f, "%s%s {\n", layout_str, container_str);
656662 ar->indent += ar->indent_size;
657663 for (size_t field_i = 0; field_i < node->data.container_decl.fields.length; field_i += 1) {
658664 AstNode *field_node = node->data.container_decl.fields.at(field_i);
659665 assert(field_node->type == NodeTypeStructField);
660666 print_indent(ar);
661667 print_symbol(ar, field_node->data.struct_field.name);
662 fprintf(ar->f, ": ");
663 render_node_grouped(ar, field_node->data.struct_field.type);
668 if (field_node->data.struct_field.type != nullptr) {
669 fprintf(ar->f, ": ");
670 render_node_grouped(ar, field_node->data.struct_field.type);
671 }
664672 fprintf(ar->f, ",\n");
665673 }
666674
......@@ -989,146 +997,3 @@ void ast_render(CodeGen *codegen, FILE *f, AstNode *node, int indent_size) {
989997
990998 render_node_grouped(&ar, node);
991999}
992
993static void ast_render_tld_fn(AstRender *ar, Buf *name, TldFn *tld_fn) {
994 FnTableEntry *fn_entry = tld_fn->fn_entry;
995 FnTypeId *fn_type_id = &fn_entry->type_entry->data.fn.fn_type_id;
996 const char *visib_mod_str = visib_mod_string(tld_fn->base.visib_mod);
997 const char *cc_str = calling_convention_string(fn_type_id->cc);
998 fprintf(ar->f, "%s%sfn %s(", visib_mod_str, cc_str, buf_ptr(&fn_entry->symbol_name));
999 for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
1000 FnTypeParamInfo *param_info = &fn_type_id->param_info[i];
1001 if (i != 0) {
1002 fprintf(ar->f, ", ");
1003 }
1004 if (param_info->is_noalias) {
1005 fprintf(ar->f, "noalias ");
1006 }
1007 Buf *param_name = tld_fn->fn_entry->param_names ? tld_fn->fn_entry->param_names[i] : buf_sprintf("arg%" ZIG_PRI_usize "", i);
1008 fprintf(ar->f, "%s: %s", buf_ptr(param_name), buf_ptr(&param_info->type->name));
1009 }
1010 if (fn_type_id->return_type->id == TypeTableEntryIdVoid) {
1011 fprintf(ar->f, ");\n");
1012 } else {
1013 fprintf(ar->f, ") -> %s;\n", buf_ptr(&fn_type_id->return_type->name));
1014 }
1015}
1016
1017static void ast_render_tld_var(AstRender *ar, Buf *name, TldVar *tld_var) {
1018 VariableTableEntry *var = tld_var->var;
1019 const char *visib_mod_str = visib_mod_string(tld_var->base.visib_mod);
1020 const char *const_or_var = const_or_var_string(var->src_is_const);
1021 const char *extern_str = extern_string(var->linkage == VarLinkageExternal);
1022 fprintf(ar->f, "%s%s%s %s", visib_mod_str, extern_str, const_or_var, buf_ptr(name));
1023
1024 if (var->value->type->id == TypeTableEntryIdNumLitFloat ||
1025 var->value->type->id == TypeTableEntryIdNumLitInt ||
1026 var->value->type->id == TypeTableEntryIdMetaType)
1027 {
1028 // skip type
1029 } else {
1030 fprintf(ar->f, ": %s", buf_ptr(&var->value->type->name));
1031 }
1032
1033 if (var->value->special == ConstValSpecialRuntime) {
1034 fprintf(ar->f, ";\n");
1035 return;
1036 }
1037
1038 fprintf(ar->f, " = ");
1039
1040 if (var->value->special == ConstValSpecialStatic &&
1041 var->value->type->id == TypeTableEntryIdMetaType)
1042 {
1043 TypeTableEntry *type_entry = var->value->data.x_type;
1044 if (type_entry->id == TypeTableEntryIdStruct) {
1045 const char *layout_str = layout_string(type_entry->data.structure.layout);
1046 fprintf(ar->f, "%sstruct {\n", layout_str);
1047 if (type_entry->data.structure.complete) {
1048 for (size_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) {
1049 TypeStructField *field = &type_entry->data.structure.fields[i];
1050 fprintf(ar->f, " ");
1051 print_symbol(ar, field->name);
1052 fprintf(ar->f, ": %s,\n", buf_ptr(&field->type_entry->name));
1053 }
1054 }
1055 fprintf(ar->f, "}");
1056 } else if (type_entry->id == TypeTableEntryIdEnum) {
1057 const char *layout_str = layout_string(type_entry->data.enumeration.layout);
1058 fprintf(ar->f, "%senum {\n", layout_str);
1059 if (type_entry->data.enumeration.complete) {
1060 for (size_t i = 0; i < type_entry->data.enumeration.src_field_count; i += 1) {
1061 TypeEnumField *field = &type_entry->data.enumeration.fields[i];
1062 fprintf(ar->f, " ");
1063 print_symbol(ar, field->name);
1064 if (field->type_entry->id == TypeTableEntryIdVoid) {
1065 fprintf(ar->f, ",\n");
1066 } else {
1067 fprintf(ar->f, ": %s,\n", buf_ptr(&field->type_entry->name));
1068 }
1069 }
1070 }
1071 fprintf(ar->f, "}");
1072 } else if (type_entry->id == TypeTableEntryIdUnion) {
1073 fprintf(ar->f, "union {");
1074 fprintf(ar->f, "TODO");
1075 fprintf(ar->f, "}");
1076 } else if (type_entry->id == TypeTableEntryIdOpaque) {
1077 if (buf_eql_buf(&type_entry->name, name)) {
1078 fprintf(ar->f, "@OpaqueType()");
1079 } else {
1080 fprintf(ar->f, "%s", buf_ptr(&type_entry->name));
1081 }
1082 } else {
1083 fprintf(ar->f, "%s", buf_ptr(&type_entry->name));
1084 }
1085 } else {
1086 Buf buf = BUF_INIT;
1087 buf_resize(&buf, 0);
1088 render_const_value(ar->codegen, &buf, var->value);
1089 fprintf(ar->f, "%s", buf_ptr(&buf));
1090 }
1091
1092 fprintf(ar->f, ";\n");
1093}
1094
1095void ast_render_decls(CodeGen *codegen, FILE *f, int indent_size, ImportTableEntry *import) {
1096 AstRender ar = {0};
1097 ar.codegen = codegen;
1098 ar.f = f;
1099 ar.indent_size = indent_size;
1100 ar.indent = 0;
1101
1102 auto it = import->decls_scope->decl_table.entry_iterator();
1103 for (;;) {
1104 auto *entry = it.next();
1105 if (!entry)
1106 break;
1107
1108 Tld *tld = entry->value;
1109
1110 if (tld->name != nullptr && !buf_eql_buf(entry->key, tld->name)) {
1111 fprintf(ar.f, "pub const ");
1112 print_symbol(&ar, entry->key);
1113 fprintf(ar.f, " = %s;\n", buf_ptr(tld->name));
1114 continue;
1115 }
1116
1117 switch (tld->id) {
1118 case TldIdVar:
1119 ast_render_tld_var(&ar, entry->key, (TldVar *)tld);
1120 break;
1121 case TldIdFn:
1122 ast_render_tld_fn(&ar, entry->key, (TldFn *)tld);
1123 break;
1124 case TldIdContainer:
1125 fprintf(stdout, "container\n");
1126 break;
1127 case TldIdCompTime:
1128 fprintf(stdout, "comptime\n");
1129 break;
1130 }
1131 }
1132}
1133
1134
src/ast_render.hpp-2
......@@ -19,7 +19,5 @@ void ast_render(CodeGen *codegen, FILE *f, AstNode *node, int indent_size);
1919
2020const char *container_string(ContainerKind kind);
2121
22void ast_render_decls(CodeGen *codegen, FILE *f, int indent_size, ImportTableEntry *import);
23
2422#endif
2523
src/bigint.cpp+19
......@@ -165,6 +165,25 @@ void bigint_init_signed(BigInt *dest, int64_t x) {
165165 dest->data.digit = ((uint64_t)(-(x + 1))) + 1;
166166}
167167
168void bigint_init_data(BigInt *dest, const uint64_t *digits, size_t digit_count, bool is_negative) {
169 if (digit_count == 0) {
170 return bigint_init_unsigned(dest, 0);
171 } else if (digit_count == 1) {
172 dest->digit_count = 1;
173 dest->data.digit = digits[0];
174 dest->is_negative = is_negative;
175 bigint_normalize(dest);
176 return;
177 }
178
179 dest->digit_count = digit_count;
180 dest->is_negative = is_negative;
181 dest->data.digits = allocate_nonzero<uint64_t>(digit_count);
182 memcpy(dest->data.digits, digits, sizeof(uint64_t) * digit_count);
183
184 bigint_normalize(dest);
185}
186
168187void bigint_init_bigint(BigInt *dest, const BigInt *src) {
169188 if (src->digit_count == 0) {
170189 return bigint_init_unsigned(dest, 0);
src/bigint.hpp+1
......@@ -34,6 +34,7 @@ void bigint_init_u128(BigInt *dest, unsigned __int128 x);
3434void bigint_init_signed(BigInt *dest, int64_t x);
3535void bigint_init_bigint(BigInt *dest, const BigInt *src);
3636void bigint_init_bigfloat(BigInt *dest, const BigFloat *op);
37void bigint_init_data(BigInt *dest, const uint64_t *digits, size_t digit_count, bool is_negative);
3738
3839// panics if number won't fit
3940uint64_t bigint_as_unsigned(const BigInt *bigint);
src/codegen.cpp+4-1
......@@ -469,7 +469,8 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
469469 FnTableEntry *fn_table_entry = fn_scope->fn_entry;
470470 if (!fn_table_entry->proto_node)
471471 return get_di_scope(g, scope->parent);
472 unsigned line_number = (unsigned)fn_table_entry->proto_node->line + 1;
472 unsigned line_number = (unsigned)(fn_table_entry->proto_node->line == 0) ?
473 0 : (fn_table_entry->proto_node->line + 1);
473474 unsigned scope_line = line_number;
474475 bool is_definition = fn_table_entry->body_node != nullptr;
475476 unsigned flags = 0;
......@@ -3328,6 +3329,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,
33283329 case IrInstructionIdTypeId:
33293330 case IrInstructionIdSetEvalBranchQuota:
33303331 case IrInstructionIdPtrTypeOf:
3332 case IrInstructionIdOpaqueType:
33313333 zig_unreachable();
33323334 case IrInstructionIdReturn:
33333335 return ir_render_return(g, executable, (IrInstructionReturn *)instruction);
......@@ -4732,6 +4734,7 @@ static void define_builtin_fns(CodeGen *g) {
47324734 create_builtin_fn(g, BuiltinFnIdShrExact, "shrExact", 2);
47334735 create_builtin_fn(g, BuiltinFnIdSetEvalBranchQuota, "setEvalBranchQuota", 1);
47344736 create_builtin_fn(g, BuiltinFnIdAlignCast, "alignCast", 2);
4737 create_builtin_fn(g, BuiltinFnIdOpaqueType, "OpaqueType", 0);
47354738}
47364739
47374740static const char *bool_to_str(bool b) {
src/codegen.hpp-1
......@@ -55,7 +55,6 @@ void codegen_add_assembly(CodeGen *g, Buf *path);
5555void codegen_add_object(CodeGen *g, Buf *object_path);
5656
5757void codegen_parseh(CodeGen *g, Buf *path);
58void codegen_render_ast(CodeGen *g, FILE *f, int indent_size);
5958
6059
6160#endif
src/errmsg.cpp+5-2
......@@ -79,11 +79,14 @@ ErrorMsg *err_msg_create_with_offset(Buf *path, size_t line, size_t column, size
7979 for (;;) {
8080 if (line_start_offset == 0) {
8181 break;
82 } else if (source[line_start_offset] == '\n') {
82 }
83
84 line_start_offset -= 1;
85
86 if (source[line_start_offset] == '\n') {
8387 line_start_offset += 1;
8488 break;
8589 }
86 line_start_offset -= 1;
8790 }
8891
8992 size_t line_end_offset = offset;
src/ir.cpp+55-78
......@@ -559,6 +559,10 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionAlignCast *) {
559559 return IrInstructionIdAlignCast;
560560}
561561
562static constexpr IrInstructionId ir_instruction_id(IrInstructionOpaqueType *) {
563 return IrInstructionIdOpaqueType;
564}
565
562566template<typename T>
563567static T *ir_create_instruction(IrBuilder *irb, Scope *scope, AstNode *source_node) {
564568 T *special_instruction = allocate<T>(1);
......@@ -2238,6 +2242,12 @@ static IrInstruction *ir_build_align_cast(IrBuilder *irb, Scope *scope, AstNode
22382242 return &instruction->base;
22392243}
22402244
2245static IrInstruction *ir_build_opaque_type(IrBuilder *irb, Scope *scope, AstNode *source_node) {
2246 IrInstructionOpaqueType *instruction = ir_build_instruction<IrInstructionOpaqueType>(irb, scope, source_node);
2247
2248 return &instruction->base;
2249}
2250
22412251static IrInstruction *ir_instruction_br_get_dep(IrInstructionBr *instruction, size_t index) {
22422252 return nullptr;
22432253}
......@@ -2956,6 +2966,10 @@ static IrInstruction *ir_instruction_aligncast_get_dep(IrInstructionAlignCast *i
29562966 }
29572967}
29582968
2969static IrInstruction *ir_instruction_opaquetype_get_dep(IrInstructionOpaqueType *instruction, size_t index) {
2970 return nullptr;
2971}
2972
29592973static IrInstruction *ir_instruction_get_dep(IrInstruction *instruction, size_t index) {
29602974 switch (instruction->id) {
29612975 case IrInstructionIdInvalid:
......@@ -3154,6 +3168,8 @@ static IrInstruction *ir_instruction_get_dep(IrInstruction *instruction, size_t
31543168 return ir_instruction_ptrtypeof_get_dep((IrInstructionPtrTypeOf *) instruction, index);
31553169 case IrInstructionIdAlignCast:
31563170 return ir_instruction_aligncast_get_dep((IrInstructionAlignCast *) instruction, index);
3171 case IrInstructionIdOpaqueType:
3172 return ir_instruction_opaquetype_get_dep((IrInstructionOpaqueType *) instruction, index);
31573173 }
31583174 zig_unreachable();
31593175}
......@@ -4578,6 +4594,8 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo
45784594
45794595 return ir_build_align_cast(irb, scope, node, arg0_value, arg1_value);
45804596 }
4597 case BuiltinFnIdOpaqueType:
4598 return ir_build_opaque_type(irb, scope, node);
45814599 }
45824600 zig_unreachable();
45834601}
......@@ -6044,27 +6062,30 @@ static bool render_instance_name_recursive(CodeGen *codegen, Buf *name, Scope *o
60446062 return true;
60456063}
60466064
6047static IrInstruction *ir_gen_container_decl(IrBuilder *irb, Scope *parent_scope, AstNode *node) {
6048 assert(node->type == NodeTypeContainerDecl);
6049
6050 ContainerKind kind = node->data.container_decl.kind;
6051 Buf *name;
6052 if (irb->exec->name) {
6053 name = irb->exec->name;
6065static Buf *get_anon_type_name(CodeGen *codegen, IrExecutable *exec, const char *kind_name, AstNode *source_node) {
6066 if (exec->name) {
6067 return exec->name;
60546068 } else {
6055 FnTableEntry *fn_entry = exec_fn_entry(irb->exec);
6069 FnTableEntry *fn_entry = exec_fn_entry(exec);
60566070 if (fn_entry) {
6057 name = buf_alloc();
6071 Buf *name = buf_alloc();
60586072 buf_append_buf(name, &fn_entry->symbol_name);
60596073 buf_appendf(name, "(");
6060 render_instance_name_recursive(irb->codegen, name, &fn_entry->fndef_scope->base, irb->exec->begin_scope);
6074 render_instance_name_recursive(codegen, name, &fn_entry->fndef_scope->base, exec->begin_scope);
60616075 buf_appendf(name, ")");
6076 return name;
60626077 } else {
6063 name = buf_sprintf("(anonymous %s at %s:%" ZIG_PRI_usize ":%" ZIG_PRI_usize ")", container_string(kind),
6064 buf_ptr(node->owner->path), node->line + 1, node->column + 1);
6078 return buf_sprintf("(anonymous %s at %s:%" ZIG_PRI_usize ":%" ZIG_PRI_usize ")", kind_name,
6079 buf_ptr(source_node->owner->path), source_node->line + 1, source_node->column + 1);
60656080 }
60666081 }
6082}
60676083
6084static IrInstruction *ir_gen_container_decl(IrBuilder *irb, Scope *parent_scope, AstNode *node) {
6085 assert(node->type == NodeTypeContainerDecl);
6086
6087 ContainerKind kind = node->data.container_decl.kind;
6088 Buf *name = get_anon_type_name(irb->codegen, irb->exec, container_string(kind), node);
60686089
60696090 VisibMod visib_mod = VisibModPub;
60706091 TldContainer *tld_container = allocate<TldContainer>(1);
......@@ -6114,9 +6135,14 @@ static IrInstruction *ir_gen_fn_proto(IrBuilder *irb, Scope *parent_scope, AstNo
61146135 return irb->codegen->invalid_instruction;
61156136 }
61166137
6117 IrInstruction *return_type = ir_gen_node(irb, node->data.fn_proto.return_type, parent_scope);
6118 if (return_type == irb->codegen->invalid_instruction)
6119 return irb->codegen->invalid_instruction;
6138 IrInstruction *return_type;
6139 if (node->data.fn_proto.return_type == nullptr) {
6140 return_type = ir_build_const_type(irb, parent_scope, node, irb->codegen->builtin_types.entry_void);
6141 } else {
6142 return_type = ir_gen_node(irb, node->data.fn_proto.return_type, parent_scope);
6143 if (return_type == irb->codegen->invalid_instruction)
6144 return irb->codegen->invalid_instruction;
6145 }
61206146
61216147 return ir_build_fn_proto(irb, parent_scope, node, param_types, align_value, return_type, is_var_args);
61226148}
......@@ -13358,9 +13384,11 @@ static TypeTableEntry *ir_analyze_instruction_c_import(IrAnalyze *ira, IrInstruc
1335813384 if (ira->codegen->verbose) {
1335913385 fprintf(stderr, "\nC imports:\n");
1336013386 fprintf(stderr, "-----------\n");
13361 ast_render_decls(ira->codegen, stderr, 4, child_import);
13387 ast_render(ira->codegen, stderr, child_import->root, 4);
1336213388 }
1336313389
13390 scan_decls(ira->codegen, child_import->decls_scope, child_import->root);
13391
1336413392 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);
1336513393 out_val->data.x_import = child_import;
1336613394 return ira->codegen->builtin_types.entry_namespace;
......@@ -15136,6 +15164,14 @@ static TypeTableEntry *ir_analyze_instruction_align_cast(IrAnalyze *ira, IrInstr
1513615164 return result->value.type;
1513715165}
1513815166
15167static TypeTableEntry *ir_analyze_instruction_opaque_type(IrAnalyze *ira, IrInstructionOpaqueType *instruction) {
15168 Buf *name = get_anon_type_name(ira->codegen, ira->new_irb.exec, "opaque", instruction->base.source_node);
15169 ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base);
15170 out_val->data.x_type = get_opaque_type(ira->codegen, instruction->base.scope, instruction->base.source_node,
15171 buf_ptr(name));
15172 return ira->codegen->builtin_types.entry_type;
15173}
15174
1513915175static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstruction *instruction) {
1514015176 switch (instruction->id) {
1514115177 case IrInstructionIdInvalid:
......@@ -15322,6 +15358,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi
1532215358 return ir_analyze_instruction_ptr_type_of(ira, (IrInstructionPtrTypeOf *)instruction);
1532315359 case IrInstructionIdAlignCast:
1532415360 return ir_analyze_instruction_align_cast(ira, (IrInstructionAlignCast *)instruction);
15361 case IrInstructionIdOpaqueType:
15362 return ir_analyze_instruction_opaque_type(ira, (IrInstructionOpaqueType *)instruction);
1532515363 }
1532615364 zig_unreachable();
1532715365}
......@@ -15500,6 +15538,7 @@ bool ir_has_side_effects(IrInstruction *instruction) {
1550015538 case IrInstructionIdOffsetOf:
1550115539 case IrInstructionIdTypeId:
1550215540 case IrInstructionIdAlignCast:
15541 case IrInstructionIdOpaqueType:
1550315542 return false;
1550415543 case IrInstructionIdAsm:
1550515544 {
......@@ -15515,65 +15554,3 @@ bool ir_has_side_effects(IrInstruction *instruction) {
1551515554 }
1551615555 zig_unreachable();
1551715556}
15518
15519FnTableEntry *ir_create_inline_fn(CodeGen *codegen, Buf *fn_name, VariableTableEntry *var, Scope *parent_scope) {
15520 FnTableEntry *fn_entry = create_fn_raw(FnInlineAuto, GlobalLinkageIdInternal);
15521 buf_init_from_buf(&fn_entry->symbol_name, fn_name);
15522
15523 fn_entry->fndef_scope = create_fndef_scope(nullptr, parent_scope, fn_entry);
15524 fn_entry->child_scope = &fn_entry->fndef_scope->base;
15525
15526 assert(var->value->type->id == TypeTableEntryIdMaybe);
15527 TypeTableEntry *src_fn_type = var->value->type->data.maybe.child_type;
15528 assert(src_fn_type->id == TypeTableEntryIdFn);
15529
15530 FnTypeId new_fn_type = src_fn_type->data.fn.fn_type_id;
15531 new_fn_type.cc = CallingConventionUnspecified;
15532
15533 fn_entry->type_entry = get_fn_type(codegen, &new_fn_type);
15534
15535 IrBuilder ir_builder = {0};
15536 IrBuilder *irb = &ir_builder;
15537
15538 irb->codegen = codegen;
15539 irb->exec = &fn_entry->ir_executable;
15540
15541 AstNode *source_node = parent_scope->source_node;
15542
15543 size_t arg_count = fn_entry->type_entry->data.fn.fn_type_id.param_count;
15544 IrInstruction **args = allocate<IrInstruction *>(arg_count);
15545 VariableTableEntry **arg_vars = allocate<VariableTableEntry *>(arg_count);
15546
15547 define_local_param_variables(codegen, fn_entry, arg_vars);
15548 Scope *scope = fn_entry->child_scope;
15549
15550 irb->current_basic_block = ir_build_basic_block(irb, scope, "Entry");
15551 // Entry block gets a reference because we enter it to begin.
15552 ir_ref_bb(irb->current_basic_block);
15553
15554 IrInstruction *maybe_fn_ptr = ir_build_var_ptr(irb, scope, source_node, var, true, false);
15555 IrInstruction *unwrapped_fn_ptr = ir_build_unwrap_maybe(irb, scope, source_node, maybe_fn_ptr, true);
15556 IrInstruction *fn_ref_instruction = ir_build_load_ptr(irb, scope, source_node, unwrapped_fn_ptr);
15557
15558 for (size_t i = 0; i < arg_count; i += 1) {
15559 IrInstruction *var_ptr_instruction = ir_build_var_ptr(irb, scope, source_node, arg_vars[i], true, false);
15560 args[i] = ir_build_load_ptr(irb, scope, source_node, var_ptr_instruction);
15561 }
15562
15563 IrInstruction *call_instruction = ir_build_call(irb, scope, source_node, nullptr, fn_ref_instruction,
15564 arg_count, args, false, false);
15565 ir_build_return(irb, scope, source_node, call_instruction);
15566
15567 if (codegen->verbose) {
15568 fprintf(stderr, "{\n");
15569 ir_print(codegen, stderr, &fn_entry->ir_executable, 4);
15570 fprintf(stderr, "}\n");
15571 }
15572
15573 analyze_fn_ir(codegen, fn_entry, nullptr);
15574
15575 codegen->fn_defs.append(fn_entry);
15576
15577 return fn_entry;
15578}
15579
src/ir.hpp-2
......@@ -24,6 +24,4 @@ TypeTableEntry *ir_analyze(CodeGen *g, IrExecutable *old_executable, IrExecutabl
2424bool ir_has_side_effects(IrInstruction *instruction);
2525ConstExprValue *const_ptr_pointee(CodeGen *codegen, ConstExprValue *const_val);
2626
27FnTableEntry *ir_create_inline_fn(CodeGen *codegen, Buf *fn_name, VariableTableEntry *var, Scope *parent_scope);
28
2927#endif
src/ir_print.cpp+7
......@@ -944,6 +944,10 @@ static void ir_print_align_cast(IrPrint *irp, IrInstructionAlignCast *instructio
944944 fprintf(irp->f, ")");
945945}
946946
947static void ir_print_opaque_type(IrPrint *irp, IrInstructionOpaqueType *instruction) {
948 fprintf(irp->f, "@OpaqueType()");
949}
950
947951static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
948952 ir_print_prefix(irp, instruction);
949953 switch (instruction->id) {
......@@ -1240,6 +1244,9 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
12401244 case IrInstructionIdAlignCast:
12411245 ir_print_align_cast(irp, (IrInstructionAlignCast *)instruction);
12421246 break;
1247 case IrInstructionIdOpaqueType:
1248 ir_print_opaque_type(irp, (IrInstructionOpaqueType *)instruction);
1249 break;
12431250 }
12441251 fprintf(irp->f, "\n");
12451252}
src/main.cpp+1-1
......@@ -670,7 +670,7 @@ int main(int argc, char **argv) {
670670 return EXIT_SUCCESS;
671671 } else if (cmd == CmdParseH) {
672672 codegen_parseh(g, in_file_buf);
673 ast_render_decls(g, stdout, 4, g->root_import);
673 ast_render(g, stdout, g->root_import->root, 4);
674674 if (timing_info)
675675 codegen_print_timing_report(g, stdout);
676676 return EXIT_SUCCESS;
src/parseh.cpp+1571-636
......@@ -15,8 +15,10 @@
1515#include "parseh.hpp"
1616#include "parser.hpp"
1717
18
1819#include <clang/Frontend/ASTUnit.h>
1920#include <clang/Frontend/CompilerInstance.h>
21#include <clang/AST/Expr.h>
2022
2123#include <string.h>
2224
......@@ -27,14 +29,9 @@ struct MacroSymbol {
2729 Buf *value;
2830};
2931
30struct GlobalValue {
31 TypeTableEntry *type;
32 bool is_const;
33};
34
3532struct Alias {
36 Buf *name;
37 Tld *tld;
33 Buf *new_name;
34 Buf *canon_name;
3835};
3936
4037struct Context {
......@@ -42,30 +39,27 @@ struct Context {
4239 ZigList<ErrorMsg *> *errors;
4340 bool warnings_on;
4441 VisibMod visib_mod;
45 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> global_type_table;
46 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> struct_type_table;
47 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> enum_type_table;
48 HashMap<const void *, TypeTableEntry *, ptr_hash, ptr_eq> decl_table;
49 HashMap<Buf *, Tld *, buf_hash, buf_eql_buf> macro_table;
42 AstNode *root;
43 HashMap<const void *, AstNode *, ptr_hash, ptr_eq> decl_table;
44 HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> macro_table;
5045 SourceManager *source_manager;
5146 ZigList<Alias> aliases;
5247 ZigList<MacroSymbol> macro_symbols;
5348 AstNode *source_node;
54 uint32_t next_anon_index;
5549
5650 CodeGen *codegen;
51 ASTContext *ctx;
5752};
5853
59static TypeTableEntry *resolve_qual_type_with_table(Context *c, QualType qt, const Decl *decl,
60 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> *type_table);
61
62static TypeTableEntry *resolve_qual_type(Context *c, QualType qt, const Decl *decl);
63static TypeTableEntry *resolve_record_decl(Context *c, const RecordDecl *record_decl);
64static TypeTableEntry *resolve_enum_decl(Context *c, const EnumDecl *enum_decl);
54static AstNode *resolve_record_decl(Context *c, const RecordDecl *record_decl);
55static AstNode *resolve_enum_decl(Context *c, const EnumDecl *enum_decl);
56static AstNode *resolve_typedef_decl(Context *c, const TypedefNameDecl *typedef_decl);
57static AstNode *trans_qual_type_with_table(Context *c, QualType qt, const SourceLocation &source_loc);
58static AstNode *trans_qual_type(Context *c, QualType qt, const SourceLocation &source_loc);
6559
6660
6761__attribute__ ((format (printf, 3, 4)))
68static void emit_warning(Context *c, const Decl *decl, const char *format, ...) {
62static void emit_warning(Context *c, const SourceLocation &sl, const char *format, ...) {
6963 if (!c->warnings_on) {
7064 return;
7165 }
......@@ -75,8 +69,6 @@ static void emit_warning(Context *c, const Decl *decl, const char *format, ...)
7569 Buf *msg = buf_vprintf(format, ap);
7670 va_end(ap);
7771
78 SourceLocation sl = decl->getLocation();
79
8072 StringRef filename = c->source_manager->getFilename(sl);
8173 const char *filename_bytes = (const char *)filename.bytes_begin();
8274 Buf *path;
......@@ -90,141 +82,214 @@ static void emit_warning(Context *c, const Decl *decl, const char *format, ...)
9082 fprintf(stderr, "%s:%u:%u: warning: %s\n", buf_ptr(path), line, column, buf_ptr(msg));
9183}
9284
93static uint32_t get_next_anon_index(Context *c) {
94 uint32_t result = c->next_anon_index;
95 c->next_anon_index += 1;
96 return result;
85static void add_global_weak_alias(Context *c, Buf *new_name, Buf *canon_name) {
86 Alias *alias = c->aliases.add_one();
87 alias->new_name = new_name;
88 alias->canon_name = canon_name;
9789}
9890
99static void add_global_alias(Context *c, Buf *name, Tld *tld) {
100 c->import->decls_scope->decl_table.put(name, tld);
91static AstNode * trans_create_node(Context *c, NodeType id) {
92 AstNode *node = allocate<AstNode>(1);
93 node->type = id;
94 node->owner = c->import;
95 // TODO line/column. mapping to C file??
96 return node;
10197}
10298
103static void add_global_weak_alias(Context *c, Buf *name, Tld *tld) {
104 Alias *alias = c->aliases.add_one();
105 alias->name = name;
106 alias->tld = tld;
99static AstNode *trans_create_node_float_lit(Context *c, double value) {
100 AstNode *node = trans_create_node(c, NodeTypeFloatLiteral);
101 node->data.float_literal.bigfloat = allocate<BigFloat>(1);
102 bigfloat_init_64(node->data.float_literal.bigfloat, value);
103 return node;
107104}
108105
109static void add_global(Context *c, Tld *tld) {
110 return add_global_alias(c, tld->name, tld);
106static AstNode *trans_create_node_symbol(Context *c, Buf *name) {
107 AstNode *node = trans_create_node(c, NodeTypeSymbol);
108 node->data.symbol_expr.symbol = name;
109 return node;
111110}
112111
113static Tld *get_global(Context *c, Buf *name) {
114 {
115 auto entry = c->import->decls_scope->decl_table.maybe_get(name);
116 if (entry)
117 return entry->value;
118 }
119 {
120 auto entry = c->macro_table.maybe_get(name);
121 if (entry)
122 return entry->value;
123 }
124 return nullptr;
112static AstNode *trans_create_node_symbol_str(Context *c, const char *name) {
113 return trans_create_node_symbol(c, buf_create_from_str(name));
125114}
126115
127static const char *decl_name(const Decl *decl) {
128 const NamedDecl *named_decl = static_cast<const NamedDecl *>(decl);
129 return (const char *)named_decl->getName().bytes_begin();
116static AstNode *trans_create_node_builtin_fn_call(Context *c, Buf *name) {
117 AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);
118 node->data.fn_call_expr.fn_ref_expr = trans_create_node_symbol(c, name);
119 node->data.fn_call_expr.is_builtin = true;
120 return node;
130121}
131122
132static void parseh_init_tld(Context *c, Tld *tld, TldId id, Buf *name) {
133 init_tld(tld, id, name, c->visib_mod, c->source_node, &c->import->decls_scope->base);
134 tld->resolution = TldResolutionOk;
135 tld->import = c->import;
123static AstNode *trans_create_node_builtin_fn_call_str(Context *c, const char *name) {
124 return trans_create_node_builtin_fn_call(c, buf_create_from_str(name));
136125}
137126
138static Tld *create_inline_fn_tld(Context *c, Buf *fn_name, TldVar *tld_var) {
139 TldFn *tld_fn = allocate<TldFn>(1);
140 parseh_init_tld(c, &tld_fn->base, TldIdFn, fn_name);
141 tld_fn->fn_entry = ir_create_inline_fn(c->codegen, fn_name, tld_var->var, &c->import->decls_scope->base);
142 return &tld_fn->base;
127static AstNode *trans_create_node_opaque(Context *c) {
128 return trans_create_node_builtin_fn_call_str(c, "OpaqueType");
143129}
144130
145static TldVar *create_global_var(Context *c, Buf *name, ConstExprValue *var_value, bool is_const) {
146 auto entry = c->import->decls_scope->decl_table.maybe_get(name);
147 if (entry) {
148 Tld *existing_tld = entry->value;
149 assert(existing_tld->id == TldIdVar);
150 return (TldVar *)existing_tld;
151 }
152 TldVar *tld_var = allocate<TldVar>(1);
153 parseh_init_tld(c, &tld_var->base, TldIdVar, name);
154 tld_var->var = add_variable(c->codegen, c->source_node, &c->import->decls_scope->base,
155 name, is_const, var_value, &tld_var->base);
156 c->codegen->global_vars.append(tld_var);
157 return tld_var;
131static AstNode *trans_create_node_field_access(Context *c, AstNode *container, Buf *field_name) {
132 AstNode *node = trans_create_node(c, NodeTypeFieldAccessExpr);
133 node->data.field_access_expr.struct_expr = container;
134 node->data.field_access_expr.field_name = field_name;
135 return node;
158136}
159137
160static Tld *create_global_str_lit_var(Context *c, Buf *name, Buf *value) {
161 TldVar *tld_var = create_global_var(c, name, create_const_c_str_lit(c->codegen, value), true);
162 return &tld_var->base;
138static AstNode *trans_create_node_prefix_op(Context *c, PrefixOp op, AstNode *child_node) {
139 AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);
140 node->data.prefix_op_expr.prefix_op = op;
141 node->data.prefix_op_expr.primary_expr = child_node;
142 return node;
163143}
164144
165static Tld *create_global_num_lit_unsigned_negative_type(Context *c, Buf *name, uint64_t x, bool negative, TypeTableEntry *type_entry) {
166 ConstExprValue *var_val = create_const_unsigned_negative(type_entry, x, negative);
167 TldVar *tld_var = create_global_var(c, name, var_val, true);
168 return &tld_var->base;
145static AstNode *trans_create_node_addr_of(Context *c, bool is_const, bool is_volatile, AstNode *child_node) {
146 AstNode *node = trans_create_node(c, NodeTypeAddrOfExpr);
147 node->data.addr_of_expr.is_const = is_const;
148 node->data.addr_of_expr.is_volatile = is_volatile;
149 node->data.addr_of_expr.op_expr = child_node;
150 return node;
169151}
170152
171static Tld *create_global_num_lit_unsigned_negative(Context *c, Buf *name, uint64_t x, bool negative) {
172 return create_global_num_lit_unsigned_negative_type(c, name, x, negative, c->codegen->builtin_types.entry_num_lit_int);
153static AstNode *trans_create_node_str_lit_c(Context *c, Buf *buf) {
154 AstNode *node = trans_create_node(c, NodeTypeStringLiteral);
155 node->data.string_literal.buf = buf;
156 node->data.string_literal.c = true;
157 return node;
173158}
174159
175static Tld *create_global_num_lit_float(Context *c, Buf *name, double value) {
176 ConstExprValue *var_val = create_const_float(c->codegen->builtin_types.entry_num_lit_float, value);
177 TldVar *tld_var = create_global_var(c, name, var_val, true);
178 return &tld_var->base;
160static AstNode *trans_create_node_unsigned_negative(Context *c, uint64_t x, bool is_negative) {
161 AstNode *node = trans_create_node(c, NodeTypeIntLiteral);
162 node->data.int_literal.bigint = allocate<BigInt>(1);
163 bigint_init_data(node->data.int_literal.bigint, &x, 1, is_negative);
164 return node;
179165}
180166
181static ConstExprValue *create_const_int_ap(Context *c, TypeTableEntry *type, const Decl *source_decl,
182 const llvm::APSInt &aps_int)
167static AstNode *trans_create_node_unsigned(Context *c, uint64_t x) {
168 return trans_create_node_unsigned_negative(c, x, false);
169}
170
171static AstNode *trans_create_node_cast(Context *c, AstNode *dest, AstNode *src) {
172 AstNode *node = trans_create_node(c, NodeTypeFnCallExpr);
173 node->data.fn_call_expr.fn_ref_expr = dest;
174 node->data.fn_call_expr.params.resize(1);
175 node->data.fn_call_expr.params.items[0] = src;
176 return node;
177}
178
179static AstNode *trans_create_node_unsigned_negative_type(Context *c, uint64_t x, bool is_negative,
180 const char *type_name)
183181{
184 if (aps_int.isSigned()) {
185 if (aps_int > INT64_MAX || aps_int < INT64_MIN) {
186 emit_warning(c, source_decl, "integer overflow\n");
187 return nullptr;
188 } else {
189 return create_const_signed(type, aps_int.getExtValue());
190 }
191 } else {
192 if (aps_int > INT64_MAX) {
193 emit_warning(c, source_decl, "integer overflow\n");
194 return nullptr;
195 } else {
196 return create_const_unsigned_negative(type, aps_int.getExtValue(), false);
197 }
198 }
182 AstNode *lit_node = trans_create_node_unsigned_negative(c, x, is_negative);
183 return trans_create_node_cast(c, trans_create_node_symbol_str(c, type_name), lit_node);
199184}
200185
201static Tld *create_global_num_lit_ap(Context *c, const Decl *source_decl, Buf *name,
202 const llvm::APSInt &aps_int)
186static AstNode *trans_create_node_array_type(Context *c, AstNode *size_node, AstNode *child_type_node) {
187 AstNode *node = trans_create_node(c, NodeTypeArrayType);
188 node->data.array_type.size = size_node;
189 node->data.array_type.child_type = child_type_node;
190 return node;
191}
192
193static AstNode *trans_create_node_var_decl(Context *c, bool is_const, Buf *var_name, AstNode *type_node,
194 AstNode *init_node)
203195{
204 ConstExprValue *const_value = create_const_int_ap(c, c->codegen->builtin_types.entry_num_lit_int,
205 source_decl, aps_int);
206 if (!const_value)
207 return nullptr;
208 TldVar *tld_var = create_global_var(c, name, const_value, true);
209 return &tld_var->base;
196 AstNode *node = trans_create_node(c, NodeTypeVariableDeclaration);
197 node->data.variable_declaration.visib_mod = c->visib_mod;
198 node->data.variable_declaration.symbol = var_name;
199 node->data.variable_declaration.is_const = is_const;
200 node->data.variable_declaration.type = type_node;
201 node->data.variable_declaration.expr = init_node;
202 return node;
210203}
211204
212205
213static Tld *add_const_type(Context *c, Buf *name, TypeTableEntry *type_entry) {
214 ConstExprValue *var_value = create_const_type(c->codegen, type_entry);
215 TldVar *tld_var = create_global_var(c, name, var_value, true);
216 add_global(c, &tld_var->base);
206static AstNode *trans_create_node_inline_fn(Context *c, Buf *fn_name, Buf *var_name, AstNode *src_proto_node) {
207 AstNode *fn_def = trans_create_node(c, NodeTypeFnDef);
208 AstNode *fn_proto = trans_create_node(c, NodeTypeFnProto);
209 fn_proto->data.fn_proto.visib_mod = c->visib_mod;
210 fn_proto->data.fn_proto.name = fn_name;
211 fn_proto->data.fn_proto.is_inline = true;
212 fn_proto->data.fn_proto.return_type = src_proto_node->data.fn_proto.return_type; // TODO ok for these to alias?
213
214 fn_def->data.fn_def.fn_proto = fn_proto;
215 fn_proto->data.fn_proto.fn_def_node = fn_def;
216
217 AstNode *unwrap_node = trans_create_node_prefix_op(c, PrefixOpUnwrapMaybe, trans_create_node_symbol(c, var_name));
218 AstNode *fn_call_node = trans_create_node(c, NodeTypeFnCallExpr);
219 fn_call_node->data.fn_call_expr.fn_ref_expr = unwrap_node;
220
221 for (size_t i = 0; i < src_proto_node->data.fn_proto.params.length; i += 1) {
222 AstNode *src_param_node = src_proto_node->data.fn_proto.params.at(i);
223 Buf *param_name = src_param_node->data.param_decl.name;
224 if (!param_name) param_name = buf_sprintf("arg%" ZIG_PRI_usize "", i);
225
226 AstNode *dest_param_node = trans_create_node(c, NodeTypeParamDecl);
227 dest_param_node->data.param_decl.name = param_name;
228 dest_param_node->data.param_decl.type = src_param_node->data.param_decl.type;
229 dest_param_node->data.param_decl.is_noalias = src_param_node->data.param_decl.is_noalias;
230 fn_proto->data.fn_proto.params.append(dest_param_node);
231
232 fn_call_node->data.fn_call_expr.params.append(trans_create_node_symbol(c, param_name));
233
234 }
235
236 AstNode *block = trans_create_node(c, NodeTypeBlock);
237 block->data.block.statements.resize(1);
238 block->data.block.statements.items[0] = fn_call_node;
239 block->data.block.last_statement_is_result_expression = true;
240
241 fn_def->data.fn_def.body = block;
242 return fn_def;
243}
244
245static AstNode *get_global(Context *c, Buf *name) {
246 for (size_t i = 0; i < c->root->data.root.top_level_decls.length; i += 1) {
247 AstNode *decl_node = c->root->data.root.top_level_decls.items[i];
248 if (decl_node->type == NodeTypeVariableDeclaration) {
249 if (buf_eql_buf(decl_node->data.variable_declaration.symbol, name)) {
250 return decl_node;
251 }
252 } else if (decl_node->type == NodeTypeFnDef) {
253 if (buf_eql_buf(decl_node->data.fn_def.fn_proto->data.fn_proto.name, name)) {
254 return decl_node;
255 }
256 } else if (decl_node->type == NodeTypeFnProto) {
257 if (buf_eql_buf(decl_node->data.fn_proto.name, name)) {
258 return decl_node;
259 }
260 }
261 }
262 {
263 auto entry = c->macro_table.maybe_get(name);
264 if (entry)
265 return entry->value;
266 }
267 return nullptr;
268}
269
270static AstNode *add_global_var(Context *c, Buf *var_name, AstNode *value_node) {
271 bool is_const = true;
272 AstNode *type_node = nullptr;
273 AstNode *node = trans_create_node_var_decl(c, is_const, var_name, type_node, value_node);
274 c->root->data.root.top_level_decls.append(node);
275 return node;
276}
217277
218 c->global_type_table.put(name, type_entry);
219 return &tld_var->base;
278static const char *decl_name(const Decl *decl) {
279 const NamedDecl *named_decl = static_cast<const NamedDecl *>(decl);
280 return (const char *)named_decl->getName().bytes_begin();
220281}
221282
222static Tld *add_container_tld(Context *c, TypeTableEntry *type_entry) {
223 return add_const_type(c, &type_entry->name, type_entry);
283static AstNode *trans_create_node_apint(Context *c, const llvm::APSInt &aps_int) {
284 AstNode *node = trans_create_node(c, NodeTypeIntLiteral);
285 node->data.int_literal.bigint = allocate<BigInt>(1);
286 bigint_init_data(node->data.int_literal.bigint, aps_int.getRawData(), aps_int.getNumWords(), aps_int.isNegative());
287 return node;
288
224289}
225290
226static bool is_c_void_type(Context *c, TypeTableEntry *type_entry) {
227 return (type_entry == c->codegen->builtin_types.entry_c_void);
291static bool is_c_void_type(AstNode *node) {
292 return (node->type == NodeTypeSymbol && buf_eql_str(node->data.symbol_expr.symbol, "c_void"));
228293}
229294
230295static bool qual_type_child_is_fn_proto(const QualType &qt) {
......@@ -240,52 +305,118 @@ static bool qual_type_child_is_fn_proto(const QualType &qt) {
240305 return false;
241306}
242307
243static TypeTableEntry *resolve_type_with_table(Context *c, const Type *ty, const Decl *decl,
244 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> *type_table)
245{
308static bool c_is_signed_integer(Context *c, QualType qt) {
309 const Type *c_type = qt.getTypePtr();
310 if (c_type->getTypeClass() != Type::Builtin)
311 return false;
312 const BuiltinType *builtin_ty = static_cast<const BuiltinType*>(c_type);
313 switch (builtin_ty->getKind()) {
314 case BuiltinType::SChar:
315 case BuiltinType::Short:
316 case BuiltinType::Int:
317 case BuiltinType::Long:
318 case BuiltinType::LongLong:
319 case BuiltinType::Int128:
320 case BuiltinType::WChar_S:
321 return true;
322 default:
323 return false;
324 }
325}
326
327static bool c_is_unsigned_integer(Context *c, QualType qt) {
328 const Type *c_type = qt.getTypePtr();
329 if (c_type->getTypeClass() != Type::Builtin)
330 return false;
331 const BuiltinType *builtin_ty = static_cast<const BuiltinType*>(c_type);
332 switch (builtin_ty->getKind()) {
333 case BuiltinType::Char_U:
334 case BuiltinType::UChar:
335 case BuiltinType::Char_S:
336 case BuiltinType::UShort:
337 case BuiltinType::UInt:
338 case BuiltinType::ULong:
339 case BuiltinType::ULongLong:
340 case BuiltinType::UInt128:
341 case BuiltinType::WChar_U:
342 return true;
343 default:
344 return false;
345 }
346}
347
348static bool c_is_float(Context *c, QualType qt) {
349 const Type *c_type = qt.getTypePtr();
350 if (c_type->getTypeClass() != Type::Builtin)
351 return false;
352 const BuiltinType *builtin_ty = static_cast<const BuiltinType*>(c_type);
353 switch (builtin_ty->getKind()) {
354 case BuiltinType::Half:
355 case BuiltinType::Float:
356 case BuiltinType::Double:
357 case BuiltinType::Float128:
358 case BuiltinType::LongDouble:
359 return true;
360 default:
361 return false;
362 }
363}
364
365static AstNode * trans_stmt(Context *c, AstNode *block, Stmt *stmt);
366static AstNode * trans_qual_type(Context *c, QualType qt, const SourceLocation &source_loc);
367
368static AstNode * trans_expr(Context *c, AstNode *block, Expr *expr) {
369 return trans_stmt(c, block, expr);
370}
371
372static AstNode *trans_type_with_table(Context *c, const Type *ty, const SourceLocation &source_loc) {
246373 switch (ty->getTypeClass()) {
247374 case Type::Builtin:
248375 {
249376 const BuiltinType *builtin_ty = static_cast<const BuiltinType*>(ty);
250377 switch (builtin_ty->getKind()) {
251378 case BuiltinType::Void:
252 return c->codegen->builtin_types.entry_c_void;
379 return trans_create_node_symbol_str(c, "c_void");
253380 case BuiltinType::Bool:
254 return c->codegen->builtin_types.entry_bool;
381 return trans_create_node_symbol_str(c, "bool");
255382 case BuiltinType::Char_U:
256383 case BuiltinType::UChar:
257384 case BuiltinType::Char_S:
258 return c->codegen->builtin_types.entry_u8;
385 return trans_create_node_symbol_str(c, "u8");
259386 case BuiltinType::SChar:
260 return c->codegen->builtin_types.entry_i8;
387 return trans_create_node_symbol_str(c, "i8");
261388 case BuiltinType::UShort:
262 return get_c_int_type(c->codegen, CIntTypeUShort);
389 return trans_create_node_symbol_str(c, "c_ushort");
263390 case BuiltinType::UInt:
264 return get_c_int_type(c->codegen, CIntTypeUInt);
391 return trans_create_node_symbol_str(c, "c_uint");
265392 case BuiltinType::ULong:
266 return get_c_int_type(c->codegen, CIntTypeULong);
393 return trans_create_node_symbol_str(c, "c_ulong");
267394 case BuiltinType::ULongLong:
268 return get_c_int_type(c->codegen, CIntTypeULongLong);
395 return trans_create_node_symbol_str(c, "c_ulonglong");
269396 case BuiltinType::Short:
270 return get_c_int_type(c->codegen, CIntTypeShort);
397 return trans_create_node_symbol_str(c, "c_short");
271398 case BuiltinType::Int:
272 return get_c_int_type(c->codegen, CIntTypeInt);
399 return trans_create_node_symbol_str(c, "c_int");
273400 case BuiltinType::Long:
274 return get_c_int_type(c->codegen, CIntTypeLong);
401 return trans_create_node_symbol_str(c, "c_long");
275402 case BuiltinType::LongLong:
276 return get_c_int_type(c->codegen, CIntTypeLongLong);
403 return trans_create_node_symbol_str(c, "c_longlong");
404 case BuiltinType::UInt128:
405 return trans_create_node_symbol_str(c, "u128");
406 case BuiltinType::Int128:
407 return trans_create_node_symbol_str(c, "i128");
277408 case BuiltinType::Float:
278 return c->codegen->builtin_types.entry_f32;
409 return trans_create_node_symbol_str(c, "f32");
279410 case BuiltinType::Double:
280 return c->codegen->builtin_types.entry_f64;
411 return trans_create_node_symbol_str(c, "f64");
412 case BuiltinType::Float128:
413 return trans_create_node_symbol_str(c, "f128");
281414 case BuiltinType::LongDouble:
282 return c->codegen->builtin_types.entry_c_longdouble;
415 return trans_create_node_symbol_str(c, "c_longdouble");
283416 case BuiltinType::WChar_U:
284417 case BuiltinType::Char16:
285418 case BuiltinType::Char32:
286 case BuiltinType::UInt128:
287419 case BuiltinType::WChar_S:
288 case BuiltinType::Int128:
289420 case BuiltinType::Half:
290421 case BuiltinType::NullPtr:
291422 case BuiltinType::ObjCId:
......@@ -336,14 +467,13 @@ static TypeTableEntry *resolve_type_with_table(Context *c, const Type *ty, const
336467 case BuiltinType::OCLImage2dMSAADepthRW:
337468 case BuiltinType::OCLImage2dArrayMSAADepthRW:
338469 case BuiltinType::OCLImage3dRW:
339 case BuiltinType::Float128:
340470 case BuiltinType::OCLSampler:
341471 case BuiltinType::OCLEvent:
342472 case BuiltinType::OCLClkEvent:
343473 case BuiltinType::OCLQueue:
344474 case BuiltinType::OCLReserveID:
345 emit_warning(c, decl, "missed a builtin type");
346 return c->codegen->builtin_types.entry_invalid;
475 emit_warning(c, source_loc, "unsupported builtin type");
476 return nullptr;
347477 }
348478 break;
349479 }
......@@ -351,170 +481,150 @@ static TypeTableEntry *resolve_type_with_table(Context *c, const Type *ty, const
351481 {
352482 const PointerType *pointer_ty = static_cast<const PointerType*>(ty);
353483 QualType child_qt = pointer_ty->getPointeeType();
354 TypeTableEntry *child_type = resolve_qual_type(c, child_qt, decl);
355 if (type_is_invalid(child_type)) {
356 emit_warning(c, decl, "pointer to unresolved type");
357 return c->codegen->builtin_types.entry_invalid;
484 AstNode *child_node = trans_qual_type(c, child_qt, source_loc);
485 if (child_node == nullptr) {
486 emit_warning(c, source_loc, "pointer to unsupported type");
487 return nullptr;
358488 }
359489
360490 if (qual_type_child_is_fn_proto(child_qt)) {
361 return get_maybe_type(c->codegen, child_type);
491 return trans_create_node_prefix_op(c, PrefixOpMaybe, child_node);
362492 }
363 bool is_const = child_qt.isConstQualified();
364493
365 TypeTableEntry *non_null_pointer_type = get_pointer_to_type(c->codegen, child_type, is_const);
366 return get_maybe_type(c->codegen, non_null_pointer_type);
494 AstNode *pointer_node = trans_create_node_addr_of(c, child_qt.isConstQualified(),
495 child_qt.isVolatileQualified(), child_node);
496 return trans_create_node_prefix_op(c, PrefixOpMaybe, pointer_node);
367497 }
368498 case Type::Typedef:
369499 {
370500 const TypedefType *typedef_ty = static_cast<const TypedefType*>(ty);
371501 const TypedefNameDecl *typedef_decl = typedef_ty->getDecl();
372 Buf *type_name = buf_create_from_str(decl_name(typedef_decl));
373 if (buf_eql_str(type_name, "uint8_t")) {
374 return c->codegen->builtin_types.entry_u8;
375 } else if (buf_eql_str(type_name, "int8_t")) {
376 return c->codegen->builtin_types.entry_i8;
377 } else if (buf_eql_str(type_name, "uint16_t")) {
378 return c->codegen->builtin_types.entry_u16;
379 } else if (buf_eql_str(type_name, "int16_t")) {
380 return c->codegen->builtin_types.entry_i16;
381 } else if (buf_eql_str(type_name, "uint32_t")) {
382 return c->codegen->builtin_types.entry_u32;
383 } else if (buf_eql_str(type_name, "int32_t")) {
384 return c->codegen->builtin_types.entry_i32;
385 } else if (buf_eql_str(type_name, "uint64_t")) {
386 return c->codegen->builtin_types.entry_u64;
387 } else if (buf_eql_str(type_name, "int64_t")) {
388 return c->codegen->builtin_types.entry_i64;
389 } else if (buf_eql_str(type_name, "intptr_t")) {
390 return c->codegen->builtin_types.entry_isize;
391 } else if (buf_eql_str(type_name, "uintptr_t")) {
392 return c->codegen->builtin_types.entry_usize;
393 } else {
394 auto entry = type_table->maybe_get(type_name);
395 if (entry) {
396 if (type_is_invalid(entry->value)) {
397 return c->codegen->builtin_types.entry_invalid;
398 } else {
399 return entry->value;
400 }
401 } else {
402 return c->codegen->builtin_types.entry_invalid;
403 }
404 }
502 return resolve_typedef_decl(c, typedef_decl);
405503 }
406504 case Type::Elaborated:
407505 {
408506 const ElaboratedType *elaborated_ty = static_cast<const ElaboratedType*>(ty);
409507 switch (elaborated_ty->getKeyword()) {
410508 case ETK_Struct:
411 return resolve_qual_type_with_table(c, elaborated_ty->getNamedType(),
412 decl, &c->struct_type_table);
509 return trans_qual_type_with_table(c, elaborated_ty->getNamedType(), source_loc);
413510 case ETK_Enum:
414 return resolve_qual_type_with_table(c, elaborated_ty->getNamedType(),
415 decl, &c->enum_type_table);
511 return trans_qual_type_with_table(c, elaborated_ty->getNamedType(), source_loc);
416512 case ETK_Interface:
417513 case ETK_Union:
418514 case ETK_Class:
419515 case ETK_Typename:
420516 case ETK_None:
421 emit_warning(c, decl, "unsupported elaborated type");
422 return c->codegen->builtin_types.entry_invalid;
517 emit_warning(c, source_loc, "unsupported elaborated type");
518 return nullptr;
423519 }
424520 }
425521 case Type::FunctionProto:
426522 {
427523 const FunctionProtoType *fn_proto_ty = static_cast<const FunctionProtoType*>(ty);
428524
525 AstNode *proto_node = trans_create_node(c, NodeTypeFnProto);
429526 switch (fn_proto_ty->getCallConv()) {
430527 case CC_C: // __attribute__((cdecl))
528 proto_node->data.fn_proto.cc = CallingConventionC;
529 proto_node->data.fn_proto.is_extern = true;
431530 break;
432531 case CC_X86StdCall: // __attribute__((stdcall))
433 emit_warning(c, decl, "function type has x86 stdcall calling convention");
434 return c->codegen->builtin_types.entry_invalid;
532 proto_node->data.fn_proto.cc = CallingConventionStdcall;
533 break;
435534 case CC_X86FastCall: // __attribute__((fastcall))
436 emit_warning(c, decl, "function type has x86 fastcall calling convention");
437 return c->codegen->builtin_types.entry_invalid;
535 emit_warning(c, source_loc, "unsupported calling convention: x86 fastcall");
536 return nullptr;
438537 case CC_X86ThisCall: // __attribute__((thiscall))
439 emit_warning(c, decl, "function type has x86 thiscall calling convention");
440 return c->codegen->builtin_types.entry_invalid;
538 emit_warning(c, source_loc, "unsupported calling convention: x86 thiscall");
539 return nullptr;
441540 case CC_X86VectorCall: // __attribute__((vectorcall))
442 emit_warning(c, decl, "function type has x86 vectorcall calling convention");
443 return c->codegen->builtin_types.entry_invalid;
541 emit_warning(c, source_loc, "unsupported calling convention: x86 vectorcall");
542 return nullptr;
444543 case CC_X86Pascal: // __attribute__((pascal))
445 emit_warning(c, decl, "function type has x86 pascal calling convention");
446 return c->codegen->builtin_types.entry_invalid;
544 emit_warning(c, source_loc, "unsupported calling convention: x86 pascal");
545 return nullptr;
447546 case CC_Win64: // __attribute__((ms_abi))
448 emit_warning(c, decl, "function type has win64 calling convention");
449 return c->codegen->builtin_types.entry_invalid;
547 emit_warning(c, source_loc, "unsupported calling convention: win64");
548 return nullptr;
450549 case CC_X86_64SysV: // __attribute__((sysv_abi))
451 emit_warning(c, decl, "function type has x86 64sysv calling convention");
452 return c->codegen->builtin_types.entry_invalid;
550 emit_warning(c, source_loc, "unsupported calling convention: x86 64sysv");
551 return nullptr;
453552 case CC_X86RegCall:
454 emit_warning(c, decl, "function type has x86 reg calling convention");
455 return c->codegen->builtin_types.entry_invalid;
553 emit_warning(c, source_loc, "unsupported calling convention: x86 reg");
554 return nullptr;
456555 case CC_AAPCS: // __attribute__((pcs("aapcs")))
457 emit_warning(c, decl, "function type has aapcs calling convention");
458 return c->codegen->builtin_types.entry_invalid;
556 emit_warning(c, source_loc, "unsupported calling convention: aapcs");
557 return nullptr;
459558 case CC_AAPCS_VFP: // __attribute__((pcs("aapcs-vfp")))
460 emit_warning(c, decl, "function type has aapcs-vfp calling convention");
461 return c->codegen->builtin_types.entry_invalid;
559 emit_warning(c, source_loc, "unsupported calling convention: aapcs-vfp");
560 return nullptr;
462561 case CC_IntelOclBicc: // __attribute__((intel_ocl_bicc))
463 emit_warning(c, decl, "function type has intel_ocl_bicc calling convention");
464 return c->codegen->builtin_types.entry_invalid;
562 emit_warning(c, source_loc, "unsupported calling convention: intel_ocl_bicc");
563 return nullptr;
465564 case CC_SpirFunction: // default for OpenCL functions on SPIR target
466 emit_warning(c, decl, "function type has SPIR function calling convention");
467 return c->codegen->builtin_types.entry_invalid;
565 emit_warning(c, source_loc, "unsupported calling convention: SPIR function");
566 return nullptr;
468567 case CC_OpenCLKernel:
469 emit_warning(c, decl, "function type has OpenCLKernel calling convention");
470 return c->codegen->builtin_types.entry_invalid;
568 emit_warning(c, source_loc, "unsupported calling convention: OpenCLKernel");
569 return nullptr;
471570 case CC_Swift:
472 emit_warning(c, decl, "function type has Swift calling convention");
473 return c->codegen->builtin_types.entry_invalid;
571 emit_warning(c, source_loc, "unsupported calling convention: Swift");
572 return nullptr;
474573 case CC_PreserveMost:
475 emit_warning(c, decl, "function type has PreserveMost calling convention");
476 return c->codegen->builtin_types.entry_invalid;
574 emit_warning(c, source_loc, "unsupported calling convention: PreserveMost");
575 return nullptr;
477576 case CC_PreserveAll:
478 emit_warning(c, decl, "function type has PreserveAll calling convention");
479 return c->codegen->builtin_types.entry_invalid;
577 emit_warning(c, source_loc, "unsupported calling convention: PreserveAll");
578 return nullptr;
480579 }
481580
482 FnTypeId fn_type_id = {0};
483 fn_type_id.cc = CallingConventionC;
484 fn_type_id.is_var_args = fn_proto_ty->isVariadic();
485 fn_type_id.param_count = fn_proto_ty->getNumParams();
486
581 proto_node->data.fn_proto.is_var_args = fn_proto_ty->isVariadic();
582 size_t param_count = fn_proto_ty->getNumParams();
487583
488584 if (fn_proto_ty->getNoReturnAttr()) {
489 fn_type_id.return_type = c->codegen->builtin_types.entry_unreachable;
585 proto_node->data.fn_proto.return_type = trans_create_node_symbol_str(c, "noreturn");
490586 } else {
491 fn_type_id.return_type = resolve_qual_type(c, fn_proto_ty->getReturnType(), decl);
492 if (type_is_invalid(fn_type_id.return_type)) {
493 emit_warning(c, decl, "unresolved function proto return type");
494 return c->codegen->builtin_types.entry_invalid;
587 proto_node->data.fn_proto.return_type = trans_qual_type(c, fn_proto_ty->getReturnType(),
588 source_loc);
589 if (proto_node->data.fn_proto.return_type == nullptr) {
590 emit_warning(c, source_loc, "unsupported function proto return type");
591 return nullptr;
495592 }
496593 // convert c_void to actual void (only for return type)
497 if (is_c_void_type(c, fn_type_id.return_type)) {
498 fn_type_id.return_type = c->codegen->builtin_types.entry_void;
594 if (is_c_void_type(proto_node->data.fn_proto.return_type)) {
595 proto_node->data.fn_proto.return_type = nullptr;
499596 }
500597 }
501598
502 fn_type_id.param_info = allocate_nonzero<FnTypeParamInfo>(fn_type_id.param_count);
503 for (size_t i = 0; i < fn_type_id.param_count; i += 1) {
599 //emit_warning(c, source_loc, "TODO figure out fn prototype fn name");
600 const char *fn_name = nullptr;
601 if (fn_name != nullptr) {
602 proto_node->data.fn_proto.name = buf_create_from_str(fn_name);
603 }
604
605 for (size_t i = 0; i < param_count; i += 1) {
504606 QualType qt = fn_proto_ty->getParamType(i);
505 TypeTableEntry *param_type = resolve_qual_type(c, qt, decl);
607 AstNode *param_type_node = trans_qual_type(c, qt, source_loc);
506608
507 if (type_is_invalid(param_type)) {
508 emit_warning(c, decl, "unresolved function proto parameter type");
509 return c->codegen->builtin_types.entry_invalid;
609 if (param_type_node == nullptr) {
610 emit_warning(c, source_loc, "unresolved function proto parameter type");
611 return nullptr;
510612 }
511613
512 FnTypeParamInfo *param_info = &fn_type_id.param_info[i];
513 param_info->type = param_type;
514 param_info->is_noalias = qt.isRestrictQualified();
614 AstNode *param_node = trans_create_node(c, NodeTypeParamDecl);
615 //emit_warning(c, source_loc, "TODO figure out fn prototype param name");
616 const char *param_name = nullptr;
617 if (param_name != nullptr) {
618 param_node->data.param_decl.name = buf_create_from_str(param_name);
619 }
620 param_node->data.param_decl.is_noalias = qt.isRestrictQualified();
621 param_node->data.param_decl.type = param_type_node;
622 proto_node->data.fn_proto.params.append(param_node);
515623 }
624 // TODO check for always_inline attribute
625 // TODO check for align attribute
516626
517 return get_fn_type(c->codegen, &fn_type_id);
627 return proto_node;
518628 }
519629 case Type::Record:
520630 {
......@@ -529,28 +639,29 @@ static TypeTableEntry *resolve_type_with_table(Context *c, const Type *ty, const
529639 case Type::ConstantArray:
530640 {
531641 const ConstantArrayType *const_arr_ty = static_cast<const ConstantArrayType *>(ty);
532 TypeTableEntry *child_type = resolve_qual_type(c, const_arr_ty->getElementType(), decl);
533 if (child_type->id == TypeTableEntryIdInvalid) {
534 emit_warning(c, decl, "unresolved array element type");
535 return child_type;
642 AstNode *child_type_node = trans_qual_type(c, const_arr_ty->getElementType(), source_loc);
643 if (child_type_node == nullptr) {
644 emit_warning(c, source_loc, "unresolved array element type");
645 return nullptr;
536646 }
537647 uint64_t size = const_arr_ty->getSize().getLimitedValue();
538 return get_array_type(c->codegen, child_type, size);
648 AstNode *size_node = trans_create_node_unsigned(c, size);
649 return trans_create_node_array_type(c, size_node, child_type_node);
539650 }
540651 case Type::Paren:
541652 {
542653 const ParenType *paren_ty = static_cast<const ParenType *>(ty);
543 return resolve_qual_type(c, paren_ty->getInnerType(), decl);
654 return trans_qual_type(c, paren_ty->getInnerType(), source_loc);
544655 }
545656 case Type::Decayed:
546657 {
547658 const DecayedType *decayed_ty = static_cast<const DecayedType *>(ty);
548 return resolve_qual_type(c, decayed_ty->getDecayedType(), decl);
659 return trans_qual_type(c, decayed_ty->getDecayedType(), source_loc);
549660 }
550661 case Type::Attributed:
551662 {
552663 const AttributedType *attributed_ty = static_cast<const AttributedType *>(ty);
553 return resolve_qual_type(c, attributed_ty->getEquivalentType(), decl);
664 return trans_qual_type(c, attributed_ty->getEquivalentType(), source_loc);
554665 }
555666 case Type::BlockPointer:
556667 case Type::LValueReference:
......@@ -586,20 +697,897 @@ static TypeTableEntry *resolve_type_with_table(Context *c, const Type *ty, const
586697 case Type::Pipe:
587698 case Type::ObjCTypeParam:
588699 case Type::DeducedTemplateSpecialization:
589 emit_warning(c, decl, "missed a '%s' type", ty->getTypeClassName());
590 return c->codegen->builtin_types.entry_invalid;
700 emit_warning(c, source_loc, "unsupported type: '%s'", ty->getTypeClassName());
701 return nullptr;
591702 }
592703 zig_unreachable();
593704}
594705
595static TypeTableEntry *resolve_qual_type_with_table(Context *c, QualType qt, const Decl *decl,
596 HashMap<Buf *, TypeTableEntry *, buf_hash, buf_eql_buf> *type_table)
597{
598 return resolve_type_with_table(c, qt.getTypePtr(), decl, type_table);
706static AstNode * trans_qual_type_with_table(Context *c, QualType qt, const SourceLocation &source_loc) {
707 return trans_type_with_table(c, qt.getTypePtr(), source_loc);
708}
709
710static AstNode * trans_qual_type(Context *c, QualType qt, const SourceLocation &source_loc) {
711 return trans_qual_type_with_table(c, qt, source_loc);
599712}
600713
601static TypeTableEntry *resolve_qual_type(Context *c, QualType qt, const Decl *decl) {
602 return resolve_qual_type_with_table(c, qt, decl, &c->global_type_table);
714static AstNode * trans_compound_stmt(Context *c, AstNode *parent, CompoundStmt *stmt) {
715 AstNode *child_block = trans_create_node(c, NodeTypeBlock);
716 for (CompoundStmt::body_iterator it = stmt->body_begin(), end_it = stmt->body_end(); it != end_it; ++it) {
717 AstNode *child_node = trans_stmt(c, child_block, *it);
718 if (child_node != nullptr)
719 child_block->data.block.statements.append(child_node);
720 }
721 return child_block;
722}
723
724static AstNode *trans_return_stmt(Context *c, AstNode *block, ReturnStmt *stmt) {
725 Expr *value_expr = stmt->getRetValue();
726 if (value_expr == nullptr) {
727 zig_panic("TODO handle C return void");
728 } else {
729 AstNode *return_node = trans_create_node(c, NodeTypeReturnExpr);
730 return_node->data.return_expr.expr = trans_expr(c, block, value_expr);
731 return return_node;
732 }
733}
734
735static AstNode *trans_integer_literal(Context *c, IntegerLiteral *stmt) {
736 llvm::APSInt result;
737 if (!stmt->EvaluateAsInt(result, *c->ctx)) {
738 zig_panic("TODO handle libclang unable to evaluate C integer literal");
739 }
740 return trans_create_node_apint(c, result);
741}
742
743static AstNode *trans_conditional_operator(Context *c, AstNode *block, ConditionalOperator *stmt) {
744 AstNode *node = trans_create_node(c, NodeTypeIfBoolExpr);
745
746 Expr *cond_expr = stmt->getCond();
747 Expr *true_expr = stmt->getTrueExpr();
748 Expr *false_expr = stmt->getFalseExpr();
749
750 node->data.if_bool_expr.condition = trans_expr(c, block, cond_expr);
751 node->data.if_bool_expr.then_block = trans_expr(c, block, true_expr);
752 node->data.if_bool_expr.else_node = trans_expr(c, block, false_expr);
753
754 return node;
755}
756
757static AstNode * trans_create_bin_op(Context *c, AstNode *block, Expr *lhs, BinOpType bin_op, Expr *rhs) {
758 AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);
759 node->data.bin_op_expr.bin_op = bin_op;
760 node->data.bin_op_expr.op1 = trans_expr(c, block, lhs);
761 node->data.bin_op_expr.op2 = trans_expr(c, block, rhs);
762 return node;
763}
764
765static AstNode * trans_binary_operator(Context *c, AstNode *block, BinaryOperator *stmt) {
766 switch (stmt->getOpcode()) {
767 case BO_PtrMemD:
768 zig_panic("TODO handle more C binary operators: BO_PtrMemD");
769 case BO_PtrMemI:
770 zig_panic("TODO handle more C binary operators: BO_PtrMemI");
771 case BO_Mul:
772 zig_panic("TODO handle more C binary operators: BO_Mul");
773 case BO_Div:
774 zig_panic("TODO handle more C binary operators: BO_Div");
775 case BO_Rem:
776 zig_panic("TODO handle more C binary operators: BO_Rem");
777 case BO_Add:
778 zig_panic("TODO handle more C binary operators: BO_Add");
779 case BO_Sub:
780 zig_panic("TODO handle more C binary operators: BO_Sub");
781 case BO_Shl:
782 zig_panic("TODO handle more C binary operators: BO_Shl");
783 case BO_Shr:
784 zig_panic("TODO handle more C binary operators: BO_Shr");
785 case BO_LT:
786 return trans_create_bin_op(c, block, stmt->getLHS(), BinOpTypeCmpLessThan, stmt->getRHS());
787 case BO_GT:
788 return trans_create_bin_op(c, block, stmt->getLHS(), BinOpTypeCmpGreaterThan, stmt->getRHS());
789 case BO_LE:
790 return trans_create_bin_op(c, block, stmt->getLHS(), BinOpTypeCmpLessOrEq, stmt->getRHS());
791 case BO_GE:
792 return trans_create_bin_op(c, block, stmt->getLHS(), BinOpTypeCmpGreaterOrEq, stmt->getRHS());
793 case BO_EQ:
794 zig_panic("TODO handle more C binary operators: BO_EQ");
795 case BO_NE:
796 zig_panic("TODO handle more C binary operators: BO_NE");
797 case BO_And:
798 zig_panic("TODO handle more C binary operators: BO_And");
799 case BO_Xor:
800 zig_panic("TODO handle more C binary operators: BO_Xor");
801 case BO_Or:
802 zig_panic("TODO handle more C binary operators: BO_Or");
803 case BO_LAnd:
804 zig_panic("TODO handle more C binary operators: BO_LAnd");
805 case BO_LOr:
806 zig_panic("TODO handle more C binary operators: BO_LOr");
807 case BO_Assign:
808 zig_panic("TODO handle more C binary operators: BO_Assign");
809 case BO_MulAssign:
810 zig_panic("TODO handle more C binary operators: BO_MulAssign");
811 case BO_DivAssign:
812 zig_panic("TODO handle more C binary operators: BO_DivAssign");
813 case BO_RemAssign:
814 zig_panic("TODO handle more C binary operators: BO_RemAssign");
815 case BO_AddAssign:
816 zig_panic("TODO handle more C binary operators: BO_AddAssign");
817 case BO_SubAssign:
818 zig_panic("TODO handle more C binary operators: BO_SubAssign");
819 case BO_ShlAssign:
820 zig_panic("TODO handle more C binary operators: BO_ShlAssign");
821 case BO_ShrAssign:
822 zig_panic("TODO handle more C binary operators: BO_ShrAssign");
823 case BO_AndAssign:
824 zig_panic("TODO handle more C binary operators: BO_AndAssign");
825 case BO_XorAssign:
826 zig_panic("TODO handle more C binary operators: BO_XorAssign");
827 case BO_OrAssign:
828 zig_panic("TODO handle more C binary operators: BO_OrAssign");
829 case BO_Comma:
830 zig_panic("TODO handle more C binary operators: BO_Comma");
831 }
832
833 zig_unreachable();
834}
835
836static AstNode * trans_implicit_cast_expr(Context *c, AstNode *block, ImplicitCastExpr *stmt) {
837 switch (stmt->getCastKind()) {
838 case CK_LValueToRValue:
839 return trans_expr(c, block, stmt->getSubExpr());
840 case CK_IntegralCast:
841 {
842 AstNode *node = trans_create_node_builtin_fn_call_str(c, "bitCast");
843 node->data.fn_call_expr.params.append(trans_qual_type(c, stmt->getType(), stmt->getExprLoc()));
844 node->data.fn_call_expr.params.append(trans_expr(c, block, stmt->getSubExpr()));
845 return node;
846 }
847 case CK_Dependent:
848 zig_panic("TODO handle C translation cast CK_Dependent");
849 case CK_BitCast:
850 zig_panic("TODO handle C translation cast CK_BitCast");
851 case CK_LValueBitCast:
852 zig_panic("TODO handle C translation cast CK_LValueBitCast");
853 case CK_NoOp:
854 zig_panic("TODO handle C translation cast CK_NoOp");
855 case CK_BaseToDerived:
856 zig_panic("TODO handle C translation cast CK_BaseToDerived");
857 case CK_DerivedToBase:
858 zig_panic("TODO handle C translation cast CK_DerivedToBase");
859 case CK_UncheckedDerivedToBase:
860 zig_panic("TODO handle C translation cast CK_UncheckedDerivedToBase");
861 case CK_Dynamic:
862 zig_panic("TODO handle C translation cast CK_Dynamic");
863 case CK_ToUnion:
864 zig_panic("TODO handle C translation cast CK_ToUnion");
865 case CK_ArrayToPointerDecay:
866 zig_panic("TODO handle C translation cast CK_ArrayToPointerDecay");
867 case CK_FunctionToPointerDecay:
868 zig_panic("TODO handle C translation cast CK_FunctionToPointerDecay");
869 case CK_NullToPointer:
870 zig_panic("TODO handle C translation cast CK_NullToPointer");
871 case CK_NullToMemberPointer:
872 zig_panic("TODO handle C translation cast CK_NullToMemberPointer");
873 case CK_BaseToDerivedMemberPointer:
874 zig_panic("TODO handle C translation cast CK_BaseToDerivedMemberPointer");
875 case CK_DerivedToBaseMemberPointer:
876 zig_panic("TODO handle C translation cast CK_DerivedToBaseMemberPointer");
877 case CK_MemberPointerToBoolean:
878 zig_panic("TODO handle C translation cast CK_MemberPointerToBoolean");
879 case CK_ReinterpretMemberPointer:
880 zig_panic("TODO handle C translation cast CK_ReinterpretMemberPointer");
881 case CK_UserDefinedConversion:
882 zig_panic("TODO handle C translation cast CK_UserDefinedConversion");
883 case CK_ConstructorConversion:
884 zig_panic("TODO handle C translation cast CK_ConstructorConversion");
885 case CK_IntegralToPointer:
886 zig_panic("TODO handle C translation cast CK_IntegralToPointer");
887 case CK_PointerToIntegral:
888 zig_panic("TODO handle C translation cast CK_PointerToIntegral");
889 case CK_PointerToBoolean:
890 zig_panic("TODO handle C translation cast CK_PointerToBoolean");
891 case CK_ToVoid:
892 zig_panic("TODO handle C translation cast CK_ToVoid");
893 case CK_VectorSplat:
894 zig_panic("TODO handle C translation cast CK_VectorSplat");
895 case CK_IntegralToBoolean:
896 zig_panic("TODO handle C translation cast CK_IntegralToBoolean");
897 case CK_IntegralToFloating:
898 zig_panic("TODO handle C translation cast CK_IntegralToFloating");
899 case CK_FloatingToIntegral:
900 zig_panic("TODO handle C translation cast CK_FloatingToIntegral");
901 case CK_FloatingToBoolean:
902 zig_panic("TODO handle C translation cast CK_FloatingToBoolean");
903 case CK_BooleanToSignedIntegral:
904 zig_panic("TODO handle C translation cast CK_BooleanToSignedIntegral");
905 case CK_FloatingCast:
906 zig_panic("TODO handle C translation cast CK_FloatingCast");
907 case CK_CPointerToObjCPointerCast:
908 zig_panic("TODO handle C translation cast CK_CPointerToObjCPointerCast");
909 case CK_BlockPointerToObjCPointerCast:
910 zig_panic("TODO handle C translation cast CK_BlockPointerToObjCPointerCast");
911 case CK_AnyPointerToBlockPointerCast:
912 zig_panic("TODO handle C translation cast CK_AnyPointerToBlockPointerCast");
913 case CK_ObjCObjectLValueCast:
914 zig_panic("TODO handle C translation cast CK_ObjCObjectLValueCast");
915 case CK_FloatingRealToComplex:
916 zig_panic("TODO handle C translation cast CK_FloatingRealToComplex");
917 case CK_FloatingComplexToReal:
918 zig_panic("TODO handle C translation cast CK_FloatingComplexToReal");
919 case CK_FloatingComplexToBoolean:
920 zig_panic("TODO handle C translation cast CK_FloatingComplexToBoolean");
921 case CK_FloatingComplexCast:
922 zig_panic("TODO handle C translation cast CK_FloatingComplexCast");
923 case CK_FloatingComplexToIntegralComplex:
924 zig_panic("TODO handle C translation cast CK_FloatingComplexToIntegralComplex");
925 case CK_IntegralRealToComplex:
926 zig_panic("TODO handle C translation cast CK_IntegralRealToComplex");
927 case CK_IntegralComplexToReal:
928 zig_panic("TODO handle C translation cast CK_IntegralComplexToReal");
929 case CK_IntegralComplexToBoolean:
930 zig_panic("TODO handle C translation cast CK_IntegralComplexToBoolean");
931 case CK_IntegralComplexCast:
932 zig_panic("TODO handle C translation cast CK_IntegralComplexCast");
933 case CK_IntegralComplexToFloatingComplex:
934 zig_panic("TODO handle C translation cast CK_IntegralComplexToFloatingComplex");
935 case CK_ARCProduceObject:
936 zig_panic("TODO handle C translation cast CK_ARCProduceObject");
937 case CK_ARCConsumeObject:
938 zig_panic("TODO handle C translation cast CK_ARCConsumeObject");
939 case CK_ARCReclaimReturnedObject:
940 zig_panic("TODO handle C translation cast CK_ARCReclaimReturnedObject");
941 case CK_ARCExtendBlockObject:
942 zig_panic("TODO handle C translation cast CK_ARCExtendBlockObject");
943 case CK_AtomicToNonAtomic:
944 zig_panic("TODO handle C translation cast CK_AtomicToNonAtomic");
945 case CK_NonAtomicToAtomic:
946 zig_panic("TODO handle C translation cast CK_NonAtomicToAtomic");
947 case CK_CopyAndAutoreleaseBlockObject:
948 zig_panic("TODO handle C translation cast CK_CopyAndAutoreleaseBlockObject");
949 case CK_BuiltinFnToFnPtr:
950 zig_panic("TODO handle C translation cast CK_BuiltinFnToFnPtr");
951 case CK_ZeroToOCLEvent:
952 zig_panic("TODO handle C translation cast CK_ZeroToOCLEvent");
953 case CK_ZeroToOCLQueue:
954 zig_panic("TODO handle C translation cast CK_ZeroToOCLQueue");
955 case CK_AddressSpaceConversion:
956 zig_panic("TODO handle C translation cast CK_AddressSpaceConversion");
957 case CK_IntToOCLSampler:
958 zig_panic("TODO handle C translation cast CK_IntToOCLSampler");
959 }
960 zig_unreachable();
961}
962
963static AstNode * trans_decl_ref_expr(Context *c, DeclRefExpr *stmt) {
964 ValueDecl *value_decl = stmt->getDecl();
965 const char *name = decl_name(value_decl);
966
967 AstNode *node = trans_create_node(c, NodeTypeSymbol);
968 node->data.symbol_expr.symbol = buf_create_from_str(name);
969 return node;
970}
971
972static AstNode * trans_unary_operator(Context *c, AstNode *block, UnaryOperator *stmt) {
973 switch (stmt->getOpcode()) {
974 case UO_PostInc:
975 zig_panic("TODO handle C translation UO_PostInc");
976 case UO_PostDec:
977 zig_panic("TODO handle C translation UO_PostDec");
978 case UO_PreInc:
979 zig_panic("TODO handle C translation UO_PreInc");
980 case UO_PreDec:
981 zig_panic("TODO handle C translation UO_PreDec");
982 case UO_AddrOf:
983 zig_panic("TODO handle C translation UO_AddrOf");
984 case UO_Deref:
985 zig_panic("TODO handle C translation UO_Deref");
986 case UO_Plus:
987 zig_panic("TODO handle C translation UO_Plus");
988 case UO_Minus:
989 {
990 Expr *op_expr = stmt->getSubExpr();
991 if (c_is_signed_integer(c, op_expr->getType()) || c_is_float(c, op_expr->getType())) {
992 AstNode *node = trans_create_node(c, NodeTypePrefixOpExpr);
993 node->data.prefix_op_expr.prefix_op = PrefixOpNegation;
994 node->data.prefix_op_expr.primary_expr = trans_expr(c, block, op_expr);
995 return node;
996 } else if (c_is_unsigned_integer(c, op_expr->getType())) {
997 // we gotta emit 0 -% x
998 AstNode *node = trans_create_node(c, NodeTypeBinOpExpr);
999 node->data.bin_op_expr.op1 = trans_create_node_unsigned(c, 0);
1000 node->data.bin_op_expr.op2 = trans_expr(c, block, op_expr);
1001 node->data.bin_op_expr.bin_op = BinOpTypeSubWrap;
1002 return node;
1003 } else {
1004 zig_panic("TODO translate C negation with non float non integer");
1005 }
1006 }
1007 case UO_Not:
1008 zig_panic("TODO handle C translation UO_Not");
1009 case UO_LNot:
1010 zig_panic("TODO handle C translation UO_LNot");
1011 case UO_Real:
1012 zig_panic("TODO handle C translation UO_Real");
1013 case UO_Imag:
1014 zig_panic("TODO handle C translation UO_Imag");
1015 case UO_Extension:
1016 zig_panic("TODO handle C translation UO_Extension");
1017 case UO_Coawait:
1018 zig_panic("TODO handle C translation UO_Coawait");
1019 }
1020 zig_unreachable();
1021}
1022
1023static AstNode * trans_local_declaration(Context *c, AstNode *block, DeclStmt *stmt) {
1024 for (auto iter = stmt->decl_begin(); iter != stmt->decl_end(); iter++) {
1025 Decl *decl = *iter;
1026 switch (decl->getKind()) {
1027 case Decl::Var: {
1028 VarDecl *var_decl = (VarDecl *)decl;
1029 QualType qual_type = var_decl->getTypeSourceInfo()->getType();
1030 AstNode *init_node = var_decl->hasInit() ? trans_expr(c, block, var_decl->getInit()) : nullptr;
1031 AstNode *type_node = trans_qual_type(c, qual_type, stmt->getStartLoc());
1032 AstNode *node = trans_create_node_var_decl(c, qual_type.isConstQualified(),
1033 buf_create_from_str(decl_name(var_decl)), type_node, init_node);
1034 block->data.block.statements.append(node);
1035 continue;
1036 }
1037 case Decl::AccessSpec:
1038 zig_panic("TODO handle decl kind AccessSpec");
1039 case Decl::Block:
1040 zig_panic("TODO handle decl kind Block");
1041 case Decl::Captured:
1042 zig_panic("TODO handle decl kind Captured");
1043 case Decl::ClassScopeFunctionSpecialization:
1044 zig_panic("TODO handle decl kind ClassScopeFunctionSpecialization");
1045 case Decl::Empty:
1046 zig_panic("TODO handle decl kind Empty");
1047 case Decl::Export:
1048 zig_panic("TODO handle decl kind Export");
1049 case Decl::ExternCContext:
1050 zig_panic("TODO handle decl kind ExternCContext");
1051 case Decl::FileScopeAsm:
1052 zig_panic("TODO handle decl kind FileScopeAsm");
1053 case Decl::Friend:
1054 zig_panic("TODO handle decl kind Friend");
1055 case Decl::FriendTemplate:
1056 zig_panic("TODO handle decl kind FriendTemplate");
1057 case Decl::Import:
1058 zig_panic("TODO handle decl kind Import");
1059 case Decl::LinkageSpec:
1060 zig_panic("TODO handle decl kind LinkageSpec");
1061 case Decl::Label:
1062 zig_panic("TODO handle decl kind Label");
1063 case Decl::Namespace:
1064 zig_panic("TODO handle decl kind Namespace");
1065 case Decl::NamespaceAlias:
1066 zig_panic("TODO handle decl kind NamespaceAlias");
1067 case Decl::ObjCCompatibleAlias:
1068 zig_panic("TODO handle decl kind ObjCCompatibleAlias");
1069 case Decl::ObjCCategory:
1070 zig_panic("TODO handle decl kind ObjCCategory");
1071 case Decl::ObjCCategoryImpl:
1072 zig_panic("TODO handle decl kind ObjCCategoryImpl");
1073 case Decl::ObjCImplementation:
1074 zig_panic("TODO handle decl kind ObjCImplementation");
1075 case Decl::ObjCInterface:
1076 zig_panic("TODO handle decl kind ObjCInterface");
1077 case Decl::ObjCProtocol:
1078 zig_panic("TODO handle decl kind ObjCProtocol");
1079 case Decl::ObjCMethod:
1080 zig_panic("TODO handle decl kind ObjCMethod");
1081 case Decl::ObjCProperty:
1082 zig_panic("TODO handle decl kind ObjCProperty");
1083 case Decl::BuiltinTemplate:
1084 zig_panic("TODO handle decl kind BuiltinTemplate");
1085 case Decl::ClassTemplate:
1086 zig_panic("TODO handle decl kind ClassTemplate");
1087 case Decl::FunctionTemplate:
1088 zig_panic("TODO handle decl kind FunctionTemplate");
1089 case Decl::TypeAliasTemplate:
1090 zig_panic("TODO handle decl kind TypeAliasTemplate");
1091 case Decl::VarTemplate:
1092 zig_panic("TODO handle decl kind VarTemplate");
1093 case Decl::TemplateTemplateParm:
1094 zig_panic("TODO handle decl kind TemplateTemplateParm");
1095 case Decl::Enum:
1096 zig_panic("TODO handle decl kind Enum");
1097 case Decl::Record:
1098 zig_panic("TODO handle decl kind Record");
1099 case Decl::CXXRecord:
1100 zig_panic("TODO handle decl kind CXXRecord");
1101 case Decl::ClassTemplateSpecialization:
1102 zig_panic("TODO handle decl kind ClassTemplateSpecialization");
1103 case Decl::ClassTemplatePartialSpecialization:
1104 zig_panic("TODO handle decl kind ClassTemplatePartialSpecialization");
1105 case Decl::TemplateTypeParm:
1106 zig_panic("TODO handle decl kind TemplateTypeParm");
1107 case Decl::ObjCTypeParam:
1108 zig_panic("TODO handle decl kind ObjCTypeParam");
1109 case Decl::TypeAlias:
1110 zig_panic("TODO handle decl kind TypeAlias");
1111 case Decl::Typedef:
1112 zig_panic("TODO handle decl kind Typedef");
1113 case Decl::UnresolvedUsingTypename:
1114 zig_panic("TODO handle decl kind UnresolvedUsingTypename");
1115 case Decl::Using:
1116 zig_panic("TODO handle decl kind Using");
1117 case Decl::UsingDirective:
1118 zig_panic("TODO handle decl kind UsingDirective");
1119 case Decl::UsingPack:
1120 zig_panic("TODO handle decl kind UsingPack");
1121 case Decl::UsingShadow:
1122 zig_panic("TODO handle decl kind UsingShadow");
1123 case Decl::ConstructorUsingShadow:
1124 zig_panic("TODO handle decl kind ConstructorUsingShadow");
1125 case Decl::Binding:
1126 zig_panic("TODO handle decl kind Binding");
1127 case Decl::Field:
1128 zig_panic("TODO handle decl kind Field");
1129 case Decl::ObjCAtDefsField:
1130 zig_panic("TODO handle decl kind ObjCAtDefsField");
1131 case Decl::ObjCIvar:
1132 zig_panic("TODO handle decl kind ObjCIvar");
1133 case Decl::Function:
1134 zig_panic("TODO handle decl kind Function");
1135 case Decl::CXXDeductionGuide:
1136 zig_panic("TODO handle decl kind CXXDeductionGuide");
1137 case Decl::CXXMethod:
1138 zig_panic("TODO handle decl kind CXXMethod");
1139 case Decl::CXXConstructor:
1140 zig_panic("TODO handle decl kind CXXConstructor");
1141 case Decl::CXXConversion:
1142 zig_panic("TODO handle decl kind CXXConversion");
1143 case Decl::CXXDestructor:
1144 zig_panic("TODO handle decl kind CXXDestructor");
1145 case Decl::MSProperty:
1146 zig_panic("TODO handle decl kind MSProperty");
1147 case Decl::NonTypeTemplateParm:
1148 zig_panic("TODO handle decl kind NonTypeTemplateParm");
1149 case Decl::Decomposition:
1150 zig_panic("TODO handle decl kind Decomposition");
1151 case Decl::ImplicitParam:
1152 zig_panic("TODO handle decl kind ImplicitParam");
1153 case Decl::OMPCapturedExpr:
1154 zig_panic("TODO handle decl kind OMPCapturedExpr");
1155 case Decl::ParmVar:
1156 zig_panic("TODO handle decl kind ParmVar");
1157 case Decl::VarTemplateSpecialization:
1158 zig_panic("TODO handle decl kind VarTemplateSpecialization");
1159 case Decl::VarTemplatePartialSpecialization:
1160 zig_panic("TODO handle decl kind VarTemplatePartialSpecialization");
1161 case Decl::EnumConstant:
1162 zig_panic("TODO handle decl kind EnumConstant");
1163 case Decl::IndirectField:
1164 zig_panic("TODO handle decl kind IndirectField");
1165 case Decl::OMPDeclareReduction:
1166 zig_panic("TODO handle decl kind OMPDeclareReduction");
1167 case Decl::UnresolvedUsingValue:
1168 zig_panic("TODO handle decl kind UnresolvedUsingValue");
1169 case Decl::OMPThreadPrivate:
1170 zig_panic("TODO handle decl kind OMPThreadPrivate");
1171 case Decl::ObjCPropertyImpl:
1172 zig_panic("TODO handle decl kind ObjCPropertyImpl");
1173 case Decl::PragmaComment:
1174 zig_panic("TODO handle decl kind PragmaComment");
1175 case Decl::PragmaDetectMismatch:
1176 zig_panic("TODO handle decl kind PragmaDetectMismatch");
1177 case Decl::StaticAssert:
1178 zig_panic("TODO handle decl kind StaticAssert");
1179 case Decl::TranslationUnit:
1180 zig_panic("TODO handle decl kind TranslationUnit");
1181 }
1182 zig_unreachable();
1183 }
1184
1185 // declarations were already added
1186 return nullptr;
1187}
1188
1189static AstNode *trans_while_loop(Context *c, AstNode *block, WhileStmt *stmt) {
1190 AstNode *while_node = trans_create_node(c, NodeTypeWhileExpr);
1191 while_node->data.while_expr.condition = trans_expr(c, block, stmt->getCond());
1192 while_node->data.while_expr.body = trans_stmt(c, block, stmt->getBody());
1193 return while_node;
1194}
1195
1196static AstNode *trans_stmt(Context *c, AstNode *block, Stmt *stmt) {
1197 Stmt::StmtClass sc = stmt->getStmtClass();
1198 switch (sc) {
1199 case Stmt::ReturnStmtClass:
1200 return trans_return_stmt(c, block, (ReturnStmt *)stmt);
1201 case Stmt::CompoundStmtClass:
1202 return trans_compound_stmt(c, block, (CompoundStmt *)stmt);
1203 case Stmt::IntegerLiteralClass:
1204 return trans_integer_literal(c, (IntegerLiteral *)stmt);
1205 case Stmt::ConditionalOperatorClass:
1206 return trans_conditional_operator(c, block, (ConditionalOperator *)stmt);
1207 case Stmt::BinaryOperatorClass:
1208 return trans_binary_operator(c, block, (BinaryOperator *)stmt);
1209 case Stmt::ImplicitCastExprClass:
1210 return trans_implicit_cast_expr(c, block, (ImplicitCastExpr *)stmt);
1211 case Stmt::DeclRefExprClass:
1212 return trans_decl_ref_expr(c, (DeclRefExpr *)stmt);
1213 case Stmt::UnaryOperatorClass:
1214 return trans_unary_operator(c, block, (UnaryOperator *)stmt);
1215 case Stmt::DeclStmtClass:
1216 return trans_local_declaration(c, block, (DeclStmt *)stmt);
1217 case Stmt::WhileStmtClass:
1218 return trans_while_loop(c, block, (WhileStmt *)stmt);
1219 case Stmt::CaseStmtClass:
1220 zig_panic("TODO handle C CaseStmtClass");
1221 case Stmt::DefaultStmtClass:
1222 zig_panic("TODO handle C DefaultStmtClass");
1223 case Stmt::SwitchStmtClass:
1224 zig_panic("TODO handle C SwitchStmtClass");
1225 case Stmt::NoStmtClass:
1226 zig_panic("TODO handle C NoStmtClass");
1227 case Stmt::GCCAsmStmtClass:
1228 zig_panic("TODO handle C GCCAsmStmtClass");
1229 case Stmt::MSAsmStmtClass:
1230 zig_panic("TODO handle C MSAsmStmtClass");
1231 case Stmt::AttributedStmtClass:
1232 zig_panic("TODO handle C AttributedStmtClass");
1233 case Stmt::BreakStmtClass:
1234 zig_panic("TODO handle C BreakStmtClass");
1235 case Stmt::CXXCatchStmtClass:
1236 zig_panic("TODO handle C CXXCatchStmtClass");
1237 case Stmt::CXXForRangeStmtClass:
1238 zig_panic("TODO handle C CXXForRangeStmtClass");
1239 case Stmt::CXXTryStmtClass:
1240 zig_panic("TODO handle C CXXTryStmtClass");
1241 case Stmt::CapturedStmtClass:
1242 zig_panic("TODO handle C CapturedStmtClass");
1243 case Stmt::ContinueStmtClass:
1244 zig_panic("TODO handle C ContinueStmtClass");
1245 case Stmt::CoreturnStmtClass:
1246 zig_panic("TODO handle C CoreturnStmtClass");
1247 case Stmt::CoroutineBodyStmtClass:
1248 zig_panic("TODO handle C CoroutineBodyStmtClass");
1249 case Stmt::DoStmtClass:
1250 zig_panic("TODO handle C DoStmtClass");
1251 case Stmt::BinaryConditionalOperatorClass:
1252 zig_panic("TODO handle C BinaryConditionalOperatorClass");
1253 case Stmt::AddrLabelExprClass:
1254 zig_panic("TODO handle C AddrLabelExprClass");
1255 case Stmt::ArrayInitIndexExprClass:
1256 zig_panic("TODO handle C ArrayInitIndexExprClass");
1257 case Stmt::ArrayInitLoopExprClass:
1258 zig_panic("TODO handle C ArrayInitLoopExprClass");
1259 case Stmt::ArraySubscriptExprClass:
1260 zig_panic("TODO handle C ArraySubscriptExprClass");
1261 case Stmt::ArrayTypeTraitExprClass:
1262 zig_panic("TODO handle C ArrayTypeTraitExprClass");
1263 case Stmt::AsTypeExprClass:
1264 zig_panic("TODO handle C AsTypeExprClass");
1265 case Stmt::AtomicExprClass:
1266 zig_panic("TODO handle C AtomicExprClass");
1267 case Stmt::CompoundAssignOperatorClass:
1268 zig_panic("TODO handle C CompoundAssignOperatorClass");
1269 case Stmt::BlockExprClass:
1270 zig_panic("TODO handle C BlockExprClass");
1271 case Stmt::CXXBindTemporaryExprClass:
1272 zig_panic("TODO handle C CXXBindTemporaryExprClass");
1273 case Stmt::CXXBoolLiteralExprClass:
1274 zig_panic("TODO handle C CXXBoolLiteralExprClass");
1275 case Stmt::CXXConstructExprClass:
1276 zig_panic("TODO handle C CXXConstructExprClass");
1277 case Stmt::CXXTemporaryObjectExprClass:
1278 zig_panic("TODO handle C CXXTemporaryObjectExprClass");
1279 case Stmt::CXXDefaultArgExprClass:
1280 zig_panic("TODO handle C CXXDefaultArgExprClass");
1281 case Stmt::CXXDefaultInitExprClass:
1282 zig_panic("TODO handle C CXXDefaultInitExprClass");
1283 case Stmt::CXXDeleteExprClass:
1284 zig_panic("TODO handle C CXXDeleteExprClass");
1285 case Stmt::CXXDependentScopeMemberExprClass:
1286 zig_panic("TODO handle C CXXDependentScopeMemberExprClass");
1287 case Stmt::CXXFoldExprClass:
1288 zig_panic("TODO handle C CXXFoldExprClass");
1289 case Stmt::CXXInheritedCtorInitExprClass:
1290 zig_panic("TODO handle C CXXInheritedCtorInitExprClass");
1291 case Stmt::CXXNewExprClass:
1292 zig_panic("TODO handle C CXXNewExprClass");
1293 case Stmt::CXXNoexceptExprClass:
1294 zig_panic("TODO handle C CXXNoexceptExprClass");
1295 case Stmt::CXXNullPtrLiteralExprClass:
1296 zig_panic("TODO handle C CXXNullPtrLiteralExprClass");
1297 case Stmt::CXXPseudoDestructorExprClass:
1298 zig_panic("TODO handle C CXXPseudoDestructorExprClass");
1299 case Stmt::CXXScalarValueInitExprClass:
1300 zig_panic("TODO handle C CXXScalarValueInitExprClass");
1301 case Stmt::CXXStdInitializerListExprClass:
1302 zig_panic("TODO handle C CXXStdInitializerListExprClass");
1303 case Stmt::CXXThisExprClass:
1304 zig_panic("TODO handle C CXXThisExprClass");
1305 case Stmt::CXXThrowExprClass:
1306 zig_panic("TODO handle C CXXThrowExprClass");
1307 case Stmt::CXXTypeidExprClass:
1308 zig_panic("TODO handle C CXXTypeidExprClass");
1309 case Stmt::CXXUnresolvedConstructExprClass:
1310 zig_panic("TODO handle C CXXUnresolvedConstructExprClass");
1311 case Stmt::CXXUuidofExprClass:
1312 zig_panic("TODO handle C CXXUuidofExprClass");
1313 case Stmt::CallExprClass:
1314 zig_panic("TODO handle C CallExprClass");
1315 case Stmt::CUDAKernelCallExprClass:
1316 zig_panic("TODO handle C CUDAKernelCallExprClass");
1317 case Stmt::CXXMemberCallExprClass:
1318 zig_panic("TODO handle C CXXMemberCallExprClass");
1319 case Stmt::CXXOperatorCallExprClass:
1320 zig_panic("TODO handle C CXXOperatorCallExprClass");
1321 case Stmt::UserDefinedLiteralClass:
1322 zig_panic("TODO handle C UserDefinedLiteralClass");
1323 case Stmt::CStyleCastExprClass:
1324 zig_panic("TODO handle C CStyleCastExprClass");
1325 case Stmt::CXXFunctionalCastExprClass:
1326 zig_panic("TODO handle C CXXFunctionalCastExprClass");
1327 case Stmt::CXXConstCastExprClass:
1328 zig_panic("TODO handle C CXXConstCastExprClass");
1329 case Stmt::CXXDynamicCastExprClass:
1330 zig_panic("TODO handle C CXXDynamicCastExprClass");
1331 case Stmt::CXXReinterpretCastExprClass:
1332 zig_panic("TODO handle C CXXReinterpretCastExprClass");
1333 case Stmt::CXXStaticCastExprClass:
1334 zig_panic("TODO handle C CXXStaticCastExprClass");
1335 case Stmt::ObjCBridgedCastExprClass:
1336 zig_panic("TODO handle C ObjCBridgedCastExprClass");
1337 case Stmt::CharacterLiteralClass:
1338 zig_panic("TODO handle C CharacterLiteralClass");
1339 case Stmt::ChooseExprClass:
1340 zig_panic("TODO handle C ChooseExprClass");
1341 case Stmt::CompoundLiteralExprClass:
1342 zig_panic("TODO handle C CompoundLiteralExprClass");
1343 case Stmt::ConvertVectorExprClass:
1344 zig_panic("TODO handle C ConvertVectorExprClass");
1345 case Stmt::CoawaitExprClass:
1346 zig_panic("TODO handle C CoawaitExprClass");
1347 case Stmt::CoyieldExprClass:
1348 zig_panic("TODO handle C CoyieldExprClass");
1349 case Stmt::DependentCoawaitExprClass:
1350 zig_panic("TODO handle C DependentCoawaitExprClass");
1351 case Stmt::DependentScopeDeclRefExprClass:
1352 zig_panic("TODO handle C DependentScopeDeclRefExprClass");
1353 case Stmt::DesignatedInitExprClass:
1354 zig_panic("TODO handle C DesignatedInitExprClass");
1355 case Stmt::DesignatedInitUpdateExprClass:
1356 zig_panic("TODO handle C DesignatedInitUpdateExprClass");
1357 case Stmt::ExprWithCleanupsClass:
1358 zig_panic("TODO handle C ExprWithCleanupsClass");
1359 case Stmt::ExpressionTraitExprClass:
1360 zig_panic("TODO handle C ExpressionTraitExprClass");
1361 case Stmt::ExtVectorElementExprClass:
1362 zig_panic("TODO handle C ExtVectorElementExprClass");
1363 case Stmt::FloatingLiteralClass:
1364 zig_panic("TODO handle C FloatingLiteralClass");
1365 case Stmt::FunctionParmPackExprClass:
1366 zig_panic("TODO handle C FunctionParmPackExprClass");
1367 case Stmt::GNUNullExprClass:
1368 zig_panic("TODO handle C GNUNullExprClass");
1369 case Stmt::GenericSelectionExprClass:
1370 zig_panic("TODO handle C GenericSelectionExprClass");
1371 case Stmt::ImaginaryLiteralClass:
1372 zig_panic("TODO handle C ImaginaryLiteralClass");
1373 case Stmt::ImplicitValueInitExprClass:
1374 zig_panic("TODO handle C ImplicitValueInitExprClass");
1375 case Stmt::InitListExprClass:
1376 zig_panic("TODO handle C InitListExprClass");
1377 case Stmt::LambdaExprClass:
1378 zig_panic("TODO handle C LambdaExprClass");
1379 case Stmt::MSPropertyRefExprClass:
1380 zig_panic("TODO handle C MSPropertyRefExprClass");
1381 case Stmt::MSPropertySubscriptExprClass:
1382 zig_panic("TODO handle C MSPropertySubscriptExprClass");
1383 case Stmt::MaterializeTemporaryExprClass:
1384 zig_panic("TODO handle C MaterializeTemporaryExprClass");
1385 case Stmt::MemberExprClass:
1386 zig_panic("TODO handle C MemberExprClass");
1387 case Stmt::NoInitExprClass:
1388 zig_panic("TODO handle C NoInitExprClass");
1389 case Stmt::OMPArraySectionExprClass:
1390 zig_panic("TODO handle C OMPArraySectionExprClass");
1391 case Stmt::ObjCArrayLiteralClass:
1392 zig_panic("TODO handle C ObjCArrayLiteralClass");
1393 case Stmt::ObjCAvailabilityCheckExprClass:
1394 zig_panic("TODO handle C ObjCAvailabilityCheckExprClass");
1395 case Stmt::ObjCBoolLiteralExprClass:
1396 zig_panic("TODO handle C ObjCBoolLiteralExprClass");
1397 case Stmt::ObjCBoxedExprClass:
1398 zig_panic("TODO handle C ObjCBoxedExprClass");
1399 case Stmt::ObjCDictionaryLiteralClass:
1400 zig_panic("TODO handle C ObjCDictionaryLiteralClass");
1401 case Stmt::ObjCEncodeExprClass:
1402 zig_panic("TODO handle C ObjCEncodeExprClass");
1403 case Stmt::ObjCIndirectCopyRestoreExprClass:
1404 zig_panic("TODO handle C ObjCIndirectCopyRestoreExprClass");
1405 case Stmt::ObjCIsaExprClass:
1406 zig_panic("TODO handle C ObjCIsaExprClass");
1407 case Stmt::ObjCIvarRefExprClass:
1408 zig_panic("TODO handle C ObjCIvarRefExprClass");
1409 case Stmt::ObjCMessageExprClass:
1410 zig_panic("TODO handle C ObjCMessageExprClass");
1411 case Stmt::ObjCPropertyRefExprClass:
1412 zig_panic("TODO handle C ObjCPropertyRefExprClass");
1413 case Stmt::ObjCProtocolExprClass:
1414 zig_panic("TODO handle C ObjCProtocolExprClass");
1415 case Stmt::ObjCSelectorExprClass:
1416 zig_panic("TODO handle C ObjCSelectorExprClass");
1417 case Stmt::ObjCStringLiteralClass:
1418 zig_panic("TODO handle C ObjCStringLiteralClass");
1419 case Stmt::ObjCSubscriptRefExprClass:
1420 zig_panic("TODO handle C ObjCSubscriptRefExprClass");
1421 case Stmt::OffsetOfExprClass:
1422 zig_panic("TODO handle C OffsetOfExprClass");
1423 case Stmt::OpaqueValueExprClass:
1424 zig_panic("TODO handle C OpaqueValueExprClass");
1425 case Stmt::UnresolvedLookupExprClass:
1426 zig_panic("TODO handle C UnresolvedLookupExprClass");
1427 case Stmt::UnresolvedMemberExprClass:
1428 zig_panic("TODO handle C UnresolvedMemberExprClass");
1429 case Stmt::PackExpansionExprClass:
1430 zig_panic("TODO handle C PackExpansionExprClass");
1431 case Stmt::ParenExprClass:
1432 zig_panic("TODO handle C ParenExprClass");
1433 case Stmt::ParenListExprClass:
1434 zig_panic("TODO handle C ParenListExprClass");
1435 case Stmt::PredefinedExprClass:
1436 zig_panic("TODO handle C PredefinedExprClass");
1437 case Stmt::PseudoObjectExprClass:
1438 zig_panic("TODO handle C PseudoObjectExprClass");
1439 case Stmt::ShuffleVectorExprClass:
1440 zig_panic("TODO handle C ShuffleVectorExprClass");
1441 case Stmt::SizeOfPackExprClass:
1442 zig_panic("TODO handle C SizeOfPackExprClass");
1443 case Stmt::StmtExprClass:
1444 zig_panic("TODO handle C StmtExprClass");
1445 case Stmt::StringLiteralClass:
1446 zig_panic("TODO handle C StringLiteralClass");
1447 case Stmt::SubstNonTypeTemplateParmExprClass:
1448 zig_panic("TODO handle C SubstNonTypeTemplateParmExprClass");
1449 case Stmt::SubstNonTypeTemplateParmPackExprClass:
1450 zig_panic("TODO handle C SubstNonTypeTemplateParmPackExprClass");
1451 case Stmt::TypeTraitExprClass:
1452 zig_panic("TODO handle C TypeTraitExprClass");
1453 case Stmt::TypoExprClass:
1454 zig_panic("TODO handle C TypoExprClass");
1455 case Stmt::UnaryExprOrTypeTraitExprClass:
1456 zig_panic("TODO handle C UnaryExprOrTypeTraitExprClass");
1457 case Stmt::VAArgExprClass:
1458 zig_panic("TODO handle C VAArgExprClass");
1459 case Stmt::ForStmtClass:
1460 zig_panic("TODO handle C ForStmtClass");
1461 case Stmt::GotoStmtClass:
1462 zig_panic("TODO handle C GotoStmtClass");
1463 case Stmt::IfStmtClass:
1464 zig_panic("TODO handle C IfStmtClass");
1465 case Stmt::IndirectGotoStmtClass:
1466 zig_panic("TODO handle C IndirectGotoStmtClass");
1467 case Stmt::LabelStmtClass:
1468 zig_panic("TODO handle C LabelStmtClass");
1469 case Stmt::MSDependentExistsStmtClass:
1470 zig_panic("TODO handle C MSDependentExistsStmtClass");
1471 case Stmt::NullStmtClass:
1472 zig_panic("TODO handle C NullStmtClass");
1473 case Stmt::OMPAtomicDirectiveClass:
1474 zig_panic("TODO handle C OMPAtomicDirectiveClass");
1475 case Stmt::OMPBarrierDirectiveClass:
1476 zig_panic("TODO handle C OMPBarrierDirectiveClass");
1477 case Stmt::OMPCancelDirectiveClass:
1478 zig_panic("TODO handle C OMPCancelDirectiveClass");
1479 case Stmt::OMPCancellationPointDirectiveClass:
1480 zig_panic("TODO handle C OMPCancellationPointDirectiveClass");
1481 case Stmt::OMPCriticalDirectiveClass:
1482 zig_panic("TODO handle C OMPCriticalDirectiveClass");
1483 case Stmt::OMPFlushDirectiveClass:
1484 zig_panic("TODO handle C OMPFlushDirectiveClass");
1485 case Stmt::OMPDistributeDirectiveClass:
1486 zig_panic("TODO handle C OMPDistributeDirectiveClass");
1487 case Stmt::OMPDistributeParallelForDirectiveClass:
1488 zig_panic("TODO handle C OMPDistributeParallelForDirectiveClass");
1489 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1490 zig_panic("TODO handle C OMPDistributeParallelForSimdDirectiveClass");
1491 case Stmt::OMPDistributeSimdDirectiveClass:
1492 zig_panic("TODO handle C OMPDistributeSimdDirectiveClass");
1493 case Stmt::OMPForDirectiveClass:
1494 zig_panic("TODO handle C OMPForDirectiveClass");
1495 case Stmt::OMPForSimdDirectiveClass:
1496 zig_panic("TODO handle C OMPForSimdDirectiveClass");
1497 case Stmt::OMPParallelForDirectiveClass:
1498 zig_panic("TODO handle C OMPParallelForDirectiveClass");
1499 case Stmt::OMPParallelForSimdDirectiveClass:
1500 zig_panic("TODO handle C OMPParallelForSimdDirectiveClass");
1501 case Stmt::OMPSimdDirectiveClass:
1502 zig_panic("TODO handle C OMPSimdDirectiveClass");
1503 case Stmt::OMPTargetParallelForSimdDirectiveClass:
1504 zig_panic("TODO handle C OMPTargetParallelForSimdDirectiveClass");
1505 case Stmt::OMPTargetSimdDirectiveClass:
1506 zig_panic("TODO handle C OMPTargetSimdDirectiveClass");
1507 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1508 zig_panic("TODO handle C OMPTargetTeamsDistributeDirectiveClass");
1509 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1510 zig_panic("TODO handle C OMPTargetTeamsDistributeParallelForDirectiveClass");
1511 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1512 zig_panic("TODO handle C OMPTargetTeamsDistributeParallelForSimdDirectiveClass");
1513 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1514 zig_panic("TODO handle C OMPTargetTeamsDistributeSimdDirectiveClass");
1515 case Stmt::OMPTaskLoopDirectiveClass:
1516 zig_panic("TODO handle C OMPTaskLoopDirectiveClass");
1517 case Stmt::OMPTaskLoopSimdDirectiveClass:
1518 zig_panic("TODO handle C OMPTaskLoopSimdDirectiveClass");
1519 case Stmt::OMPTeamsDistributeDirectiveClass:
1520 zig_panic("TODO handle C OMPTeamsDistributeDirectiveClass");
1521 case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1522 zig_panic("TODO handle C OMPTeamsDistributeParallelForDirectiveClass");
1523 case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1524 zig_panic("TODO handle C OMPTeamsDistributeParallelForSimdDirectiveClass");
1525 case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1526 zig_panic("TODO handle C OMPTeamsDistributeSimdDirectiveClass");
1527 case Stmt::OMPMasterDirectiveClass:
1528 zig_panic("TODO handle C OMPMasterDirectiveClass");
1529 case Stmt::OMPOrderedDirectiveClass:
1530 zig_panic("TODO handle C OMPOrderedDirectiveClass");
1531 case Stmt::OMPParallelDirectiveClass:
1532 zig_panic("TODO handle C OMPParallelDirectiveClass");
1533 case Stmt::OMPParallelSectionsDirectiveClass:
1534 zig_panic("TODO handle C OMPParallelSectionsDirectiveClass");
1535 case Stmt::OMPSectionDirectiveClass:
1536 zig_panic("TODO handle C OMPSectionDirectiveClass");
1537 case Stmt::OMPSectionsDirectiveClass:
1538 zig_panic("TODO handle C OMPSectionsDirectiveClass");
1539 case Stmt::OMPSingleDirectiveClass:
1540 zig_panic("TODO handle C OMPSingleDirectiveClass");
1541 case Stmt::OMPTargetDataDirectiveClass:
1542 zig_panic("TODO handle C OMPTargetDataDirectiveClass");
1543 case Stmt::OMPTargetDirectiveClass:
1544 zig_panic("TODO handle C OMPTargetDirectiveClass");
1545 case Stmt::OMPTargetEnterDataDirectiveClass:
1546 zig_panic("TODO handle C OMPTargetEnterDataDirectiveClass");
1547 case Stmt::OMPTargetExitDataDirectiveClass:
1548 zig_panic("TODO handle C OMPTargetExitDataDirectiveClass");
1549 case Stmt::OMPTargetParallelDirectiveClass:
1550 zig_panic("TODO handle C OMPTargetParallelDirectiveClass");
1551 case Stmt::OMPTargetParallelForDirectiveClass:
1552 zig_panic("TODO handle C OMPTargetParallelForDirectiveClass");
1553 case Stmt::OMPTargetTeamsDirectiveClass:
1554 zig_panic("TODO handle C OMPTargetTeamsDirectiveClass");
1555 case Stmt::OMPTargetUpdateDirectiveClass:
1556 zig_panic("TODO handle C OMPTargetUpdateDirectiveClass");
1557 case Stmt::OMPTaskDirectiveClass:
1558 zig_panic("TODO handle C OMPTaskDirectiveClass");
1559 case Stmt::OMPTaskgroupDirectiveClass:
1560 zig_panic("TODO handle C OMPTaskgroupDirectiveClass");
1561 case Stmt::OMPTaskwaitDirectiveClass:
1562 zig_panic("TODO handle C OMPTaskwaitDirectiveClass");
1563 case Stmt::OMPTaskyieldDirectiveClass:
1564 zig_panic("TODO handle C OMPTaskyieldDirectiveClass");
1565 case Stmt::OMPTeamsDirectiveClass:
1566 zig_panic("TODO handle C OMPTeamsDirectiveClass");
1567 case Stmt::ObjCAtCatchStmtClass:
1568 zig_panic("TODO handle C ObjCAtCatchStmtClass");
1569 case Stmt::ObjCAtFinallyStmtClass:
1570 zig_panic("TODO handle C ObjCAtFinallyStmtClass");
1571 case Stmt::ObjCAtSynchronizedStmtClass:
1572 zig_panic("TODO handle C ObjCAtSynchronizedStmtClass");
1573 case Stmt::ObjCAtThrowStmtClass:
1574 zig_panic("TODO handle C ObjCAtThrowStmtClass");
1575 case Stmt::ObjCAtTryStmtClass:
1576 zig_panic("TODO handle C ObjCAtTryStmtClass");
1577 case Stmt::ObjCAutoreleasePoolStmtClass:
1578 zig_panic("TODO handle C ObjCAutoreleasePoolStmtClass");
1579 case Stmt::ObjCForCollectionStmtClass:
1580 zig_panic("TODO handle C ObjCForCollectionStmtClass");
1581 case Stmt::SEHExceptStmtClass:
1582 zig_panic("TODO handle C SEHExceptStmtClass");
1583 case Stmt::SEHFinallyStmtClass:
1584 zig_panic("TODO handle C SEHFinallyStmtClass");
1585 case Stmt::SEHLeaveStmtClass:
1586 zig_panic("TODO handle C SEHLeaveStmtClass");
1587 case Stmt::SEHTryStmtClass:
1588 zig_panic("TODO handle C SEHTryStmtClass");
1589 }
1590 zig_unreachable();
6031591}
6041592
6051593static void visit_fn_decl(Context *c, const FunctionDecl *fn_decl) {
......@@ -610,112 +1598,146 @@ static void visit_fn_decl(Context *c, const FunctionDecl *fn_decl) {
6101598 return;
6111599 }
6121600
613 TypeTableEntry *fn_type = resolve_qual_type(c, fn_decl->getType(), fn_decl);
614
615 if (fn_type->id == TypeTableEntryIdInvalid) {
616 emit_warning(c, fn_decl, "ignoring function '%s' - unable to resolve type", buf_ptr(fn_name));
1601 AstNode *proto_node = trans_qual_type(c, fn_decl->getType(), fn_decl->getLocation());
1602 if (proto_node == nullptr) {
1603 emit_warning(c, fn_decl->getLocation(), "unable to resolve prototype of function '%s'", buf_ptr(fn_name));
6171604 return;
6181605 }
619 assert(fn_type->id == TypeTableEntryIdFn);
6201606
621 FnTableEntry *fn_entry = create_fn_raw(FnInlineAuto, GlobalLinkageIdStrong);
622 buf_init_from_buf(&fn_entry->symbol_name, fn_name);
623 fn_entry->type_entry = fn_type;
1607 proto_node->data.fn_proto.name = fn_name;
1608 proto_node->data.fn_proto.is_extern = !fn_decl->hasBody();
6241609
625 assert(fn_type->data.fn.fn_type_id.cc != CallingConventionNaked);
1610 StorageClass sc = fn_decl->getStorageClass();
1611 if (sc == SC_None) {
1612 proto_node->data.fn_proto.visib_mod = fn_decl->hasBody() ? VisibModExport : c->visib_mod;
1613 } else if (sc == SC_Extern || sc == SC_Static) {
1614 proto_node->data.fn_proto.visib_mod = c->visib_mod;
1615 } else if (sc == SC_PrivateExtern) {
1616 emit_warning(c, fn_decl->getLocation(), "unsupported storage class: private extern");
1617 return;
1618 } else {
1619 emit_warning(c, fn_decl->getLocation(), "unsupported storage class: unknown");
1620 return;
1621 }
6261622
627 size_t arg_count = fn_type->data.fn.fn_type_id.param_count;
628 fn_entry->param_names = allocate<Buf *>(arg_count);
629 Buf *name_buf;
630 for (size_t i = 0; i < arg_count; i += 1) {
1623 for (size_t i = 0; i < proto_node->data.fn_proto.params.length; i += 1) {
1624 AstNode *param_node = proto_node->data.fn_proto.params.at(i);
6311625 const ParmVarDecl *param = fn_decl->getParamDecl(i);
6321626 const char *name = decl_name(param);
6331627 if (strlen(name) == 0) {
634 name_buf = buf_sprintf("arg%" ZIG_PRI_usize "", i);
1628 Buf *proto_param_name = param_node->data.param_decl.name;
1629 if (proto_param_name == nullptr) {
1630 param_node->data.param_decl.name = buf_sprintf("arg%" ZIG_PRI_usize "", i);
1631 } else {
1632 param_node->data.param_decl.name = proto_param_name;
1633 }
6351634 } else {
636 name_buf = buf_create_from_str(name);
1635 param_node->data.param_decl.name = buf_create_from_str(name);
6371636 }
638 fn_entry->param_names[i] = name_buf;
6391637 }
6401638
641 TldFn *tld_fn = allocate<TldFn>(1);
642 parseh_init_tld(c, &tld_fn->base, TldIdFn, fn_name);
643 tld_fn->fn_entry = fn_entry;
644 add_global(c, &tld_fn->base);
1639 if (fn_decl->hasBody()) {
1640 Stmt *body = fn_decl->getBody();
1641
1642 AstNode *fn_def_node = trans_create_node(c, NodeTypeFnDef);
1643 fn_def_node->data.fn_def.fn_proto = proto_node;
1644 fn_def_node->data.fn_def.body = trans_stmt(c, nullptr, body);
6451645
646 c->codegen->fn_protos.append(fn_entry);
1646 proto_node->data.fn_proto.fn_def_node = fn_def_node;
1647 c->root->data.root.top_level_decls.append(fn_def_node);
1648 return;
1649 }
1650
1651 c->root->data.root.top_level_decls.append(proto_node);
1652}
1653
1654static AstNode *resolve_typdef_as_builtin(Context *c, const TypedefNameDecl *typedef_decl, const char *primitive_name) {
1655 AstNode *node = trans_create_node_symbol_str(c, primitive_name);
1656 c->decl_table.put(typedef_decl, node);
1657 return node;
6471658}
6481659
649static void visit_typedef_decl(Context *c, const TypedefNameDecl *typedef_decl) {
1660static AstNode *resolve_typedef_decl(Context *c, const TypedefNameDecl *typedef_decl) {
1661 auto existing_entry = c->decl_table.maybe_get((void*)typedef_decl);
1662 if (existing_entry) {
1663 return existing_entry->value;
1664 }
1665
6501666 QualType child_qt = typedef_decl->getUnderlyingType();
6511667 Buf *type_name = buf_create_from_str(decl_name(typedef_decl));
6521668
653 if (buf_eql_str(type_name, "uint8_t") ||
654 buf_eql_str(type_name, "int8_t") ||
655 buf_eql_str(type_name, "uint16_t") ||
656 buf_eql_str(type_name, "int16_t") ||
657 buf_eql_str(type_name, "uint32_t") ||
658 buf_eql_str(type_name, "int32_t") ||
659 buf_eql_str(type_name, "uint64_t") ||
660 buf_eql_str(type_name, "int64_t") ||
661 buf_eql_str(type_name, "intptr_t") ||
662 buf_eql_str(type_name, "uintptr_t"))
663 {
664 // special case we can just use the builtin types
665 return;
1669 if (buf_eql_str(type_name, "uint8_t")) {
1670 return resolve_typdef_as_builtin(c, typedef_decl, "u8");
1671 } else if (buf_eql_str(type_name, "int8_t")) {
1672 return resolve_typdef_as_builtin(c, typedef_decl, "i8");
1673 } else if (buf_eql_str(type_name, "uint16_t")) {
1674 return resolve_typdef_as_builtin(c, typedef_decl, "u16");
1675 } else if (buf_eql_str(type_name, "int16_t")) {
1676 return resolve_typdef_as_builtin(c, typedef_decl, "i16");
1677 } else if (buf_eql_str(type_name, "uint32_t")) {
1678 return resolve_typdef_as_builtin(c, typedef_decl, "u32");
1679 } else if (buf_eql_str(type_name, "int32_t")) {
1680 return resolve_typdef_as_builtin(c, typedef_decl, "i32");
1681 } else if (buf_eql_str(type_name, "uint64_t")) {
1682 return resolve_typdef_as_builtin(c, typedef_decl, "u64");
1683 } else if (buf_eql_str(type_name, "int64_t")) {
1684 return resolve_typdef_as_builtin(c, typedef_decl, "i64");
1685 } else if (buf_eql_str(type_name, "intptr_t")) {
1686 return resolve_typdef_as_builtin(c, typedef_decl, "isize");
1687 } else if (buf_eql_str(type_name, "uintptr_t")) {
1688 return resolve_typdef_as_builtin(c, typedef_decl, "usize");
1689 } else if (buf_eql_str(type_name, "ssize_t")) {
1690 return resolve_typdef_as_builtin(c, typedef_decl, "isize");
1691 } else if (buf_eql_str(type_name, "size_t")) {
1692 return resolve_typdef_as_builtin(c, typedef_decl, "usize");
6661693 }
6671694
6681695 // if the underlying type is anonymous, we can special case it to just
6691696 // use the name of this typedef
6701697 // TODO
6711698
672 TypeTableEntry *child_type = resolve_qual_type(c, child_qt, typedef_decl);
673 if (child_type->id == TypeTableEntryIdInvalid) {
674 emit_warning(c, typedef_decl, "typedef %s - unresolved child type", buf_ptr(type_name));
675 return;
1699 AstNode *type_node = trans_qual_type(c, child_qt, typedef_decl->getLocation());
1700 if (type_node == nullptr) {
1701 emit_warning(c, typedef_decl->getLocation(), "typedef %s - unresolved child type", buf_ptr(type_name));
1702 c->decl_table.put(typedef_decl, nullptr);
1703 return nullptr;
6761704 }
677 add_const_type(c, type_name, child_type);
678}
1705 add_global_var(c, type_name, type_node);
6791706
680static void replace_with_fwd_decl(Context *c, TypeTableEntry *struct_type, Buf *full_type_name) {
681 unsigned line = c->source_node ? c->source_node->line : 0;
682 ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugForwardDeclType(c->codegen->dbuilder,
683 ZigLLVMTag_DW_structure_type(), buf_ptr(full_type_name),
684 ZigLLVMFileToScope(c->import->di_file), c->import->di_file, line);
1707 AstNode *symbol_node = trans_create_node_symbol(c, type_name);
1708 c->decl_table.put(typedef_decl, symbol_node);
1709 return symbol_node;
1710}
6851711
686 ZigLLVMReplaceTemporary(c->codegen->dbuilder, struct_type->di_type, replacement_di_type);
687 struct_type->di_type = replacement_di_type;
688 struct_type->id = TypeTableEntryIdOpaque;
1712struct AstNode *demote_enum_to_opaque(Context *c, const EnumDecl *enum_decl,
1713 Buf *full_type_name, Buf *bare_name)
1714{
1715 AstNode *opaque_node = trans_create_node_opaque(c);
1716 if (full_type_name == nullptr) {
1717 c->decl_table.put(enum_decl->getCanonicalDecl(), opaque_node);
1718 return opaque_node;
1719 }
1720 AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);
1721 add_global_weak_alias(c, bare_name, full_type_name);
1722 add_global_var(c, full_type_name, opaque_node);
1723 c->decl_table.put(enum_decl->getCanonicalDecl(), symbol_node);
1724 return symbol_node;
6891725}
6901726
691static TypeTableEntry *resolve_enum_decl(Context *c, const EnumDecl *enum_decl) {
692 auto existing_entry = c->decl_table.maybe_get((void*)enum_decl);
1727static AstNode *resolve_enum_decl(Context *c, const EnumDecl *enum_decl) {
1728 auto existing_entry = c->decl_table.maybe_get((void*)enum_decl->getCanonicalDecl());
6931729 if (existing_entry) {
6941730 return existing_entry->value;
6951731 }
6961732
6971733 const char *raw_name = decl_name(enum_decl);
698
699 Buf *bare_name;
700 if (raw_name[0] == 0) {
701 bare_name = buf_sprintf("anon_$%" PRIu32, get_next_anon_index(c));
702 } else {
703 bare_name = buf_create_from_str(raw_name);
704 }
705
706 Buf *full_type_name = buf_sprintf("enum_%s", buf_ptr(bare_name));
1734 bool is_anonymous = (raw_name[0] == 0);
1735 Buf *bare_name = is_anonymous ? nullptr : buf_create_from_str(raw_name);
1736 Buf *full_type_name = is_anonymous ? nullptr : buf_sprintf("enum_%s", buf_ptr(bare_name));
7071737
7081738 const EnumDecl *enum_def = enum_decl->getDefinition();
7091739 if (!enum_def) {
710 TypeTableEntry *enum_type = get_partial_container_type(c->codegen, &c->import->decls_scope->base,
711 ContainerKindEnum, c->source_node, buf_ptr(full_type_name), ContainerLayoutExtern);
712 enum_type->data.enumeration.zero_bits_known = true;
713 enum_type->data.enumeration.abi_alignment = 1;
714 c->enum_type_table.put(bare_name, enum_type);
715 c->decl_table.put(enum_decl, enum_type);
716 replace_with_fwd_decl(c, enum_type, full_type_name);
717
718 return enum_type;
1740 return demote_enum_to_opaque(c, enum_decl, full_type_name, bare_name);
7191741 }
7201742
7211743 bool pure_enum = true;
......@@ -730,25 +1752,16 @@ static TypeTableEntry *resolve_enum_decl(Context *c, const EnumDecl *enum_decl)
7301752 }
7311753 }
7321754
733 TypeTableEntry *tag_int_type = resolve_qual_type(c, enum_decl->getIntegerType(), enum_decl);
1755 AstNode *tag_int_type = trans_qual_type(c, enum_decl->getIntegerType(), enum_decl->getLocation());
1756 assert(tag_int_type);
7341757
7351758 if (pure_enum) {
736 TypeTableEntry *enum_type = get_partial_container_type(c->codegen, &c->import->decls_scope->base,
737 ContainerKindEnum, c->source_node, buf_ptr(full_type_name), ContainerLayoutExtern);
738 TypeTableEntry *tag_type_entry = create_enum_tag_type(c->codegen, enum_type, tag_int_type);
739 c->enum_type_table.put(bare_name, enum_type);
740 c->decl_table.put(enum_decl, enum_type);
741
742 enum_type->data.enumeration.gen_field_count = 0;
743 enum_type->data.enumeration.complete = true;
744 enum_type->data.enumeration.zero_bits_known = true;
745 enum_type->data.enumeration.abi_alignment = 1;
746 enum_type->data.enumeration.tag_type = tag_type_entry;
747
748 enum_type->data.enumeration.src_field_count = field_count;
749 enum_type->data.enumeration.fields = allocate<TypeEnumField>(field_count);
750 ZigLLVMDIEnumerator **di_enumerators = allocate<ZigLLVMDIEnumerator*>(field_count);
1759 AstNode *enum_node = trans_create_node(c, NodeTypeContainerDecl);
1760 enum_node->data.container_decl.kind = ContainerKindEnum;
1761 enum_node->data.container_decl.layout = ContainerLayoutExtern;
1762 enum_node->data.container_decl.init_arg_expr = tag_int_type;
7511763
1764 enum_node->data.container_decl.fields.resize(field_count);
7521765 uint32_t i = 0;
7531766 for (auto it = enum_def->enumerator_begin(),
7541767 it_end = enum_def->enumerator_end();
......@@ -758,93 +1771,82 @@ static TypeTableEntry *resolve_enum_decl(Context *c, const EnumDecl *enum_decl)
7581771
7591772 Buf *enum_val_name = buf_create_from_str(decl_name(enum_const));
7601773 Buf *field_name;
761 if (buf_starts_with_buf(enum_val_name, bare_name)) {
1774 if (bare_name != nullptr && buf_starts_with_buf(enum_val_name, bare_name)) {
7621775 field_name = buf_slice(enum_val_name, buf_len(bare_name), buf_len(enum_val_name));
7631776 } else {
7641777 field_name = enum_val_name;
7651778 }
7661779
767 TypeEnumField *type_enum_field = &enum_type->data.enumeration.fields[i];
768 type_enum_field->name = field_name;
769 type_enum_field->type_entry = c->codegen->builtin_types.entry_void;
770 type_enum_field->value = i;
771
772 di_enumerators[i] = ZigLLVMCreateDebugEnumerator(c->codegen->dbuilder, buf_ptr(type_enum_field->name), i);
773
1780 AstNode *field_node = trans_create_node(c, NodeTypeStructField);
1781 field_node->data.struct_field.name = field_name;
1782 field_node->data.struct_field.type = nullptr;
1783 enum_node->data.container_decl.fields.items[i] = field_node;
7741784
7751785 // in C each enum value is in the global namespace. so we put them there too.
7761786 // at this point we can rely on the enum emitting successfully
777 add_global(c, create_global_num_lit_unsigned_negative(c, enum_val_name, i, false));
1787 AstNode *field_access_node = trans_create_node_field_access(c,
1788 trans_create_node_symbol(c, full_type_name), field_name);
1789 add_global_var(c, enum_val_name, field_access_node);
7781790 }
7791791
780 // create llvm type for root struct
781 enum_type->type_ref = tag_type_entry->type_ref;
782
783 enum_type->data.enumeration.abi_alignment = LLVMABIAlignmentOfType(c->codegen->target_data_ref,
784 enum_type->type_ref);
785
786 // create debug type for tag
787 unsigned line = c->source_node ? (c->source_node->line + 1) : 0;
788 uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(c->codegen->target_data_ref, enum_type->type_ref);
789 uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(c->codegen->target_data_ref, enum_type->type_ref);
790 ZigLLVMDIType *tag_di_type = ZigLLVMCreateDebugEnumerationType(c->codegen->dbuilder,
791 ZigLLVMFileToScope(c->import->di_file), buf_ptr(bare_name),
792 c->import->di_file, line,
793 debug_size_in_bits,
794 debug_align_in_bits,
795 di_enumerators, field_count, tag_type_entry->di_type, "");
796
797 ZigLLVMReplaceTemporary(c->codegen->dbuilder, enum_type->di_type, tag_di_type);
798 enum_type->di_type = tag_di_type;
799
800 return enum_type;
801 } else {
802 // TODO after issue #305 is solved, make this be an enum with tag_int_type
803 // as the integer type and set the custom enum values
804 TypeTableEntry *enum_type = tag_int_type;
805 c->enum_type_table.put(bare_name, enum_type);
806 c->decl_table.put(enum_decl, enum_type);
1792 if (is_anonymous) {
1793 c->decl_table.put(enum_decl->getCanonicalDecl(), enum_node);
1794 return enum_node;
1795 } else {
1796 AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);
1797 add_global_weak_alias(c, bare_name, full_type_name);
1798 add_global_var(c, full_type_name, enum_node);
1799 c->decl_table.put(enum_decl->getCanonicalDecl(), symbol_node);
1800 return enum_node;
1801 }
1802 }
8071803
808 // add variables for all the values with enum_type
809 for (auto it = enum_def->enumerator_begin(),
810 it_end = enum_def->enumerator_end();
811 it != it_end; ++it)
812 {
813 const EnumConstantDecl *enum_const = *it;
1804 // TODO after issue #305 is solved, make this be an enum with tag_int_type
1805 // as the integer type and set the custom enum values
1806 AstNode *enum_node = tag_int_type;
8141807
815 Buf *enum_val_name = buf_create_from_str(decl_name(enum_const));
8161808
817 Tld *tld = create_global_num_lit_ap(c, enum_decl, enum_val_name, enum_const->getInitVal());
818 if (!tld)
819 return c->codegen->builtin_types.entry_invalid;
1809 // add variables for all the values with enum_node
1810 for (auto it = enum_def->enumerator_begin(),
1811 it_end = enum_def->enumerator_end();
1812 it != it_end; ++it)
1813 {
1814 const EnumConstantDecl *enum_const = *it;
8201815
821 add_global(c, tld);
822 }
1816 Buf *enum_val_name = buf_create_from_str(decl_name(enum_const));
1817 AstNode *int_node = trans_create_node_apint(c, enum_const->getInitVal());
1818 AstNode *var_node = add_global_var(c, enum_val_name, int_node);
1819 var_node->data.variable_declaration.type = tag_int_type;
1820 }
8231821
824 return enum_type;
1822 if (is_anonymous) {
1823 c->decl_table.put(enum_decl->getCanonicalDecl(), enum_node);
1824 return enum_node;
1825 } else {
1826 AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);
1827 add_global_weak_alias(c, bare_name, full_type_name);
1828 add_global_var(c, full_type_name, enum_node);
1829 return symbol_node;
8251830 }
8261831}
8271832
828static void visit_enum_decl(Context *c, const EnumDecl *enum_decl) {
829 TypeTableEntry *enum_type = resolve_enum_decl(c, enum_decl);
830
831 if (enum_type->id == TypeTableEntryIdInvalid)
832 return;
833
834 // make an alias without the "enum_" prefix. this will get emitted at the
835 // end if it doesn't conflict with anything else
836 bool is_anonymous = (decl_name(enum_decl)[0] == 0);
837 if (is_anonymous)
838 return;
839
840 Buf *bare_name = buf_create_from_str(decl_name(enum_decl));
841
842 Tld *tld = add_container_tld(c, enum_type);
843 add_global_weak_alias(c, bare_name, tld);
1833static AstNode *demote_struct_to_opaque(Context *c, const RecordDecl *record_decl,
1834 Buf *full_type_name, Buf *bare_name)
1835{
1836 AstNode *opaque_node = trans_create_node_opaque(c);
1837 if (full_type_name == nullptr) {
1838 c->decl_table.put(record_decl->getCanonicalDecl(), opaque_node);
1839 return opaque_node;
1840 }
1841 AstNode *symbol_node = trans_create_node_symbol(c, full_type_name);
1842 add_global_weak_alias(c, bare_name, full_type_name);
1843 add_global_var(c, full_type_name, opaque_node);
1844 c->decl_table.put(record_decl->getCanonicalDecl(), symbol_node);
1845 return symbol_node;
8441846}
8451847
846static TypeTableEntry *resolve_record_decl(Context *c, const RecordDecl *record_decl) {
847 auto existing_entry = c->decl_table.maybe_get((void*)record_decl);
1848static AstNode *resolve_record_decl(Context *c, const RecordDecl *record_decl) {
1849 auto existing_entry = c->decl_table.maybe_get((void*)record_decl->getCanonicalDecl());
8481850 if (existing_entry) {
8491851 return existing_entry->value;
8501852 }
......@@ -852,36 +1854,20 @@ static TypeTableEntry *resolve_record_decl(Context *c, const RecordDecl *record_
8521854 const char *raw_name = decl_name(record_decl);
8531855
8541856 if (!record_decl->isStruct()) {
855 emit_warning(c, record_decl, "skipping record %s, not a struct", raw_name);
856 return c->codegen->builtin_types.entry_invalid;
857 }
858
859 Buf *bare_name;
860 if (record_decl->isAnonymousStructOrUnion() || raw_name[0] == 0) {
861 bare_name = buf_sprintf("anon_$%" PRIu32, get_next_anon_index(c));
862 } else {
863 bare_name = buf_create_from_str(raw_name);
1857 emit_warning(c, record_decl->getLocation(), "skipping record %s, not a struct", raw_name);
1858 c->decl_table.put(record_decl->getCanonicalDecl(), nullptr);
1859 return nullptr;
8641860 }
8651861
866 Buf *full_type_name = buf_sprintf("struct_%s", buf_ptr(bare_name));
867
868
869 TypeTableEntry *struct_type = get_partial_container_type(c->codegen, &c->import->decls_scope->base,
870 ContainerKindStruct, c->source_node, buf_ptr(full_type_name), ContainerLayoutExtern);
871 struct_type->data.structure.zero_bits_known = true;
872 struct_type->data.structure.abi_alignment = 1;
873
874 c->struct_type_table.put(bare_name, struct_type);
875 c->decl_table.put(record_decl, struct_type);
1862 bool is_anonymous = record_decl->isAnonymousStructOrUnion() || raw_name[0] == 0;
1863 Buf *bare_name = is_anonymous ? nullptr : buf_create_from_str(raw_name);
1864 Buf *full_type_name = (bare_name == nullptr) ? nullptr : buf_sprintf("struct_%s", buf_ptr(bare_name));
8761865
8771866 RecordDecl *record_def = record_decl->getDefinition();
878 unsigned line = c->source_node ? c->source_node->line : 0;
879 if (!record_def) {
880 replace_with_fwd_decl(c, struct_type, full_type_name);
881 return struct_type;
1867 if (record_def == nullptr) {
1868 return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);
8821869 }
8831870
884
8851871 // count fields and validate
8861872 uint32_t field_count = 0;
8871873 for (auto it = record_def->field_begin(),
......@@ -891,105 +1877,56 @@ static TypeTableEntry *resolve_record_decl(Context *c, const RecordDecl *record_
8911877 const FieldDecl *field_decl = *it;
8921878
8931879 if (field_decl->isBitField()) {
894 emit_warning(c, field_decl, "struct %s demoted to opaque type - has bitfield\n", buf_ptr(bare_name));
895 replace_with_fwd_decl(c, struct_type, full_type_name);
896 return struct_type;
1880 emit_warning(c, field_decl->getLocation(), "struct %s demoted to opaque type - has bitfield",
1881 is_anonymous ? "(anon)" : buf_ptr(bare_name));
1882 return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);
8971883 }
8981884 }
8991885
900 struct_type->data.structure.src_field_count = field_count;
901 struct_type->data.structure.fields = allocate<TypeStructField>(field_count);
902 LLVMTypeRef *element_types = allocate<LLVMTypeRef>(field_count);
903 ZigLLVMDIType **di_element_types = allocate<ZigLLVMDIType*>(field_count);
1886 AstNode *struct_node = trans_create_node(c, NodeTypeContainerDecl);
1887 struct_node->data.container_decl.kind = ContainerKindStruct;
1888 struct_node->data.container_decl.layout = ContainerLayoutExtern;
9041889
905 // next, populate element_types as its needed for LLVMStructSetBody which is needed for LLVMOffsetOfElement
906 uint32_t i = 0;
907 for (auto it = record_def->field_begin(),
908 it_end = record_def->field_end();
909 it != it_end; ++it, i += 1)
910 {
911 const FieldDecl *field_decl = *it;
1890 // TODO handle attribute packed
9121891
913 TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
914 type_struct_field->name = buf_create_from_str(decl_name(field_decl));
915 type_struct_field->src_index = i;
916 type_struct_field->gen_index = i;
917 TypeTableEntry *field_type = resolve_qual_type(c, field_decl->getType(), field_decl);
918 type_struct_field->type_entry = field_type;
919
920 if (type_is_invalid(field_type) || !type_is_complete(field_type)) {
921 emit_warning(c, field_decl, "struct %s demoted to opaque type - unresolved type\n", buf_ptr(bare_name));
922 replace_with_fwd_decl(c, struct_type, full_type_name);
923 return struct_type;
924 }
1892 struct_node->data.container_decl.fields.resize(field_count);
9251893
926 element_types[i] = field_type->type_ref;
927 assert(element_types[i]);
1894 // must be before fields in case a circular reference happens
1895 if (is_anonymous) {
1896 c->decl_table.put(record_decl->getCanonicalDecl(), struct_node);
1897 } else {
1898 c->decl_table.put(record_decl->getCanonicalDecl(), trans_create_node_symbol(c, full_type_name));
9281899 }
9291900
930 LLVMStructSetBody(struct_type->type_ref, element_types, field_count, false);
931
932 // finally populate debug info
933 i = 0;
1901 uint32_t i = 0;
9341902 for (auto it = record_def->field_begin(),
9351903 it_end = record_def->field_end();
9361904 it != it_end; ++it, i += 1)
9371905 {
938 TypeStructField *type_struct_field = &struct_type->data.structure.fields[i];
939 TypeTableEntry *field_type = type_struct_field->type_entry;
940
941 uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(c->codegen->target_data_ref, field_type->type_ref);
942 uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(c->codegen->target_data_ref, field_type->type_ref);
943 uint64_t debug_offset_in_bits = 8*LLVMOffsetOfElement(c->codegen->target_data_ref, struct_type->type_ref, i);
944 di_element_types[i] = ZigLLVMCreateDebugMemberType(c->codegen->dbuilder,
945 ZigLLVMTypeToScope(struct_type->di_type), buf_ptr(type_struct_field->name),
946 c->import->di_file, line + 1,
947 debug_size_in_bits,
948 debug_align_in_bits,
949 debug_offset_in_bits,
950 0, field_type->di_type);
951
952 assert(di_element_types[i]);
1906 const FieldDecl *field_decl = *it;
9531907
954 }
955 struct_type->data.structure.embedded_in_current = false;
956
957 struct_type->data.structure.gen_field_count = field_count;
958 struct_type->data.structure.complete = true;
959 struct_type->data.structure.abi_alignment = LLVMABIAlignmentOfType(c->codegen->target_data_ref,
960 struct_type->type_ref);
961
962 uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(c->codegen->target_data_ref, struct_type->type_ref);
963 uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(c->codegen->target_data_ref, struct_type->type_ref);
964 ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(c->codegen->dbuilder,
965 ZigLLVMFileToScope(c->import->di_file),
966 buf_ptr(full_type_name), c->import->di_file, line + 1,
967 debug_size_in_bits,
968 debug_align_in_bits,
969 0,
970 nullptr, di_element_types, field_count, 0, nullptr, "");
971
972 ZigLLVMReplaceTemporary(c->codegen->dbuilder, struct_type->di_type, replacement_di_type);
973 struct_type->di_type = replacement_di_type;
974
975 return struct_type;
976}
1908 AstNode *field_node = trans_create_node(c, NodeTypeStructField);
1909 field_node->data.struct_field.name = buf_create_from_str(decl_name(field_decl));
1910 field_node->data.struct_field.type = trans_qual_type(c, field_decl->getType(), field_decl->getLocation());
9771911
978static void visit_record_decl(Context *c, const RecordDecl *record_decl) {
979 TypeTableEntry *struct_type = resolve_record_decl(c, record_decl);
1912 if (field_node->data.struct_field.type == nullptr) {
1913 emit_warning(c, field_decl->getLocation(),
1914 "struct %s demoted to opaque type - unresolved type",
1915 is_anonymous ? "(anon)" : buf_ptr(bare_name));
9801916
981 if (struct_type->id == TypeTableEntryIdInvalid) {
982 return;
983 }
984
985 bool is_anonymous = (record_decl->isAnonymousStructOrUnion() || decl_name(record_decl)[0] == 0);
986 if (is_anonymous)
987 return;
1917 return demote_struct_to_opaque(c, record_decl, full_type_name, bare_name);
1918 }
9881919
989 Buf *bare_name = buf_create_from_str(decl_name(record_decl));
1920 struct_node->data.container_decl.fields.items[i] = field_node;
1921 }
9901922
991 Tld *tld = add_container_tld(c, struct_type);
992 add_global_weak_alias(c, bare_name, tld);
1923 if (is_anonymous) {
1924 return struct_node;
1925 } else {
1926 add_global_weak_alias(c, bare_name, full_type_name);
1927 add_global_var(c, full_type_name, struct_node);
1928 return trans_create_node_symbol(c, full_type_name);
1929 }
9931930}
9941931
9951932static void visit_var_decl(Context *c, const VarDecl *var_decl) {
......@@ -999,17 +1936,19 @@ static void visit_var_decl(Context *c, const VarDecl *var_decl) {
9991936 case VarDecl::TLS_None:
10001937 break;
10011938 case VarDecl::TLS_Static:
1002 emit_warning(c, var_decl, "ignoring variable '%s' - static thread local storage\n", buf_ptr(name));
1939 emit_warning(c, var_decl->getLocation(),
1940 "ignoring variable '%s' - static thread local storage", buf_ptr(name));
10031941 return;
10041942 case VarDecl::TLS_Dynamic:
1005 emit_warning(c, var_decl, "ignoring variable '%s' - dynamic thread local storage\n", buf_ptr(name));
1943 emit_warning(c, var_decl->getLocation(),
1944 "ignoring variable '%s' - dynamic thread local storage", buf_ptr(name));
10061945 return;
10071946 }
10081947
10091948 QualType qt = var_decl->getType();
1010 TypeTableEntry *var_type = resolve_qual_type(c, qt, var_decl);
1011 if (var_type->id == TypeTableEntryIdInvalid) {
1012 emit_warning(c, var_decl, "ignoring variable '%s' - unresolved type\n", buf_ptr(name));
1949 AstNode *var_type = trans_qual_type(c, qt, var_decl->getLocation());
1950 if (var_type == nullptr) {
1951 emit_warning(c, var_decl->getLocation(), "ignoring variable '%s' - unresolved type", buf_ptr(name));
10131952 return;
10141953 }
10151954
......@@ -1018,59 +1957,53 @@ static void visit_var_decl(Context *c, const VarDecl *var_decl) {
10181957 bool is_const = qt.isConstQualified();
10191958
10201959 if (is_static && !is_extern) {
1021 if (!var_decl->hasInit()) {
1022 emit_warning(c, var_decl, "ignoring variable '%s' - no initializer\n", buf_ptr(name));
1023 return;
1024 }
1025 APValue *ap_value = var_decl->evaluateValue();
1026 if (!ap_value) {
1027 emit_warning(c, var_decl, "ignoring variable '%s' - unable to evaluate initializer\n", buf_ptr(name));
1028 return;
1029 }
1030 ConstExprValue *init_value = nullptr;
1031 switch (ap_value->getKind()) {
1032 case APValue::Int:
1033 {
1034 if (var_type->id != TypeTableEntryIdInt) {
1035 emit_warning(c, var_decl,
1036 "ignoring variable '%s' - int initializer for non int type\n", buf_ptr(name));
1037 return;
1038 }
1039 init_value = create_const_int_ap(c, var_type, var_decl, ap_value->getInt());
1040 if (!init_value)
1041 return;
1042
1043 break;
1044 }
1045 case APValue::Uninitialized:
1046 case APValue::Float:
1047 case APValue::ComplexInt:
1048 case APValue::ComplexFloat:
1049 case APValue::LValue:
1050 case APValue::Vector:
1051 case APValue::Array:
1052 case APValue::Struct:
1053 case APValue::Union:
1054 case APValue::MemberPointer:
1055 case APValue::AddrLabelDiff:
1056 emit_warning(c, var_decl,
1057 "ignoring variable '%s' - unrecognized initializer value kind\n", buf_ptr(name));
1960 AstNode *init_node;
1961 if (var_decl->hasInit()) {
1962 APValue *ap_value = var_decl->evaluateValue();
1963 if (ap_value == nullptr) {
1964 emit_warning(c, var_decl->getLocation(),
1965 "ignoring variable '%s' - unable to evaluate initializer", buf_ptr(name));
10581966 return;
1967 }
1968 switch (ap_value->getKind()) {
1969 case APValue::Int:
1970 init_node = trans_create_node_apint(c, ap_value->getInt());
1971 break;
1972 case APValue::Uninitialized:
1973 init_node = trans_create_node_symbol_str(c, "undefined");
1974 break;
1975 case APValue::Float:
1976 case APValue::ComplexInt:
1977 case APValue::ComplexFloat:
1978 case APValue::LValue:
1979 case APValue::Vector:
1980 case APValue::Array:
1981 case APValue::Struct:
1982 case APValue::Union:
1983 case APValue::MemberPointer:
1984 case APValue::AddrLabelDiff:
1985 emit_warning(c, var_decl->getLocation(),
1986 "ignoring variable '%s' - unrecognized initializer value kind", buf_ptr(name));
1987 return;
1988 }
1989 } else {
1990 init_node = trans_create_node_symbol_str(c, "undefined");
10591991 }
10601992
1061 TldVar *tld_var = create_global_var(c, name, init_value, true);
1062 add_global(c, &tld_var->base);
1993 AstNode *var_node = trans_create_node_var_decl(c, is_const, name, var_type, init_node);
1994 c->root->data.root.top_level_decls.append(var_node);
10631995 return;
10641996 }
10651997
10661998 if (is_extern) {
1067 TldVar *tld_var = create_global_var(c, name, create_const_runtime(var_type), is_const);
1068 tld_var->var->linkage = VarLinkageExternal;
1069 add_global(c, &tld_var->base);
1999 AstNode *var_node = trans_create_node_var_decl(c, is_const, name, var_type, nullptr);
2000 var_node->data.variable_declaration.is_extern = true;
2001 c->root->data.root.top_level_decls.append(var_node);
10702002 return;
10712003 }
10722004
1073 emit_warning(c, var_decl, "ignoring variable '%s' - non-extern, non-static variable\n", buf_ptr(name));
2005 emit_warning(c, var_decl->getLocation(),
2006 "ignoring variable '%s' - non-extern, non-static variable", buf_ptr(name));
10742007 return;
10752008}
10762009
......@@ -1082,44 +2015,35 @@ static bool decl_visitor(void *context, const Decl *decl) {
10822015 visit_fn_decl(c, static_cast<const FunctionDecl*>(decl));
10832016 break;
10842017 case Decl::Typedef:
1085 visit_typedef_decl(c, static_cast<const TypedefNameDecl *>(decl));
2018 resolve_typedef_decl(c, static_cast<const TypedefNameDecl *>(decl));
10862019 break;
10872020 case Decl::Enum:
1088 visit_enum_decl(c, static_cast<const EnumDecl *>(decl));
2021 resolve_enum_decl(c, static_cast<const EnumDecl *>(decl));
10892022 break;
10902023 case Decl::Record:
1091 visit_record_decl(c, static_cast<const RecordDecl *>(decl));
2024 resolve_record_decl(c, static_cast<const RecordDecl *>(decl));
10922025 break;
10932026 case Decl::Var:
10942027 visit_var_decl(c, static_cast<const VarDecl *>(decl));
10952028 break;
10962029 default:
1097 emit_warning(c, decl, "ignoring %s decl\n", decl->getDeclKindName());
2030 emit_warning(c, decl->getLocation(), "ignoring %s decl", decl->getDeclKindName());
10982031 }
10992032
11002033 return true;
11012034}
11022035
11032036static bool name_exists(Context *c, Buf *name) {
1104 if (c->global_type_table.maybe_get(name)) {
1105 return true;
1106 }
1107 if (get_global(c, name)) {
1108 return true;
1109 }
1110 if (c->macro_table.maybe_get(name)) {
1111 return true;
1112 }
1113 return false;
2037 return get_global(c, name) != nullptr;
11142038}
11152039
11162040static void render_aliases(Context *c) {
11172041 for (size_t i = 0; i < c->aliases.length; i += 1) {
11182042 Alias *alias = &c->aliases.at(i);
1119 if (name_exists(c, alias->name))
2043 if (name_exists(c, alias->new_name))
11202044 continue;
11212045
1122 add_global_alias(c, alias->name, alias->tld);
2046 add_global_var(c, alias->new_name, trans_create_node_symbol(c, alias->canon_name));
11232047 }
11242048}
11252049
......@@ -1130,8 +2054,12 @@ static void render_macros(Context *c) {
11302054 if (!entry)
11312055 break;
11322056
1133 Tld *var_tld = entry->value;
1134 add_global(c, var_tld);
2057 AstNode *value_node = entry->value;
2058 if (value_node->type == NodeTypeFnDef) {
2059 c->root->data.root.top_level_decls.append(value_node);
2060 } else {
2061 add_global_var(c, entry->key, value_node);
2062 }
11352063 }
11362064}
11372065
......@@ -1150,52 +2078,52 @@ static void process_macro(Context *c, CTokenize *ctok, Buf *name, const char *ch
11502078 switch (tok->id) {
11512079 case CTokIdCharLit:
11522080 if (is_last && is_first) {
1153 Tld *tld = create_global_num_lit_unsigned_negative(c, name, tok->data.char_lit, false);
1154 c->macro_table.put(name, tld);
2081 AstNode *node = trans_create_node_unsigned(c, tok->data.char_lit);
2082 c->macro_table.put(name, node);
11552083 }
11562084 return;
11572085 case CTokIdStrLit:
11582086 if (is_last && is_first) {
1159 Tld *tld = create_global_str_lit_var(c, name, buf_create_from_buf(&tok->data.str_lit));
1160 c->macro_table.put(name, tld);
2087 AstNode *node = trans_create_node_str_lit_c(c, buf_create_from_buf(&tok->data.str_lit));
2088 c->macro_table.put(name, node);
11612089 }
11622090 return;
11632091 case CTokIdNumLitInt:
11642092 if (is_last) {
1165 Tld *tld;
2093 AstNode *node;
11662094 switch (tok->data.num_lit_int.suffix) {
11672095 case CNumLitSuffixNone:
1168 tld = create_global_num_lit_unsigned_negative(c, name, tok->data.num_lit_int.x, negate);
2096 node = trans_create_node_unsigned_negative(c, tok->data.num_lit_int.x, negate);
11692097 break;
11702098 case CNumLitSuffixL:
1171 tld = create_global_num_lit_unsigned_negative_type(c, name, tok->data.num_lit_int.x, negate,
1172 c->codegen->builtin_types.entry_c_int[CIntTypeLong]);
2099 node = trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate,
2100 "c_long");
11732101 break;
11742102 case CNumLitSuffixU:
1175 tld = create_global_num_lit_unsigned_negative_type(c, name, tok->data.num_lit_int.x, negate,
1176 c->codegen->builtin_types.entry_c_int[CIntTypeUInt]);
2103 node = trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate,
2104 "c_uint");
11772105 break;
11782106 case CNumLitSuffixLU:
1179 tld = create_global_num_lit_unsigned_negative_type(c, name, tok->data.num_lit_int.x, negate,
1180 c->codegen->builtin_types.entry_c_int[CIntTypeULong]);
2107 node = trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate,
2108 "c_ulong");
11812109 break;
11822110 case CNumLitSuffixLL:
1183 tld = create_global_num_lit_unsigned_negative_type(c, name, tok->data.num_lit_int.x, negate,
1184 c->codegen->builtin_types.entry_c_int[CIntTypeLongLong]);
2111 node = trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate,
2112 "c_longlong");
11852113 break;
11862114 case CNumLitSuffixLLU:
1187 tld = create_global_num_lit_unsigned_negative_type(c, name, tok->data.num_lit_int.x, negate,
1188 c->codegen->builtin_types.entry_c_int[CIntTypeULongLong]);
2115 node = trans_create_node_unsigned_negative_type(c, tok->data.num_lit_int.x, negate,
2116 "c_ulonglong");
11892117 break;
11902118 }
1191 c->macro_table.put(name, tld);
2119 c->macro_table.put(name, node);
11922120 }
11932121 return;
11942122 case CTokIdNumLitFloat:
11952123 if (is_last) {
11962124 double value = negate ? -tok->data.num_lit_float : tok->data.num_lit_float;
1197 Tld *tld = create_global_num_lit_float(c, name, value);
1198 c->macro_table.put(name, tld);
2125 AstNode *node = trans_create_node_float_lit(c, value);
2126 c->macro_table.put(name, node);
11992127 }
12002128 return;
12012129 case CTokIdSymbol:
......@@ -1224,35 +2152,37 @@ static void process_symbol_macros(Context *c) {
12242152 for (size_t i = 0; i < c->macro_symbols.length; i += 1) {
12252153 MacroSymbol ms = c->macro_symbols.at(i);
12262154
1227 // If this macro aliases another top level declaration, we can make that happen by
1228 // putting another entry in the decl table pointing to the same top level decl.
1229 Tld *existing_tld = get_global(c, ms.value);
1230 if (!existing_tld)
2155 // Check if this macro aliases another top level declaration
2156 AstNode *existing_node = get_global(c, ms.value);
2157 if (!existing_node || name_exists(c, ms.name))
12312158 continue;
12322159
12332160 // If a macro aliases a global variable which is a function pointer, we conclude that
12342161 // the macro is intended to represent a function that assumes the function pointer
12352162 // variable is non-null and calls it.
1236 if (existing_tld->id == TldIdVar) {
1237 TldVar *tld_var = (TldVar *)existing_tld;
1238 TypeTableEntry *var_type = tld_var->var->value->type;
1239 if (var_type->id == TypeTableEntryIdMaybe && !tld_var->var->src_is_const) {
1240 TypeTableEntry *child_type = var_type->data.maybe.child_type;
1241 if (child_type->id == TypeTableEntryIdFn) {
1242 Tld *tld = create_inline_fn_tld(c, ms.name, tld_var);
1243 c->macro_table.put(ms.name, tld);
2163 if (existing_node->type == NodeTypeVariableDeclaration) {
2164 AstNode *var_type = existing_node->data.variable_declaration.type;
2165 if (var_type != nullptr && var_type->type == NodeTypePrefixOpExpr &&
2166 var_type->data.prefix_op_expr.prefix_op == PrefixOpMaybe)
2167 {
2168 AstNode *fn_proto_node = var_type->data.prefix_op_expr.primary_expr;
2169 if (fn_proto_node->type == NodeTypeFnProto) {
2170 AstNode *inline_fn_node = trans_create_node_inline_fn(c, ms.name, ms.value, fn_proto_node);
2171 c->macro_table.put(ms.name, inline_fn_node);
12442172 continue;
12452173 }
12462174 }
12472175 }
12482176
1249 add_global_alias(c, ms.name, existing_tld);
2177 add_global_var(c, ms.name, trans_create_node_symbol(c, ms.value));
12502178 }
12512179}
12522180
12532181static void process_preprocessor_entities(Context *c, ASTUnit &unit) {
12542182 CTokenize ctok = {{0}};
12552183
2184 // TODO if we see #undef, delete it from the table
2185
12562186 for (PreprocessedEntity *entity : unit.getLocalPreprocessingEntities()) {
12572187 switch (entity->getKind()) {
12582188 case PreprocessedEntity::InvalidKind:
......@@ -1309,9 +2239,6 @@ int parse_h_file(ImportTableEntry *import, ZigList<ErrorMsg *> *errors, const ch
13092239 c->import = import;
13102240 c->errors = errors;
13112241 c->visib_mod = VisibModPub;
1312 c->global_type_table.init(8);
1313 c->enum_type_table.init(8);
1314 c->struct_type_table.init(8);
13152242 c->decl_table.init(8);
13162243 c->macro_table.init(8);
13172244 c->codegen = codegen;
......@@ -1373,7 +2300,7 @@ int parse_h_file(ImportTableEntry *import, ZigList<ErrorMsg *> *errors, const ch
13732300
13742301 std::shared_ptr<PCHContainerOperations> pch_container_ops = std::make_shared<PCHContainerOperations>();
13752302
1376 bool skip_function_bodies = true;
2303 bool skip_function_bodies = false;
13772304 bool only_local_decls = true;
13782305 bool capture_diagnostics = true;
13792306 bool user_files_are_volatile = true;
......@@ -1390,7 +2317,6 @@ int parse_h_file(ImportTableEntry *import, ZigList<ErrorMsg *> *errors, const ch
13902317 single_file_parse, user_files_are_volatile, for_serialization, None, &err_unit,
13912318 nullptr));
13922319
1393
13942320 // Early failures in LoadFromCommandLine may return with ErrUnit unset.
13952321 if (!ast_unit && !err_unit) {
13962322 return ErrorFileSystem;
......@@ -1416,39 +2342,48 @@ int parse_h_file(ImportTableEntry *import, ZigList<ErrorMsg *> *errors, const ch
14162342 break;
14172343 }
14182344 StringRef msg_str_ref = it->getMessage();
1419 FullSourceLoc fsl = it->getLocation();
1420 FileID file_id = fsl.getFileID();
1421 StringRef filename = fsl.getManager().getFilename(fsl);
1422 unsigned line = fsl.getSpellingLineNumber() - 1;
1423 unsigned column = fsl.getSpellingColumnNumber() - 1;
1424 unsigned offset = fsl.getManager().getFileOffset(fsl);
1425 const char *source = (const char *)fsl.getManager().getBufferData(file_id).bytes_begin();
14262345 Buf *msg = buf_create_from_str((const char *)msg_str_ref.bytes_begin());
1427 Buf *path;
1428 if (filename.empty()) {
1429 path = buf_alloc();
1430 } else {
1431 path = buf_create_from_mem((const char *)filename.bytes_begin(), filename.size());
1432 }
2346 FullSourceLoc fsl = it->getLocation();
2347 if (fsl.hasManager()) {
2348 FileID file_id = fsl.getFileID();
2349 StringRef filename = fsl.getManager().getFilename(fsl);
2350 unsigned line = fsl.getSpellingLineNumber() - 1;
2351 unsigned column = fsl.getSpellingColumnNumber() - 1;
2352 unsigned offset = fsl.getManager().getFileOffset(fsl);
2353 const char *source = (const char *)fsl.getManager().getBufferData(file_id).bytes_begin();
2354 Buf *path;
2355 if (filename.empty()) {
2356 path = buf_alloc();
2357 } else {
2358 path = buf_create_from_mem((const char *)filename.bytes_begin(), filename.size());
2359 }
14332360
1434 ErrorMsg *err_msg = err_msg_create_with_offset(path, line, column, offset, source, msg);
2361 ErrorMsg *err_msg = err_msg_create_with_offset(path, line, column, offset, source, msg);
14352362
1436 c->errors->append(err_msg);
2363 c->errors->append(err_msg);
2364 } else {
2365 // NOTE the only known way this gets triggered right now is if you have a lot of errors
2366 // clang emits "too many errors emitted, stopping now"
2367 fprintf(stderr, "unexpected error from clang: %s\n", buf_ptr(msg));
2368 }
14372369 }
14382370
14392371 return 0;
14402372 }
14412373
2374 c->ctx = &ast_unit->getASTContext();
14422375 c->source_manager = &ast_unit->getSourceManager();
2376 c->root = trans_create_node(c, NodeTypeRoot);
14432377
14442378 ast_unit->visitLocalTopLevelDecls(c, decl_visitor);
14452379
14462380 process_preprocessor_entities(c, *ast_unit);
14472381
14482382 process_symbol_macros(c);
1449
14502383 render_macros(c);
14512384 render_aliases(c);
14522385
2386 import->root = c->root;
2387
14532388 return 0;
14542389}
src/parser.cpp+3-9
......@@ -20,10 +20,8 @@ struct ParseContext {
2020 ZigList<Token> *tokens;
2121 ImportTableEntry *owner;
2222 ErrColor err_color;
23 uint32_t *next_node_index;
2423 // These buffers are used freqently so we preallocate them once here.
2524 Buf *void_buf;
26 Buf *empty_buf;
2725};
2826
2927__attribute__ ((format (printf, 4, 5)))
......@@ -70,8 +68,6 @@ static AstNode *ast_create_node_no_line_info(ParseContext *pc, NodeType type) {
7068 AstNode *node = allocate<AstNode>(1);
7169 node->type = type;
7270 node->owner = pc->owner;
73 node->create_index = *pc->next_node_index;
74 *pc->next_node_index += 1;
7571 return node;
7672}
7773
......@@ -279,7 +275,7 @@ static AstNode *ast_parse_param_decl(ParseContext *pc, size_t *token_index) {
279275 token = &pc->tokens->at(*token_index);
280276 }
281277
282 node->data.param_decl.name = pc->empty_buf;
278 node->data.param_decl.name = nullptr;
283279
284280 if (token->id == TokenIdSymbol) {
285281 Token *next_token = &pc->tokens->at(*token_index + 1);
......@@ -2249,7 +2245,7 @@ static AstNode *ast_parse_fn_proto(ParseContext *pc, size_t *token_index, bool m
22492245 *token_index += 1;
22502246 node->data.fn_proto.name = token_buf(fn_name);
22512247 } else {
2252 node->data.fn_proto.name = pc->empty_buf;
2248 node->data.fn_proto.name = nullptr;
22532249 }
22542250
22552251 ast_parse_param_decl_list(pc, token_index, &node->data.fn_proto.params, &node->data.fn_proto.is_var_args);
......@@ -2611,16 +2607,14 @@ static AstNode *ast_parse_root(ParseContext *pc, size_t *token_index) {
26112607}
26122608
26132609AstNode *ast_parse(Buf *buf, ZigList<Token> *tokens, ImportTableEntry *owner,
2614 ErrColor err_color, uint32_t *next_node_index)
2610 ErrColor err_color)
26152611{
26162612 ParseContext pc = {0};
26172613 pc.void_buf = buf_create_from_str("void");
2618 pc.empty_buf = buf_create_from_str("");
26192614 pc.err_color = err_color;
26202615 pc.owner = owner;
26212616 pc.buf = buf;
26222617 pc.tokens = tokens;
2623 pc.next_node_index = next_node_index;
26242618 size_t token_index = 0;
26252619 pc.root = ast_parse_root(&pc, &token_index);
26262620 return pc.root;
src/parser.hpp+1-2
......@@ -17,8 +17,7 @@ void ast_token_error(Token *token, const char *format, ...);
1717
1818
1919// This function is provided by generated code, generated by parsergen.cpp
20AstNode * ast_parse(Buf *buf, ZigList<Token> *tokens, ImportTableEntry *owner, ErrColor err_color,
21 uint32_t *next_node_index);
20AstNode * ast_parse(Buf *buf, ZigList<Token> *tokens, ImportTableEntry *owner, ErrColor err_color);
2221
2322void ast_print(AstNode *node, int indent);
2423
std/zlib/deflate.zig created+522
......@@ -0,0 +1,522 @@
1const z_stream = struct {
2 /// next input byte */
3 next_in: &const u8,
4
5 /// number of bytes available at next_in
6 avail_in: u16,
7 /// total number of input bytes read so far
8 total_in: u32,
9
10 /// next output byte will go here
11 next_out: u8,
12 /// remaining free space at next_out
13 avail_out: u16,
14 /// total number of bytes output so far
15 total_out: u32,
16
17 /// last error message, NULL if no error
18 msg: ?&const u8,
19 /// not visible by applications
20 state:
21 struct internal_state FAR *state; // not visible by applications */
22
23 alloc_func zalloc; // used to allocate the internal state */
24 free_func zfree; // used to free the internal state */
25 voidpf opaque; // private data object passed to zalloc and zfree */
26
27 int data_type; // best guess about the data type: binary or text
28 // for deflate, or the decoding state for inflate */
29 uint32_t adler; // Adler-32 or CRC-32 value of the uncompressed data */
30 uint32_t reserved; // reserved for future use */
31};
32
33typedef struct internal_state {
34 z_stream * strm; /* pointer back to this zlib stream */
35 int status; /* as the name implies */
36 uint8_t *pending_buf; /* output still pending */
37 ulg pending_buf_size; /* size of pending_buf */
38 uint8_t *pending_out; /* next pending byte to output to the stream */
39 ulg pending; /* nb of bytes in the pending buffer */
40 int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
41 gz_headerp gzhead; /* gzip header information to write */
42 ulg gzindex; /* where in extra, name, or comment */
43 uint8_t method; /* can only be DEFLATED */
44 int last_flush; /* value of flush param for previous deflate call */
45
46 /* used by deflate.c: */
47
48 uint16_t w_size; /* LZ77 window size (32K by default) */
49 uint16_t w_bits; /* log2(w_size) (8..16) */
50 uint16_t w_mask; /* w_size - 1 */
51
52 uint8_t *window;
53 /* Sliding window. Input bytes are read into the second half of the window,
54 * and move to the first half later to keep a dictionary of at least wSize
55 * bytes. With this organization, matches are limited to a distance of
56 * wSize-MAX_MATCH bytes, but this ensures that IO is always
57 * performed with a length multiple of the block size. Also, it limits
58 * the window size to 64K, which is quite useful on MSDOS.
59 * To do: use the user input buffer as sliding window.
60 */
61
62 ulg window_size;
63 /* Actual size of window: 2*wSize, except when the user input buffer
64 * is directly used as sliding window.
65 */
66
67 Posf *prev;
68 /* Link to older string with same hash index. To limit the size of this
69 * array to 64K, this link is maintained only for the last 32K strings.
70 * An index in this array is thus a window index modulo 32K.
71 */
72
73 Posf *head; /* Heads of the hash chains or NIL. */
74
75 uint16_t ins_h; /* hash index of string to be inserted */
76 uint16_t hash_size; /* number of elements in hash table */
77 uint16_t hash_bits; /* log2(hash_size) */
78 uint16_t hash_mask; /* hash_size-1 */
79
80 uint16_t hash_shift;
81 /* Number of bits by which ins_h must be shifted at each input
82 * step. It must be such that after MIN_MATCH steps, the oldest
83 * byte no longer takes part in the hash key, that is:
84 * hash_shift * MIN_MATCH >= hash_bits
85 */
86
87 long block_start;
88 /* Window position at the beginning of the current output block. Gets
89 * negative when the window is moved backwards.
90 */
91
92 uint16_t match_length; /* length of best match */
93 IPos prev_match; /* previous match */
94 int match_available; /* set if previous match exists */
95 uint16_t strstart; /* start of string to insert */
96 uint16_t match_start; /* start of matching string */
97 uint16_t lookahead; /* number of valid bytes ahead in window */
98
99 uint16_t prev_length;
100 /* Length of the best match at previous step. Matches not greater than this
101 * are discarded. This is used in the lazy match evaluation.
102 */
103
104 uint16_t max_chain_length;
105 /* To speed up deflation, hash chains are never searched beyond this
106 * length. A higher limit improves compression ratio but degrades the
107 * speed.
108 */
109
110 uint16_t max_lazy_match;
111 /* Attempt to find a better match only when the current match is strictly
112 * smaller than this value. This mechanism is used only for compression
113 * levels >= 4.
114 */
115# define max_insert_length max_lazy_match
116 /* Insert new strings in the hash table only if the match length is not
117 * greater than this length. This saves time but degrades compression.
118 * max_insert_length is used only for compression levels <= 3.
119 */
120
121 int level; /* compression level (1..9) */
122 int strategy; /* favor or force Huffman coding*/
123
124 uint16_t good_match;
125 /* Use a faster search when the previous match is longer than this */
126
127 int nice_match; /* Stop searching when current match exceeds this */
128
129 /* used by trees.c: */
130 /* Didn't use ct_data typedef below to suppress compiler warning */
131 struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
132 struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
133 struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
134
135 struct tree_desc_s l_desc; /* desc. for literal tree */
136 struct tree_desc_s d_desc; /* desc. for distance tree */
137 struct tree_desc_s bl_desc; /* desc. for bit length tree */
138
139 ush bl_count[MAX_BITS+1];
140 /* number of codes at each bit length for an optimal tree */
141
142 int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
143 int heap_len; /* number of elements in the heap */
144 int heap_max; /* element of largest frequency */
145 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
146 * The same heap array is used to build all trees.
147 */
148
149 uch depth[2*L_CODES+1];
150 /* Depth of each subtree used as tie breaker for trees of equal frequency
151 */
152
153 uchf *l_buf; /* buffer for literals or lengths */
154
155 uint16_t lit_bufsize;
156 /* Size of match buffer for literals/lengths. There are 4 reasons for
157 * limiting lit_bufsize to 64K:
158 * - frequencies can be kept in 16 bit counters
159 * - if compression is not successful for the first block, all input
160 * data is still in the window so we can still emit a stored block even
161 * when input comes from standard input. (This can also be done for
162 * all blocks if lit_bufsize is not greater than 32K.)
163 * - if compression is not successful for a file smaller than 64K, we can
164 * even emit a stored file instead of a stored block (saving 5 bytes).
165 * This is applicable only for zip (not gzip or zlib).
166 * - creating new Huffman trees less frequently may not provide fast
167 * adaptation to changes in the input data statistics. (Take for
168 * example a binary file with poorly compressible code followed by
169 * a highly compressible string table.) Smaller buffer sizes give
170 * fast adaptation but have of course the overhead of transmitting
171 * trees more frequently.
172 * - I can't count above 4
173 */
174
175 uint16_t last_lit; /* running index in l_buf */
176
177 ushf *d_buf;
178 /* Buffer for distances. To simplify the code, d_buf and l_buf have
179 * the same number of elements. To use different lengths, an extra flag
180 * array would be necessary.
181 */
182
183 ulg opt_len; /* bit length of current block with optimal trees */
184 ulg static_len; /* bit length of current block with static trees */
185 uint16_t matches; /* number of string matches in current block */
186 uint16_t insert; /* bytes at end of window left to insert */
187
188#ifdef ZLIB_DEBUG
189 ulg compressed_len; /* total bit length of compressed file mod 2^32 */
190 ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
191#endif
192
193 ush bi_buf;
194 /* Output buffer. bits are inserted starting at the bottom (least
195 * significant bits).
196 */
197 int bi_valid;
198 /* Number of valid bits in bi_buf. All bits above the last valid bit
199 * are always zero.
200 */
201
202 ulg high_water;
203 /* High water mark offset in window for initialized bytes -- bytes above
204 * this are set to zero in order to avoid memory check warnings when
205 * longest match routines access bytes past the input. This is then
206 * updated to the new high water mark.
207 */
208
209} FAR deflate_state;
210
211fn deflate(strm: &z_stream, flush: int) -> %void {
212
213}
214
215int deflate (z_stream * strm, int flush) {
216 int old_flush; /* value of flush param for previous deflate call */
217 deflate_state *s;
218
219 if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
220 return Z_STREAM_ERROR;
221 }
222 s = strm->state;
223
224 if (strm->next_out == Z_NULL ||
225 (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
226 (s->status == FINISH_STATE && flush != Z_FINISH)) {
227 ERR_RETURN(strm, Z_STREAM_ERROR);
228 }
229 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
230
231 old_flush = s->last_flush;
232 s->last_flush = flush;
233
234 /* Flush as much pending output as possible */
235 if (s->pending != 0) {
236 flush_pending(strm);
237 if (strm->avail_out == 0) {
238 /* Since avail_out is 0, deflate will be called again with
239 * more output space, but possibly with both pending and
240 * avail_in equal to zero. There won't be anything to do,
241 * but this is not an error situation so make sure we
242 * return OK instead of BUF_ERROR at next call of deflate:
243 */
244 s->last_flush = -1;
245 return Z_OK;
246 }
247
248 /* Make sure there is something to do and avoid duplicate consecutive
249 * flushes. For repeated and useless calls with Z_FINISH, we keep
250 * returning Z_STREAM_END instead of Z_BUF_ERROR.
251 */
252 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
253 flush != Z_FINISH) {
254 ERR_RETURN(strm, Z_BUF_ERROR);
255 }
256
257 /* User must not provide more input after the first FINISH: */
258 if (s->status == FINISH_STATE && strm->avail_in != 0) {
259 ERR_RETURN(strm, Z_BUF_ERROR);
260 }
261
262 /* Write the header */
263 if (s->status == INIT_STATE) {
264 /* zlib header */
265 uint16_t header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
266 uint16_t level_flags;
267
268 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
269 level_flags = 0;
270 else if (s->level < 6)
271 level_flags = 1;
272 else if (s->level == 6)
273 level_flags = 2;
274 else
275 level_flags = 3;
276 header |= (level_flags << 6);
277 if (s->strstart != 0) header |= PRESET_DICT;
278 header += 31 - (header % 31);
279
280 putShortMSB(s, header);
281
282 /* Save the adler32 of the preset dictionary: */
283 if (s->strstart != 0) {
284 putShortMSB(s, (uint16_t)(strm->adler >> 16));
285 putShortMSB(s, (uint16_t)(strm->adler & 0xffff));
286 }
287 strm->adler = adler32(0L, Z_NULL, 0);
288 s->status = BUSY_STATE;
289
290 /* Compression must start with an empty pending buffer */
291 flush_pending(strm);
292 if (s->pending != 0) {
293 s->last_flush = -1;
294 return Z_OK;
295 }
296 }
297#ifdef GZIP
298 if (s->status == GZIP_STATE) {
299 /* gzip header */
300 strm->adler = crc32(0L, Z_NULL, 0);
301 put_byte(s, 31);
302 put_byte(s, 139);
303 put_byte(s, 8);
304 if (s->gzhead == Z_NULL) {
305 put_byte(s, 0);
306 put_byte(s, 0);
307 put_byte(s, 0);
308 put_byte(s, 0);
309 put_byte(s, 0);
310 put_byte(s, s->level == 9 ? 2 :
311 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
312 4 : 0));
313 put_byte(s, OS_CODE);
314 s->status = BUSY_STATE;
315
316 /* Compression must start with an empty pending buffer */
317 flush_pending(strm);
318 if (s->pending != 0) {
319 s->last_flush = -1;
320 return Z_OK;
321 }
322 }
323 else {
324 put_byte(s, (s->gzhead->text ? 1 : 0) +
325 (s->gzhead->hcrc ? 2 : 0) +
326 (s->gzhead->extra == Z_NULL ? 0 : 4) +
327 (s->gzhead->name == Z_NULL ? 0 : 8) +
328 (s->gzhead->comment == Z_NULL ? 0 : 16)
329 );
330 put_byte(s, (uint8_t)(s->gzhead->time & 0xff));
331 put_byte(s, (uint8_t)((s->gzhead->time >> 8) & 0xff));
332 put_byte(s, (uint8_t)((s->gzhead->time >> 16) & 0xff));
333 put_byte(s, (uint8_t)((s->gzhead->time >> 24) & 0xff));
334 put_byte(s, s->level == 9 ? 2 :
335 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
336 4 : 0));
337 put_byte(s, s->gzhead->os & 0xff);
338 if (s->gzhead->extra != Z_NULL) {
339 put_byte(s, s->gzhead->extra_len & 0xff);
340 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
341 }
342 if (s->gzhead->hcrc)
343 strm->adler = crc32(strm->adler, s->pending_buf,
344 s->pending);
345 s->gzindex = 0;
346 s->status = EXTRA_STATE;
347 }
348 }
349 if (s->status == EXTRA_STATE) {
350 if (s->gzhead->extra != Z_NULL) {
351 ulg beg = s->pending; /* start of bytes to update crc */
352 uint16_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
353 while (s->pending + left > s->pending_buf_size) {
354 uint16_t copy = s->pending_buf_size - s->pending;
355 zmemcpy(s->pending_buf + s->pending,
356 s->gzhead->extra + s->gzindex, copy);
357 s->pending = s->pending_buf_size;
358 HCRC_UPDATE(beg);
359 s->gzindex += copy;
360 flush_pending(strm);
361 if (s->pending != 0) {
362 s->last_flush = -1;
363 return Z_OK;
364 }
365 beg = 0;
366 left -= copy;
367 }
368 zmemcpy(s->pending_buf + s->pending,
369 s->gzhead->extra + s->gzindex, left);
370 s->pending += left;
371 HCRC_UPDATE(beg);
372 s->gzindex = 0;
373 }
374 s->status = NAME_STATE;
375 }
376 if (s->status == NAME_STATE) {
377 if (s->gzhead->name != Z_NULL) {
378 ulg beg = s->pending; /* start of bytes to update crc */
379 int val;
380 do {
381 if (s->pending == s->pending_buf_size) {
382 HCRC_UPDATE(beg);
383 flush_pending(strm);
384 if (s->pending != 0) {
385 s->last_flush = -1;
386 return Z_OK;
387 }
388 beg = 0;
389 }
390 val = s->gzhead->name[s->gzindex++];
391 put_byte(s, val);
392 } while (val != 0);
393 HCRC_UPDATE(beg);
394 s->gzindex = 0;
395 }
396 s->status = COMMENT_STATE;
397 }
398 if (s->status == COMMENT_STATE) {
399 if (s->gzhead->comment != Z_NULL) {
400 ulg beg = s->pending; /* start of bytes to update crc */
401 int val;
402 do {
403 if (s->pending == s->pending_buf_size) {
404 HCRC_UPDATE(beg);
405 flush_pending(strm);
406 if (s->pending != 0) {
407 s->last_flush = -1;
408 return Z_OK;
409 }
410 beg = 0;
411 }
412 val = s->gzhead->comment[s->gzindex++];
413 put_byte(s, val);
414 } while (val != 0);
415 HCRC_UPDATE(beg);
416 }
417 s->status = HCRC_STATE;
418 }
419 if (s->status == HCRC_STATE) {
420 if (s->gzhead->hcrc) {
421 if (s->pending + 2 > s->pending_buf_size) {
422 flush_pending(strm);
423 if (s->pending != 0) {
424 s->last_flush = -1;
425 return Z_OK;
426 }
427 }
428 put_byte(s, (uint8_t)(strm->adler & 0xff));
429 put_byte(s, (uint8_t)((strm->adler >> 8) & 0xff));
430 strm->adler = crc32(0L, Z_NULL, 0);
431 }
432 s->status = BUSY_STATE;
433
434 /* Compression must start with an empty pending buffer */
435 flush_pending(strm);
436 if (s->pending != 0) {
437 s->last_flush = -1;
438 return Z_OK;
439 }
440 }
441#endif
442
443 /* Start a new block or continue the current one.
444 */
445 if (strm->avail_in != 0 || s->lookahead != 0 ||
446 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
447 block_state bstate;
448
449 bstate = s->level == 0 ? deflate_stored(s, flush) :
450 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
451 s->strategy == Z_RLE ? deflate_rle(s, flush) :
452 (*(configuration_table[s->level].func))(s, flush);
453
454 if (bstate == finish_started || bstate == finish_done) {
455 s->status = FINISH_STATE;
456 }
457 if (bstate == need_more || bstate == finish_started) {
458 if (strm->avail_out == 0) {
459 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
460 }
461 return Z_OK;
462 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
463 * of deflate should use the same flush parameter to make sure
464 * that the flush is complete. So we don't have to output an
465 * empty block here, this will be done at next call. This also
466 * ensures that for a very small output buffer, we emit at most
467 * one empty block.
468 */
469 }
470 if (bstate == block_done) {
471 if (flush == Z_PARTIAL_FLUSH) {
472 _tr_align(s);
473 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
474 _tr_stored_block(s, (char*)0, 0L, 0);
475 /* For a full flush, this empty block will be recognized
476 * as a special marker by inflate_sync().
477 */
478 if (flush == Z_FULL_FLUSH) {
479 CLEAR_HASH(s); /* forget history */
480 if (s->lookahead == 0) {
481 s->strstart = 0;
482 s->block_start = 0L;
483 s->insert = 0;
484 }
485 }
486 }
487 flush_pending(strm);
488 if (strm->avail_out == 0) {
489 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
490 return Z_OK;
491 }
492 }
493 }
494
495 if (flush != Z_FINISH) return Z_OK;
496 if (s->wrap <= 0) return Z_STREAM_END;
497
498 /* Write the trailer */
499#ifdef GZIP
500 if (s->wrap == 2) {
501 put_byte(s, (uint8_t)(strm->adler & 0xff));
502 put_byte(s, (uint8_t)((strm->adler >> 8) & 0xff));
503 put_byte(s, (uint8_t)((strm->adler >> 16) & 0xff));
504 put_byte(s, (uint8_t)((strm->adler >> 24) & 0xff));
505 put_byte(s, (uint8_t)(strm->total_in & 0xff));
506 put_byte(s, (uint8_t)((strm->total_in >> 8) & 0xff));
507 put_byte(s, (uint8_t)((strm->total_in >> 16) & 0xff));
508 put_byte(s, (uint8_t)((strm->total_in >> 24) & 0xff));
509 }
510 else
511#endif
512 {
513 putShortMSB(s, (uint16_t)(strm->adler >> 16));
514 putShortMSB(s, (uint16_t)(strm->adler & 0xffff));
515 }
516 flush_pending(strm);
517 /* If avail_out is zero, the application will call deflate again
518 * to flush the rest.
519 */
520 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
521 return s->pending != 0 ? Z_OK : Z_STREAM_END;
522}
std/zlib/inflate.zig created+969
......@@ -0,0 +1,969 @@
1
2error Z_STREAM_ERROR;
3error Z_STREAM_END;
4error Z_NEED_DICT;
5error Z_ERRNO;
6error Z_STREAM_ERROR;
7error Z_DATA_ERROR;
8error Z_MEM_ERROR;
9error Z_BUF_ERROR;
10error Z_VERSION_ERROR;
11
12pub Flush = enum {
13 NO_FLUSH,
14 PARTIAL_FLUSH,
15 SYNC_FLUSH,
16 FULL_FLUSH,
17 FINISH,
18 BLOCK,
19 TREES,
20};
21
22const code = struct {
23 /// operation, extra bits, table bits
24 op: u8,
25 /// bits in this part of the code
26 bits: u8,
27 /// offset in table or code value
28 val: u16,
29};
30
31/// State maintained between inflate() calls -- approximately 7K bytes, not
32/// including the allocated sliding window, which is up to 32K bytes.
33const inflate_state = struct {
34 z_stream * strm; /* pointer back to this zlib stream */
35 inflate_mode mode; /* current inflate mode */
36 int last; /* true if processing last block */
37 int wrap; /* bit 0 true for zlib, bit 1 true for gzip,
38 bit 2 true to validate check value */
39 int havedict; /* true if dictionary provided */
40 int flags; /* gzip header method and flags (0 if zlib) */
41 unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
42 unsigned long check; /* protected copy of check value */
43 unsigned long total; /* protected copy of output count */
44 gz_headerp head; /* where to save gzip header information */
45 /* sliding window */
46 unsigned wbits; /* log base 2 of requested window size */
47 unsigned wsize; /* window size or zero if not using window */
48 unsigned whave; /* valid bytes in the window */
49 unsigned wnext; /* window write index */
50 u8 FAR *window; /* allocated sliding window, if needed */
51 /* bit accumulator */
52 unsigned long hold; /* input bit accumulator */
53 unsigned bits; /* number of bits in "in" */
54 /* for string and stored block copying */
55 unsigned length; /* literal or length of data to copy */
56 unsigned offset; /* distance back to copy string from */
57 /* for table and code decoding */
58 unsigned extra; /* extra bits needed */
59 /* fixed and dynamic code tables */
60 code const FAR *lencode; /* starting table for length/literal codes */
61 code const FAR *distcode; /* starting table for distance codes */
62 unsigned lenbits; /* index bits for lencode */
63 unsigned distbits; /* index bits for distcode */
64 /* dynamic table building */
65 unsigned ncode; /* number of code length code lengths */
66 unsigned nlen; /* number of length code lengths */
67 unsigned ndist; /* number of distance code lengths */
68 unsigned have; /* number of code lengths in lens[] */
69 code FAR *next; /* next available space in codes[] */
70 unsigned short lens[320]; /* temporary storage for code lengths */
71 unsigned short work[288]; /* work area for code table building */
72 code codes[ENOUGH]; /* space for code tables */
73 int sane; /* if false, allow invalid distance too far */
74 int back; /* bits back of last unprocessed length/lit */
75 unsigned was; /* initial length of match */
76};
77
78const alloc_func = fn(opaque: &c_void, items: u16, size: u16);
79const free_func = fn(opaque: &c_void, address: &c_void);
80
81const z_stream = struct {
82 /// next input byte
83 next_in: &u8,
84 /// number of bytes available at next_in
85 avail_in: u16,
86 /// total number of input bytes read so far
87 total_in: u32,
88
89 /// next output byte will go here
90 next_out: &u8,
91 /// remaining free space at next_out
92 avail_out: u16,
93 /// total number of bytes output so far */
94 total_out: u32,
95
96 /// last error message, NULL if no error
97 msg: &const u8,
98 /// not visible by applications
99 state: &inflate_state,
100
101 /// used to allocate the internal state
102 zalloc: alloc_func,
103 /// used to free the internal state
104 zfree: free_func,
105 /// private data object passed to zalloc and zfree
106 opaque: &c_void,
107
108 /// best guess about the data type: binary or text
109 /// for deflate, or the decoding state for inflate
110 data_type: i32,
111
112 /// Adler-32 or CRC-32 value of the uncompressed data
113 adler: u32,
114};
115
116// Possible inflate modes between inflate() calls
117/// i: waiting for magic header
118pub const HEAD = 16180;
119/// i: waiting for method and flags (gzip)
120pub const FLAGS = 16181;
121/// i: waiting for modification time (gzip)
122pub const TIME = 16182;
123/// i: waiting for extra flags and operating system (gzip)
124pub const OS = 16183;
125/// i: waiting for extra length (gzip)
126pub const EXLEN = 16184;
127/// i: waiting for extra bytes (gzip)
128pub const EXTRA = 16185;
129/// i: waiting for end of file name (gzip)
130pub const NAME = 16186;
131/// i: waiting for end of comment (gzip)
132pub const COMMENT = 16187;
133/// i: waiting for header crc (gzip)
134pub const HCRC = 16188;
135/// i: waiting for dictionary check value
136pub const DICTID = 16189;
137/// waiting for inflateSetDictionary() call
138pub const DICT = 16190;
139/// i: waiting for type bits, including last-flag bit
140pub const TYPE = 16191;
141/// i: same, but skip check to exit inflate on new block
142pub const TYPEDO = 16192;
143/// i: waiting for stored size (length and complement)
144pub const STORED = 16193;
145/// i/o: same as COPY below, but only first time in
146pub const COPY_ = 16194;
147/// i/o: waiting for input or output to copy stored block
148pub const COPY = 16195;
149/// i: waiting for dynamic block table lengths
150pub const TABLE = 16196;
151/// i: waiting for code length code lengths
152pub const LENLENS = 16197;
153/// i: waiting for length/lit and distance code lengths
154pub const CODELENS = 16198;
155/// i: same as LEN below, but only first time in
156pub const LEN_ = 16199;
157/// i: waiting for length/lit/eob code
158pub const LEN = 16200;
159/// i: waiting for length extra bits
160pub const LENEXT = 16201;
161/// i: waiting for distance code
162pub const DIST = 16202;
163/// i: waiting for distance extra bits
164pub const DISTEXT = 16203;
165/// o: waiting for output space to copy string
166pub const MATCH = 16204;
167/// o: waiting for output space to write literal
168pub const LIT = 16205;
169/// i: waiting for 32-bit check value
170pub const CHECK = 16206;
171/// i: waiting for 32-bit length (gzip)
172pub const LENGTH = 16207;
173/// finished check, done -- remain here until reset
174pub const DONE = 16208;
175/// got a data error -- remain here until reset
176pub const BAD = 16209;
177/// got an inflate() memory error -- remain here until reset
178pub const MEM = 16210;
179/// looking for synchronization bytes to restart inflate() */
180pub const SYNC = 16211;
181
182/// inflate() uses a state machine to process as much input data and generate as
183/// much output data as possible before returning. The state machine is
184/// structured roughly as follows:
185///
186/// for (;;) switch (state) {
187/// ...
188/// case STATEn:
189/// if (not enough input data or output space to make progress)
190/// return;
191/// ... make progress ...
192/// state = STATEm;
193/// break;
194/// ...
195/// }
196///
197/// so when inflate() is called again, the same case is attempted again, and
198/// if the appropriate resources are provided, the machine proceeds to the
199/// next state. The NEEDBITS() macro is usually the way the state evaluates
200/// whether it can proceed or should return. NEEDBITS() does the return if
201/// the requested bits are not available. The typical use of the BITS macros
202/// is:
203///
204/// NEEDBITS(n);
205/// ... do something with BITS(n) ...
206/// DROPBITS(n);
207///
208/// where NEEDBITS(n) either returns from inflate() if there isn't enough
209/// input left to load n bits into the accumulator, or it continues. BITS(n)
210/// gives the low n bits in the accumulator. When done, DROPBITS(n) drops
211/// the low n bits off the accumulator. INITBITS() clears the accumulator
212/// and sets the number of available bits to zero. BYTEBITS() discards just
213/// enough bits to put the accumulator on a byte boundary. After BYTEBITS()
214/// and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
215///
216/// NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
217/// if there is no input available. The decoding of variable length codes uses
218/// PULLBYTE() directly in order to pull just enough bytes to decode the next
219/// code, and no more.
220///
221/// Some states loop until they get enough input, making sure that enough
222/// state information is maintained to continue the loop where it left off
223/// if NEEDBITS() returns in the loop. For example, want, need, and keep
224/// would all have to actually be part of the saved state in case NEEDBITS()
225/// returns:
226///
227/// case STATEw:
228/// while (want < need) {
229/// NEEDBITS(n);
230/// keep[want++] = BITS(n);
231/// DROPBITS(n);
232/// }
233/// state = STATEx;
234/// case STATEx:
235///
236/// As shown above, if the next state is also the next case, then the break
237/// is omitted.
238///
239/// A state may also return if there is not enough output space available to
240/// complete that state. Those states are copying stored data, writing a
241/// literal byte, and copying a matching string.
242///
243/// When returning, a "goto inf_leave" is used to update the total counters,
244/// update the check value, and determine whether any progress has been made
245/// during that inflate() call in order to return the proper return code.
246/// Progress is defined as a change in either strm->avail_in or strm->avail_out.
247/// When there is a window, goto inf_leave will update the window with the last
248/// output written. If a goto inf_leave occurs in the middle of decompression
249/// and there is no window currently, goto inf_leave will create one and copy
250/// output to the window for the next call of inflate().
251///
252/// In this implementation, the flush parameter of inflate() only affects the
253/// return code (per zlib.h). inflate() always writes as much as possible to
254/// strm->next_out, given the space available and the provided input--the effect
255/// documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
256/// the allocation of and copying into a sliding window until necessary, which
257/// provides the effect documented in zlib.h for Z_FINISH when the entire input
258/// stream available. So the only thing the flush parameter actually does is:
259/// when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
260/// will return Z_BUF_ERROR if it has not reached the end of the stream.
261pub fn inflate(strm: &z_stream, flush: Flush, gunzip: bool) -> %void {
262 // next input
263 var next: &const u8 = undefined;
264 // next output
265 var put: &u8 = undefined;
266
267 // available input and output
268 var have: u16 = undefined;
269 var left: u16 = undefined;
270
271 // bit buffer
272 var hold: u32 = undefined;
273 // bits in bit buffer
274 var bits: u16 = undefined;
275 // save starting available input and output
276 var in: u16 = undefined;
277 var out: u16 = undefined;
278 // number of stored or match bytes to copy
279 var copy: u16 = undefined;
280 // where to copy match bytes from
281 var from: &u8 = undefined;
282 // current decoding table entry
283 var here: code = undefined;
284 // parent table entry
285 var last: code = undefined;
286 // length to copy for repeats, bits to drop
287 var len: u16 = undefined;
288
289 // return code
290 var ret: error = undefined;
291
292 // buffer for gzip header crc calculation
293 var hbuf: [4]u8 = undefined;
294
295 // permutation of code lengths
296 const short_order = []u16 = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
297
298 if (inflateStateCheck(strm) or strm.next_out == Z_NULL or (strm.next_in == Z_NULL and strm.avail_in != 0)) {
299 return error.Z_STREAM_ERROR;
300 }
301
302 var state: &inflate_state = strm.state;
303 if (state.mode == TYPE) {
304 state.mode = TYPEDO; // skip check
305 }
306 put = strm.next_out; \
307 left = strm.avail_out; \
308 next = strm.next_in; \
309 have = strm.avail_in; \
310 hold = state.hold; \
311 bits = state.bits; \
312 in = have;
313 out = left;
314 ret = Z_OK;
315 for (;;)
316 switch (state.mode) {
317 case HEAD:
318 if (state.wrap == 0) {
319 state.mode = TYPEDO;
320 break;
321 }
322 NEEDBITS(16);
323#ifdef GUNZIP
324 if ((state.wrap & 2) && hold == 0x8b1f) { /* gzip header */
325 if (state.wbits == 0)
326 state.wbits = 15;
327 state.check = crc32(0L, Z_NULL, 0);
328 CRC2(state.check, hold);
329 INITBITS();
330 state.mode = FLAGS;
331 break;
332 }
333 state.flags = 0; /* expect zlib header */
334 if (state.head != Z_NULL)
335 state.head.done = -1;
336 if (!(state.wrap & 1) || /* check if zlib header allowed */
337#else
338 if (
339#endif
340 ((BITS(8) << 8) + (hold >> 8)) % 31) {
341 strm.msg = (char *)"incorrect header check";
342 state.mode = BAD;
343 break;
344 }
345 if (BITS(4) != Z_DEFLATED) {
346 strm.msg = (char *)"unknown compression method";
347 state.mode = BAD;
348 break;
349 }
350 DROPBITS(4);
351 len = BITS(4) + 8;
352 if (state.wbits == 0)
353 state.wbits = len;
354 if (len > 15 || len > state.wbits) {
355 strm.msg = (char *)"invalid window size";
356 state.mode = BAD;
357 break;
358 }
359 state.dmax = 1U << len;
360 Tracev((stderr, "inflate: zlib header ok\n"));
361 strm.adler = state.check = adler32(0L, Z_NULL, 0);
362 state.mode = hold & 0x200 ? DICTID : TYPE;
363 INITBITS();
364 break;
365#ifdef GUNZIP
366 case FLAGS:
367 NEEDBITS(16);
368 state.flags = (int)(hold);
369 if ((state.flags & 0xff) != Z_DEFLATED) {
370 strm.msg = (char *)"unknown compression method";
371 state.mode = BAD;
372 break;
373 }
374 if (state.flags & 0xe000) {
375 strm.msg = (char *)"unknown header flags set";
376 state.mode = BAD;
377 break;
378 }
379 if (state.head != Z_NULL)
380 state.head.text = (int)((hold >> 8) & 1);
381 if ((state.flags & 0x0200) && (state.wrap & 4))
382 CRC2(state.check, hold);
383 INITBITS();
384 state.mode = TIME;
385 case TIME:
386 NEEDBITS(32);
387 if (state.head != Z_NULL)
388 state.head.time = hold;
389 if ((state.flags & 0x0200) && (state.wrap & 4))
390 CRC4(state.check, hold);
391 INITBITS();
392 state.mode = OS;
393 case OS:
394 NEEDBITS(16);
395 if (state.head != Z_NULL) {
396 state.head.xflags = (int)(hold & 0xff);
397 state.head.os = (int)(hold >> 8);
398 }
399 if ((state.flags & 0x0200) && (state.wrap & 4))
400 CRC2(state.check, hold);
401 INITBITS();
402 state.mode = EXLEN;
403 case EXLEN:
404 if (state.flags & 0x0400) {
405 NEEDBITS(16);
406 state.length = (unsigned)(hold);
407 if (state.head != Z_NULL)
408 state.head.extra_len = (unsigned)hold;
409 if ((state.flags & 0x0200) && (state.wrap & 4))
410 CRC2(state.check, hold);
411 INITBITS();
412 }
413 else if (state.head != Z_NULL)
414 state.head.extra = Z_NULL;
415 state.mode = EXTRA;
416 case EXTRA:
417 if (state.flags & 0x0400) {
418 copy = state.length;
419 if (copy > have) copy = have;
420 if (copy) {
421 if (state.head != Z_NULL &&
422 state.head.extra != Z_NULL) {
423 len = state.head.extra_len - state.length;
424 zmemcpy(state.head.extra + len, next,
425 len + copy > state.head.extra_max ?
426 state.head.extra_max - len : copy);
427 }
428 if ((state.flags & 0x0200) && (state.wrap & 4))
429 state.check = crc32(state.check, next, copy);
430 have -= copy;
431 next += copy;
432 state.length -= copy;
433 }
434 if (state.length) goto inf_leave;
435 }
436 state.length = 0;
437 state.mode = NAME;
438 case NAME:
439 if (state.flags & 0x0800) {
440 if (have == 0) goto inf_leave;
441 copy = 0;
442 do {
443 len = (unsigned)(next[copy++]);
444 if (state.head != Z_NULL &&
445 state.head.name != Z_NULL &&
446 state.length < state.head.name_max)
447 state.head.name[state.length++] = (Bytef)len;
448 } while (len && copy < have);
449 if ((state.flags & 0x0200) && (state.wrap & 4))
450 state.check = crc32(state.check, next, copy);
451 have -= copy;
452 next += copy;
453 if (len) goto inf_leave;
454 }
455 else if (state.head != Z_NULL)
456 state.head.name = Z_NULL;
457 state.length = 0;
458 state.mode = COMMENT;
459 case COMMENT:
460 if (state.flags & 0x1000) {
461 if (have == 0) goto inf_leave;
462 copy = 0;
463 do {
464 len = (unsigned)(next[copy++]);
465 if (state.head != Z_NULL &&
466 state.head.comment != Z_NULL &&
467 state.length < state.head.comm_max)
468 state.head.comment[state.length++] = (Bytef)len;
469 } while (len && copy < have);
470 if ((state.flags & 0x0200) && (state.wrap & 4))
471 state.check = crc32(state.check, next, copy);
472 have -= copy;
473 next += copy;
474 if (len) goto inf_leave;
475 }
476 else if (state.head != Z_NULL)
477 state.head.comment = Z_NULL;
478 state.mode = HCRC;
479 case HCRC:
480 if (state.flags & 0x0200) {
481 NEEDBITS(16);
482 if ((state.wrap & 4) && hold != (state.check & 0xffff)) {
483 strm.msg = (char *)"header crc mismatch";
484 state.mode = BAD;
485 break;
486 }
487 INITBITS();
488 }
489 if (state.head != Z_NULL) {
490 state.head.hcrc = (int)((state.flags >> 9) & 1);
491 state.head.done = 1;
492 }
493 strm.adler = state.check = crc32(0L, Z_NULL, 0);
494 state.mode = TYPE;
495 break;
496#endif
497 case DICTID:
498 NEEDBITS(32);
499 strm.adler = state.check = ZSWAP32(hold);
500 INITBITS();
501 state.mode = DICT;
502 case DICT:
503 if (state.havedict == 0) {
504 strm.next_out = put; \
505 strm.avail_out = left; \
506 strm.next_in = next; \
507 strm.avail_in = have; \
508 state.hold = hold; \
509 state.bits = bits; \
510 return Z_NEED_DICT;
511 }
512 strm.adler = state.check = adler32(0L, Z_NULL, 0);
513 state.mode = TYPE;
514 case TYPE:
515 if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
516 case TYPEDO:
517 if (state.last) {
518 BYTEBITS();
519 state.mode = CHECK;
520 break;
521 }
522 NEEDBITS(3);
523 state.last = BITS(1);
524 DROPBITS(1);
525 switch (BITS(2)) {
526 case 0: /* stored block */
527 Tracev((stderr, "inflate: stored block%s\n",
528 state.last ? " (last)" : ""));
529 state.mode = STORED;
530 break;
531 case 1: /* fixed block */
532 fixedtables(state);
533 Tracev((stderr, "inflate: fixed codes block%s\n",
534 state.last ? " (last)" : ""));
535 state.mode = LEN_; /* decode codes */
536 if (flush == Z_TREES) {
537 DROPBITS(2);
538 goto inf_leave;
539 }
540 break;
541 case 2: /* dynamic block */
542 Tracev((stderr, "inflate: dynamic codes block%s\n",
543 state.last ? " (last)" : ""));
544 state.mode = TABLE;
545 break;
546 case 3:
547 strm.msg = (char *)"invalid block type";
548 state.mode = BAD;
549 }
550 DROPBITS(2);
551 break;
552 case STORED:
553 BYTEBITS(); /* go to byte boundary */
554 NEEDBITS(32);
555 if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
556 strm.msg = (char *)"invalid stored block lengths";
557 state.mode = BAD;
558 break;
559 }
560 state.length = (unsigned)hold & 0xffff;
561 Tracev((stderr, "inflate: stored length %u\n",
562 state.length));
563 INITBITS();
564 state.mode = COPY_;
565 if (flush == Z_TREES) goto inf_leave;
566 case COPY_:
567 state.mode = COPY;
568 case COPY:
569 copy = state.length;
570 if (copy) {
571 if (copy > have) copy = have;
572 if (copy > left) copy = left;
573 if (copy == 0) goto inf_leave;
574 zmemcpy(put, next, copy);
575 have -= copy;
576 next += copy;
577 left -= copy;
578 put += copy;
579 state.length -= copy;
580 break;
581 }
582 Tracev((stderr, "inflate: stored end\n"));
583 state.mode = TYPE;
584 break;
585 case TABLE:
586 NEEDBITS(14);
587 state.nlen = BITS(5) + 257;
588 DROPBITS(5);
589 state.ndist = BITS(5) + 1;
590 DROPBITS(5);
591 state.ncode = BITS(4) + 4;
592 DROPBITS(4);
593#ifndef PKZIP_BUG_WORKAROUND
594 if (state.nlen > 286 || state.ndist > 30) {
595 strm.msg = (char *)"too many length or distance symbols";
596 state.mode = BAD;
597 break;
598 }
599#endif
600 Tracev((stderr, "inflate: table sizes ok\n"));
601 state.have = 0;
602 state.mode = LENLENS;
603 case LENLENS:
604 while (state.have < state.ncode) {
605 NEEDBITS(3);
606 state.lens[order[state.have++]] = (unsigned short)BITS(3);
607 DROPBITS(3);
608 }
609 while (state.have < 19)
610 state.lens[order[state.have++]] = 0;
611 state.next = state.codes;
612 state.lencode = (const code FAR *)(state.next);
613 state.lenbits = 7;
614 ret = inflate_table(CODES, state.lens, 19, &(state.next),
615 &(state.lenbits), state.work);
616 if (ret) {
617 strm.msg = (char *)"invalid code lengths set";
618 state.mode = BAD;
619 break;
620 }
621 Tracev((stderr, "inflate: code lengths ok\n"));
622 state.have = 0;
623 state.mode = CODELENS;
624 case CODELENS:
625 while (state.have < state.nlen + state.ndist) {
626 for (;;) {
627 here = state.lencode[BITS(state.lenbits)];
628 if ((unsigned)(here.bits) <= bits) break;
629 PULLBYTE();
630 }
631 if (here.val < 16) {
632 DROPBITS(here.bits);
633 state.lens[state.have++] = here.val;
634 }
635 else {
636 if (here.val == 16) {
637 NEEDBITS(here.bits + 2);
638 DROPBITS(here.bits);
639 if (state.have == 0) {
640 strm.msg = (char *)"invalid bit length repeat";
641 state.mode = BAD;
642 break;
643 }
644 len = state.lens[state.have - 1];
645 copy = 3 + BITS(2);
646 DROPBITS(2);
647 }
648 else if (here.val == 17) {
649 NEEDBITS(here.bits + 3);
650 DROPBITS(here.bits);
651 len = 0;
652 copy = 3 + BITS(3);
653 DROPBITS(3);
654 }
655 else {
656 NEEDBITS(here.bits + 7);
657 DROPBITS(here.bits);
658 len = 0;
659 copy = 11 + BITS(7);
660 DROPBITS(7);
661 }
662 if (state.have + copy > state.nlen + state.ndist) {
663 strm.msg = (char *)"invalid bit length repeat";
664 state.mode = BAD;
665 break;
666 }
667 while (copy--)
668 state.lens[state.have++] = (unsigned short)len;
669 }
670 }
671
672 /* handle error breaks in while */
673 if (state.mode == BAD) break;
674
675 /* check for end-of-block code (better have one) */
676 if (state.lens[256] == 0) {
677 strm.msg = (char *)"invalid code -- missing end-of-block";
678 state.mode = BAD;
679 break;
680 }
681
682 /* build code tables -- note: do not change the lenbits or distbits
683 values here (9 and 6) without reading the comments in inftrees.h
684 concerning the ENOUGH constants, which depend on those values */
685 state.next = state.codes;
686 state.lencode = (const code FAR *)(state.next);
687 state.lenbits = 9;
688 ret = inflate_table(LENS, state.lens, state.nlen, &(state.next),
689 &(state.lenbits), state.work);
690 if (ret) {
691 strm.msg = (char *)"invalid literal/lengths set";
692 state.mode = BAD;
693 break;
694 }
695 state.distcode = (const code FAR *)(state.next);
696 state.distbits = 6;
697 ret = inflate_table(DISTS, state.lens + state.nlen, state.ndist,
698 &(state.next), &(state.distbits), state.work);
699 if (ret) {
700 strm.msg = (char *)"invalid distances set";
701 state.mode = BAD;
702 break;
703 }
704 Tracev((stderr, "inflate: codes ok\n"));
705 state.mode = LEN_;
706 if (flush == Z_TREES) goto inf_leave;
707 case LEN_:
708 state.mode = LEN;
709 case LEN:
710 if (have >= 6 && left >= 258) {
711 strm.next_out = put; \
712 strm.avail_out = left; \
713 strm.next_in = next; \
714 strm.avail_in = have; \
715 state.hold = hold; \
716 state.bits = bits; \
717
718 inflate_fast(strm, out);
719
720 put = strm.next_out; \
721 left = strm.avail_out; \
722 next = strm.next_in; \
723 have = strm.avail_in; \
724 hold = state.hold; \
725 bits = state.bits; \
726 if (state.mode == TYPE)
727 state.back = -1;
728 break;
729 }
730 state.back = 0;
731 for (;;) {
732 here = state.lencode[BITS(state.lenbits)];
733 if ((unsigned)(here.bits) <= bits) break;
734 PULLBYTE();
735 }
736 if (here.op && (here.op & 0xf0) == 0) {
737 last = here;
738 for (;;) {
739 here = state.lencode[last.val +
740 (BITS(last.bits + last.op) >> last.bits)];
741 if ((unsigned)(last.bits + here.bits) <= bits) break;
742 PULLBYTE();
743 }
744 DROPBITS(last.bits);
745 state.back += last.bits;
746 }
747 DROPBITS(here.bits);
748 state.back += here.bits;
749 state.length = (unsigned)here.val;
750 if ((int)(here.op) == 0) {
751 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
752 "inflate: literal '%c'\n" :
753 "inflate: literal 0x%02x\n", here.val));
754 state.mode = LIT;
755 break;
756 }
757 if (here.op & 32) {
758 Tracevv((stderr, "inflate: end of block\n"));
759 state.back = -1;
760 state.mode = TYPE;
761 break;
762 }
763 if (here.op & 64) {
764 strm.msg = (char *)"invalid literal/length code";
765 state.mode = BAD;
766 break;
767 }
768 state.extra = (unsigned)(here.op) & 15;
769 state.mode = LENEXT;
770 case LENEXT:
771 if (state.extra) {
772 NEEDBITS(state.extra);
773 state.length += BITS(state.extra);
774 DROPBITS(state.extra);
775 state.back += state.extra;
776 }
777 Tracevv((stderr, "inflate: length %u\n", state.length));
778 state.was = state.length;
779 state.mode = DIST;
780 case DIST:
781 for (;;) {
782 here = state.distcode[BITS(state.distbits)];
783 if ((unsigned)(here.bits) <= bits) break;
784 PULLBYTE();
785 }
786 if ((here.op & 0xf0) == 0) {
787 last = here;
788 for (;;) {
789 here = state.distcode[last.val +
790 (BITS(last.bits + last.op) >> last.bits)];
791 if ((unsigned)(last.bits + here.bits) <= bits) break;
792 PULLBYTE();
793 }
794 DROPBITS(last.bits);
795 state.back += last.bits;
796 }
797 DROPBITS(here.bits);
798 state.back += here.bits;
799 if (here.op & 64) {
800 strm.msg = (char *)"invalid distance code";
801 state.mode = BAD;
802 break;
803 }
804 state.offset = (unsigned)here.val;
805 state.extra = (unsigned)(here.op) & 15;
806 state.mode = DISTEXT;
807 case DISTEXT:
808 if (state.extra) {
809 NEEDBITS(state.extra);
810 state.offset += BITS(state.extra);
811 DROPBITS(state.extra);
812 state.back += state.extra;
813 }
814#ifdef INFLATE_STRICT
815 if (state.offset > state.dmax) {
816 strm.msg = (char *)"invalid distance too far back";
817 state.mode = BAD;
818 break;
819 }
820#endif
821 Tracevv((stderr, "inflate: distance %u\n", state.offset));
822 state.mode = MATCH;
823 case MATCH:
824 if (left == 0) goto inf_leave;
825 copy = out - left;
826 if (state.offset > copy) { /* copy from window */
827 copy = state.offset - copy;
828 if (copy > state.whave) {
829 if (state.sane) {
830 strm.msg = (char *)"invalid distance too far back";
831 state.mode = BAD;
832 break;
833 }
834#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
835 Trace((stderr, "inflate.c too far\n"));
836 copy -= state.whave;
837 if (copy > state.length) copy = state.length;
838 if (copy > left) copy = left;
839 left -= copy;
840 state.length -= copy;
841 do {
842 *put++ = 0;
843 } while (--copy);
844 if (state.length == 0) state.mode = LEN;
845 break;
846#endif
847 }
848 if (copy > state.wnext) {
849 copy -= state.wnext;
850 from = state.window + (state.wsize - copy);
851 }
852 else
853 from = state.window + (state.wnext - copy);
854 if (copy > state.length) copy = state.length;
855 }
856 else { /* copy from output */
857 from = put - state.offset;
858 copy = state.length;
859 }
860 if (copy > left) copy = left;
861 left -= copy;
862 state.length -= copy;
863 do {
864 *put++ = *from++;
865 } while (--copy);
866 if (state.length == 0) state.mode = LEN;
867 break;
868 case LIT:
869 if (left == 0) goto inf_leave;
870 *put++ = (u8)(state.length);
871 left--;
872 state.mode = LEN;
873 break;
874 case CHECK:
875 if (state.wrap) {
876 NEEDBITS(32);
877 out -= left;
878 strm.total_out += out;
879 state.total += out;
880 if ((state.wrap & 4) && out)
881 strm.adler = state.check =
882 UPDATE(state.check, put - out, out);
883 out = left;
884 if ((state.wrap & 4) && (
885#ifdef GUNZIP
886 state.flags ? hold :
887#endif
888 ZSWAP32(hold)) != state.check) {
889 strm.msg = (char *)"incorrect data check";
890 state.mode = BAD;
891 break;
892 }
893 INITBITS();
894 Tracev((stderr, "inflate: check matches trailer\n"));
895 }
896#ifdef GUNZIP
897 state.mode = LENGTH;
898 case LENGTH:
899 if (state.wrap && state.flags) {
900 NEEDBITS(32);
901 if (hold != (state.total & 0xffffffffUL)) {
902 strm.msg = (char *)"incorrect length check";
903 state.mode = BAD;
904 break;
905 }
906 INITBITS();
907 Tracev((stderr, "inflate: length matches trailer\n"));
908 }
909#endif
910 state.mode = DONE;
911 case DONE:
912 ret = Z_STREAM_END;
913 goto inf_leave;
914 case BAD:
915 ret = Z_DATA_ERROR;
916 goto inf_leave;
917 case MEM:
918 return Z_MEM_ERROR;
919 case SYNC:
920 default:
921 return Z_STREAM_ERROR;
922 }
923
924 /*
925 Return from inflate(), updating the total counts and the check value.
926 If there was no progress during the inflate() call, return a buffer
927 error. Call updatewindow() to create and/or update the window state.
928 Note: a memory error from inflate() is non-recoverable.
929 */
930 inf_leave:
931 strm.next_out = put; \
932 strm.avail_out = left; \
933 strm.next_in = next; \
934 strm.avail_in = have; \
935 state.hold = hold; \
936 state.bits = bits; \
937 if (state.wsize || (out != strm.avail_out && state.mode < BAD &&
938 (state.mode < CHECK || flush != Z_FINISH)))
939 if (updatewindow(strm, strm.next_out, out - strm.avail_out)) {
940 state.mode = MEM;
941 return Z_MEM_ERROR;
942 }
943 in -= strm.avail_in;
944 out -= strm.avail_out;
945 strm.total_in += in;
946 strm.total_out += out;
947 state.total += out;
948 if ((state.wrap & 4) && out)
949 strm.adler = state.check =
950 UPDATE(state.check, strm.next_out - out, out);
951 strm.data_type = (int)state.bits + (state.last ? 64 : 0) +
952 (state.mode == TYPE ? 128 : 0) +
953 (state.mode == LEN_ || state.mode == COPY_ ? 256 : 0);
954 if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
955 ret = Z_BUF_ERROR;
956 return ret;
957}
958
959local int inflateStateCheck(z_stream * strm) {
960 struct inflate_state FAR *state;
961 if (strm == Z_NULL ||
962 strm.zalloc == (alloc_func)0 || strm.zfree == (free_func)0)
963 return 1;
964 state = (struct inflate_state FAR *)strm.state;
965 if (state == Z_NULL || state.strm != strm ||
966 state.mode < HEAD || state.mode > SYNC)
967 return 1;
968 return 0;
969}
test/cases/misc.zig+8
......@@ -538,3 +538,11 @@ export fn writeToVRam() {
538538test "pointer child field" {
539539 assert((&u32).child == u32);
540540}
541
542const OpaqueA = @OpaqueType();
543const OpaqueB = @OpaqueType();
544test "@OpaqueType" {
545 assert(&OpaqueA != &OpaqueB);
546 assert(mem.eql(u8, @typeName(OpaqueA), "OpaqueA"));
547 assert(mem.eql(u8, @typeName(OpaqueB), "OpaqueB"));
548}
test/compile_errors.zig+11
......@@ -2079,4 +2079,15 @@ pub fn addCases(cases: &tests.CompileErrorContext) {
20792079 ".tmp_source.zig:5:5: error: @setEvalBranchQuota must be called from the top of the comptime stack",
20802080 ".tmp_source.zig:2:8: note: called from here",
20812081 ".tmp_source.zig:1:10: note: called from here");
2082
2083 cases.add("wrong pointer implicitly casted to pointer to @OpaqueType()",
2084 \\const Derp = @OpaqueType();
2085 \\extern fn bar(d: &Derp);
2086 \\export fn foo() {
2087 \\ const x = u8(1);
2088 \\ bar(@ptrCast(&c_void, &x));
2089 \\}
2090 ,
2091 ".tmp_source.zig:5:9: error: expected type '&Derp', found '&c_void'");
2092
20822093}
test/parseh.zig+33-19
......@@ -21,6 +21,16 @@ pub fn addCases(cases: &tests.ParseHContext) {
2121 \\pub extern fn foo() -> noreturn;
2222 );
2323
24 cases.add("simple function",
25 \\int abs(int a) {
26 \\ return a < 0 ? -a : a;
27 \\}
28 ,
29 \\export fn abs(a: c_int) -> c_int {
30 \\ return if (a < 0) -a else a;
31 \\}
32 );
33
2434 cases.add("enums",
2535 \\enum Foo {
2636 \\ FooA,
......@@ -34,13 +44,13 @@ pub fn addCases(cases: &tests.ParseHContext) {
3444 \\ @"1",
3545 \\};
3646 ,
37 \\pub const FooA = 0;
47 \\pub const FooA = enum_Foo.A;
3848 ,
39 \\pub const FooB = 1;
49 \\pub const FooB = enum_Foo.B;
4050 ,
41 \\pub const Foo1 = 2;
51 \\pub const Foo1 = enum_Foo.@"1";
4252 ,
43 \\pub const Foo = enum_Foo
53 \\pub const Foo = enum_Foo;
4454 );
4555
4656 cases.add("restrict -> noalias",
......@@ -84,9 +94,9 @@ pub fn addCases(cases: &tests.ParseHContext) {
8494 \\ B,
8595 \\};
8696 ,
87 \\pub const BarA = 0;
97 \\pub const BarA = enum_Bar.A;
8898 ,
89 \\pub const BarB = 1;
99 \\pub const BarB = enum_Bar.B;
90100 ,
91101 \\pub extern fn func(a: ?&struct_Foo, b: ?&?&enum_Bar);
92102 ,
......@@ -180,7 +190,7 @@ pub fn addCases(cases: &tests.ParseHContext) {
180190 ,
181191 \\pub const Foo = c_void;
182192 ,
183 \\pub extern fn fun(a: ?&c_void);
193 \\pub extern fn fun(a: ?&Foo) -> Foo;
184194 );
185195
186196 cases.add("generate inline func for #define global extern fn",
......@@ -192,17 +202,21 @@ pub fn addCases(cases: &tests.ParseHContext) {
192202 ,
193203 \\pub extern var fn_ptr: ?extern fn();
194204 ,
195 \\pub fn foo();
205 \\pub inline fn foo() {
206 \\ ??fn_ptr()
207 \\}
196208 ,
197209 \\pub extern var fn_ptr2: ?extern fn(c_int, f32) -> u8;
198210 ,
199 \\pub fn bar(arg0: c_int, arg1: f32) -> u8;
211 \\pub inline fn bar(arg0: c_int, arg1: f32) -> u8 {
212 \\ ??fn_ptr2(arg0, arg1)
213 \\}
200214 );
201215
202216 cases.add("#define string",
203217 \\#define foo "a string"
204218 ,
205 \\pub const foo: &const u8 = &(c str lit);
219 \\pub const foo = c"a string";
206220 );
207221
208222 cases.add("__cdecl doesn't mess up function pointers",
......@@ -220,43 +234,43 @@ pub fn addCases(cases: &tests.ParseHContext) {
220234 cases.add("u integer suffix after hex literal",
221235 \\#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
222236 ,
223 \\pub const SDL_INIT_VIDEO: c_uint = 32;
237 \\pub const SDL_INIT_VIDEO = c_uint(32);
224238 );
225239
226240 cases.add("l integer suffix after hex literal",
227241 \\#define SDL_INIT_VIDEO 0x00000020l /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
228242 ,
229 \\pub const SDL_INIT_VIDEO: c_long = 32;
243 \\pub const SDL_INIT_VIDEO = c_long(32);
230244 );
231245
232246 cases.add("ul integer suffix after hex literal",
233247 \\#define SDL_INIT_VIDEO 0x00000020ul /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
234248 ,
235 \\pub const SDL_INIT_VIDEO: c_ulong = 32;
249 \\pub const SDL_INIT_VIDEO = c_ulong(32);
236250 );
237251
238252 cases.add("lu integer suffix after hex literal",
239253 \\#define SDL_INIT_VIDEO 0x00000020lu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
240254 ,
241 \\pub const SDL_INIT_VIDEO: c_ulong = 32;
255 \\pub const SDL_INIT_VIDEO = c_ulong(32);
242256 );
243257
244258 cases.add("ll integer suffix after hex literal",
245259 \\#define SDL_INIT_VIDEO 0x00000020ll /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
246260 ,
247 \\pub const SDL_INIT_VIDEO: c_longlong = 32;
261 \\pub const SDL_INIT_VIDEO = c_longlong(32);
248262 );
249263
250264 cases.add("ull integer suffix after hex literal",
251265 \\#define SDL_INIT_VIDEO 0x00000020ull /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
252266 ,
253 \\pub const SDL_INIT_VIDEO: c_ulonglong = 32;
267 \\pub const SDL_INIT_VIDEO = c_ulonglong(32);
254268 );
255269
256270 cases.add("llu integer suffix after hex literal",
257271 \\#define SDL_INIT_VIDEO 0x00000020llu /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */
258272 ,
259 \\pub const SDL_INIT_VIDEO: c_ulonglong = 32;
273 \\pub const SDL_INIT_VIDEO = c_ulonglong(32);
260274 );
261275
262276 cases.add("zig keywords in C code",
......@@ -276,9 +290,9 @@ pub fn addCases(cases: &tests.ParseHContext) {
276290 \\#define FOO2 "aoeu\0234 derp"
277291 \\#define FOO_CHAR '\077'
278292 ,
279 \\pub const FOO: &const u8 = &(c str lit);
293 \\pub const FOO = c"aoeu\x13 derp";
280294 ,
281 \\pub const FOO2: &const u8 = &(c str lit);
295 \\pub const FOO2 = c"aoeu\x134 derp";
282296 ,
283297 \\pub const FOO_CHAR = 63;
284298 );