Could anyone teach me why unity allows code written like this?
"allows" means texture declaration is allowed in cbuffer declaration scope without error, which should be impossible, as we expand the macro it is nonsense to have a Texture2D _MainTex (and the sampler) inside cbuffer UnityPerMaterial {...} in standard HLSL.
CBUFFER_START (UnityPerMaterial)
TEXTURE2D (_MainTex);
SAMPLER (sampler_MainTex);
float4 _MainTex_ST;
CBUFFER_END