As you use each individual weapon it ranks up. As it ranks up you unlock more attachments for it. This guide explains when and why a weapon levels up and when you unlock new attachments for the weapon.
At the end of this guide there is a YouTube video which contains a visual version of this guide.
Each time you earn score with your weapon you gain more weapon experience towards the next rank. So when you shoot someone, take down air support or get an assist your weapon gains experience towards ranking up. Experience from score streaks or equipment or any other source do not count towards you weapon experience. Challenges specific to the weapon, such as camo challenges, gain weapon experience.
Each time you rank up a weapon a new attachment unlocks. The number of attachments determines how high a weapon’s rank can be, and I am fairly certain that each individual weapon within a type of weapon, like assault rifles, have the same number of ranks as the rest in its class.